file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
sequence
attention_mask
sequence
labels
sequence
pragma solidity ^0.4.23; import "./ERC725.sol"; import "./ERC735.sol"; import "../common/SignUtils.sol"; /** * @title Self sovereign Identity * @author Ricardo Guilherme Schmidt (Status Research & Development GmbH) */ contract Identity is SignUtils, ERC725, ERC735 { uint256 public nonce; //not approved transactions reserve nonce address public recovery; //if defined can change salt and add a new key uint256 salt; //used for disabling all authorizations at once //used internally, store index of keys, claims and array elements position mapping (bytes32 => uint256) indexes; mapping (bytes32 => Key) keys; //used for quering by other contracts mapping (bytes32 => bool) isKeyPurpose; //used for authorization mapping (bytes32 => bytes32[]) keysByPurpose; //used for listing mapping (uint256 => Transaction) pendingTx; //used for multisig mapping (uint256 => uint256) purposeThreshold; //configure multisig mapping (bytes32 => Claim) claims; //used for quering by other contracts mapping (uint256 => bytes32[]) claimsByType; //used for listing struct Transaction { uint256 approverCount; //amount of approvals address to; uint256 value; bytes data; mapping(bytes32 => bool) approvals; //used for no key double approving } /** * @notice requires called by identity itself, otherwise forward to execute process */ modifier managementOnly { if(msg.sender == address(this)) { //call passed multisig process _; } else { //request execution keyRequestExecute(keccak256(abi.encode(msg.sender)), address(this), 0, msg.data); } } /** * @notice requires called by recovery address */ modifier recoveryOnly { require( msg.sender == recovery ); _; } /** * @notice requires `_signature` from a `_key` with `_messageHash` * @param _key key expected out from `_signature` of `_messageHash` * @param _messageHash message signed in `_signature` by `_key` * @param _signature `_messageHash` signed by `_key` */ modifier keyMessageSigned ( bytes32 _key, bytes32 _messageHash, bytes _signature ) { require(_key == keccak256(abi.encode(recoverAddress(getSignHash(_messageHash),_signature),salt))); _; } /** * @notice constructor builds identity with provided `_keys` * or uses `msg.sender` as first MANAGEMENT + ACTION key * @param _keys Keys to add * @param _purposes `_keys` corresponding purposes * @param _types `_keys` corresponding types * @param _managerThreshold how much keys needs to sign management calls * @param _actorThreshold how much keys need to sign action management calls * @param _recoveryContract Option to initialize with recovery defined */ constructor( bytes32[] _keys, uint256[] _purposes, uint256[] _types, uint256 _managerThreshold, uint256 _actorThreshold, address _recoveryContract ) public { bytes32[] memory initKeys = _keys; uint256[] memory initPurposes = _purposes; uint256[] memory initTypes = _types; uint256 managerThreshold = _managerThreshold; if (_keys.length == 0) { initKeys = new bytes32[](2); initPurposes = new uint256[](2); initTypes = new uint256[](2); initKeys[0] = keccak256(abi.encode(msg.sender)); initKeys[1] = initKeys[0]; initPurposes[0] = MANAGEMENT_KEY; initPurposes[1] = ACTION_KEY; initTypes[0] = 0; initTypes[1] = 0; managerThreshold = 1; } constructIdentity( initKeys, initPurposes, initTypes, managerThreshold, _actorThreshold, _recoveryContract ); } /** * @notice default function allows deposit of ETH */ function () external //enables default method payable //accepts ether { //nothing *here* } //////////////// // Execute calls and multisig approval //////////////// /** * @notice execute (or request) call * @param _to destination of call * @param _value amount of ETH in call * @param _data data * @return nonce of the execution */ function execute( address _to, uint256 _value, bytes _data ) public returns (uint256 executionId) { executionId = keyRequestExecute(keccak256(abi.encode(msg.sender)), _to, _value, _data); } /** * @notice approve a multisigned execution * @param _executionId unique id multisig transaction * @param _approval approve (true) or reject (false) * @return true if approved */ function approve(uint256 _executionId, bool _approval) public returns (bool success) { return keyApproveExecute(keccak256(abi.encode(msg.sender)), _executionId, _approval); } //////////////// // Message Signed functions //////////////// /** * @notice execute (or request) call using ethereum signed message as authorization * @param _to destination of call * @param _value amount of ETH in call * @param _data data * @param _nonce current nonce * @param _key key authorizing the call * @param _signature signature of key * @return nonce of the execution */ function executeMessageSigned( address _to, uint256 _value, bytes _data, uint256 _nonce, bytes32 _key, bytes _signature ) public keyMessageSigned( _key, keccak256( abi.encode( address(this), bytes4(keccak256(abi.encode("execute(address,uint256,bytes)"))), _to, _value, _data, _nonce ) ), _signature ) returns (uint256 executionId) { require(_nonce == nonce); executionId = keyRequestExecute(_key, _to, _value, _data); } /** * @notice approve a multisigned execution using ethereum signed message as authorization * @param _executionId unique id multisig transaction * @param _approval approve (true) or reject (false) * @param _key key authorizing the call * @param _signature signature of key * @return true if approved */ function approveMessageSigned( uint256 _executionId, bool _approval, bytes32 _key, bytes _signature ) public keyMessageSigned( _key, keccak256( abi.encode( address(this), bytes4(keccak256("approve(uint256,bool)")), _executionId, _approval ) ), _signature ) returns (bool success) { return keyApproveExecute(_key, _executionId, _approval); } //////////////// // Management functions //////////////// /** * @notice Adds a _key to the identity. The `_purpose` * @param _key key hash being added * @param _purpose specifies the purpose of key. * @param _type inform type of key * @return true if success */ function addKey( bytes32 _key, uint256 _purpose, uint256 _type ) public managementOnly returns (bool success) { storeKey(_key, _purpose, _type, salt); return true; } /** * @notice Replaces one `_oldKey` with other `_newKey` * @param _oldKey key to remove * @param _newKey key to add * @param _newType inform type of `_newKey` * @return true if success */ function replaceKey( bytes32 _oldKey, bytes32 _newKey, uint256 _newType ) public managementOnly returns (bool success) { return overwriteKey(_oldKey, _newKey, _newType, salt); } /** * @notice Removes `_purpose` of `_key` * @param _key key to remove * @param _purpose purpose to remove * @return true if success */ function removeKey( bytes32 _key, uint256 _purpose ) public managementOnly returns (bool success) { dropKeyPurpose(_key, _purpose, salt); return true; } /** * @notice Defines minimum approval required by key type * @param _purpose select purpose * @param _minimumApprovals select how much signatures needed */ function setMinimumApprovalsByKeyType( uint256 _purpose, uint256 _minimumApprovals ) public managementOnly { require(_minimumApprovals > 0); require(_minimumApprovals <= keysByPurpose[keccak256(abi.encode(_purpose, salt))].length); purposeThreshold[_purpose] = _minimumApprovals; } /** * @notice Defines recovery address. This is one time only action. * @param _recoveryContract address of recovery contract */ function setupRecovery(address _recoveryContract) public managementOnly { require(recovery == address(0)); recovery = _recoveryContract; } //////////////// // Claim related //////////////// /** * @notice Requests the ADDITION or the CHANGE of a claim from an `_issuer`. * Claims can requested to be added by anybody, including the claim holder itself (self issued). * @param _topic claim subject/type index * @param _scheme signature type * @param _signature Signed message of the following structure: `keccak256(address identityHolder_address, uint256 topic, bytes data)`. * @param _issuer address of msg signer or contract * @param _data information * @param _uri uri * @return claimHash: `keccak256(_issuer, _topic)` */ function addClaim( uint256 _topic, uint256 _scheme, address _issuer, bytes _signature, bytes _data, string _uri ) public returns (bytes32 claimHash) { claimHash = keccak256(abi.encode(_issuer, _topic)); if (msg.sender == address(this)) { if (claims[claimHash].topic > 0) { updateClaim(claimHash, _topic, _scheme, _issuer, _signature, _data, _uri); } else { storeClaim(claimHash, _topic, _scheme, _issuer, _signature, _data, _uri); } } else { require(keyHasPurpose(keccak256(abi.encode(msg.sender)), CLAIM_SIGNER_KEY)); keyRequestApproval(nonce++, 0, address(this), 0, msg.data); emit ClaimRequested( claimHash, _topic, _scheme, _issuer, _signature, _data, _uri ); } } /** * @notice Removes a claim. Can only be removed by the claim issuer, or the claim holder itself. * @param _claimHash claimId keccak256(address issuer_address + uint256 topic) * @return true if success */ function removeClaim(bytes32 _claimHash) public returns (bool success) { Claim memory c = claims[_claimHash]; if (msg.sender != address(this)) { require(msg.sender == c.issuer); } uint256 claimIdTopicPos = indexes[_claimHash]; delete indexes[_claimHash]; bytes32[] storage claimsTopicArr = claimsByType[c.topic]; bytes32 replacer = claimsTopicArr[claimsTopicArr.length - 1]; claimsTopicArr[claimIdTopicPos] = replacer; indexes[replacer] = claimIdTopicPos; delete claims[_claimHash]; claimsTopicArr.length--; emit ClaimRemoved(_claimHash, c.topic, c.scheme, c.issuer, c.signature, c.data, c.uri); return true; } //////////////// // Recovery methods //////////////// /** * @notice Increase salt for hashing storage pointer of keys and add `_recoveryNewKey` * @param _recoveryNewKey new key being defined */ function recoveryReset(bytes32 _recoveryNewKey) public recoveryOnly { salt++; storeKey(_recoveryNewKey, MANAGEMENT_KEY, 0, salt); storeKey(_recoveryNewKey, ACTION_KEY, 0, salt); purposeThreshold[MANAGEMENT_KEY] = 1; } //////////////// // Public Views //////////////// /** * @notice Query a key * @param _key key to select * @return full key data, if present in the identity */ function getKey( bytes32 _key ) public view returns(uint256[] purposes, uint256 keyType, bytes32 key) { Key storage myKey = keys[keccak256(abi.encode(_key, salt))]; return (myKey.purposes, myKey.keyType, myKey.key); } /** * @notice Check key purpose * @param _key key to select * @param _purpose purpose to select * @return true if a key has is present and has the given purpose */ function keyHasPurpose(bytes32 _key, uint256 _purpose) public view returns (bool exists) { return isKeyPurpose[keccak256(abi.encode(keccak256(abi.encode(_key, salt)), _purpose))]; } /** * @notice Read array of purposes from key `_key` * @param _key key to select * @return array of key's purposes */ function getKeyPurpose(bytes32 _key) public view returns(uint256[] purpose) { return keys[keccak256(abi.encode(_key, salt))].purposes; } /** * @notice Read keys defined for a purpose * @param _purpose purpose to select * @return array of keys */ function getKeysByPurpose(uint256 _purpose) public view returns(bytes32[]) { return keysByPurpose[keccak256(abi.encode(_purpose, salt))]; } /** * @notice Gets a claim by its hash * @param _claimHash claimHash to select * @return all claim information */ function getClaim(bytes32 _claimHash) public view returns( uint256 topic, uint256 scheme, address issuer, bytes signature, bytes data, string uri ) { Claim memory _claim = claims[_claimHash]; return (_claim.topic, _claim.scheme, _claim.issuer, _claim.signature, _claim.data, _claim.uri); } /** * @notice Get claims list by defined topic * @param _topic topic to select * @return array of claimhashes */ function getClaimIdsByTopic(uint256 _topic) public view returns(bytes32[] claimHash) { return claimsByType[_topic]; } //////////////// // Internal methods //////////////// /** * @dev initialize identity * @param _keys array of keys, length need to be greater than zero * @param _purposes array of keys's purposes, length need == keys length * @param _types array of key's types, length need == keys length * @param _managerThreshold how much managers need to approve self call, need to be at least managers added * @param _actorThreshold how much actors need to approve external call * @param _recoveryContract optionally initialize with recovery contract */ function constructIdentity( bytes32[] _keys, uint256[] _purposes, uint256[] _types, uint256 _managerThreshold, uint256 _actorThreshold, address _recoveryContract ) internal { uint256 _salt = salt; uint len = _keys.length; require(len > 0); require(purposeThreshold[MANAGEMENT_KEY] == 0, "Already Initialized (1)"); require(keysByPurpose[keccak256(abi.encode(MANAGEMENT_KEY, _salt))].length == 0, "Already Initialized (2)"); require(len == _purposes.length, "Wrong _purposes lenght"); uint managersAdded = 0; for(uint i = 0; i < len; i++) { uint256 _purpose = _purposes[i]; storeKey(_keys[i], _purpose, _types[i], _salt); if(_purpose == MANAGEMENT_KEY) { managersAdded++; } } require(_managerThreshold <= managersAdded, "managers added is less then required"); purposeThreshold[MANAGEMENT_KEY] = _managerThreshold; purposeThreshold[ACTION_KEY] = _actorThreshold; recovery = _recoveryContract; } /** * @dev previously authenticated `_key` request execution * @return execution id of executed or pending multisig */ function keyRequestExecute( bytes32 _key, address _to, uint256 _value, bytes _data ) internal returns (uint256 executionId) { // checks if is self call (management functions) uint256 requiredPurpose = _to == address(this) ? MANAGEMENT_KEY : ACTION_KEY; require(keyHasPurpose(_key, requiredPurpose)); executionId = nonce++; if (purposeThreshold[requiredPurpose] == 1) { //only one key is needed, dont need approval executeTransaction(executionId, _to, _value, _data); } else { //more confirmations are required keyRequestApproval(executionId, _key, _to, _value, _data); } } /** * @dev previously authenticated `_key` request approval and approve * @param _key key that approves */ function keyRequestApproval( uint256 _executionId, bytes32 _key, address _to, uint256 _value, bytes _data ) internal { pendingTx[_executionId] = Transaction({ approverCount: _key == 0 ? 0 : 1, to: _to, value: _value, data: _data }); if (_key != 0) { pendingTx[_executionId].approvals[_key] = true; } emit ExecutionRequested(_executionId, _to, _value, _data); } /** * @dev previously authenticated `_key` approve execute * @param _key key that approves * @return true if approved */ function keyApproveExecute( bytes32 _key, uint256 _executionId, bool _approval ) internal returns(bool success) //(?) should return approved instead of success? { Transaction memory approvedTx = pendingTx[_executionId]; require(approvedTx.approverCount > 0); //requires a valid pending tx uint256 requiredKeyPurpose = approvedTx.to == address(this) ? MANAGEMENT_KEY : ACTION_KEY; require(keyHasPurpose(_key, requiredKeyPurpose)); require(pendingTx[_executionId].approvals[_key] != _approval); //require changing approval if (_approval) { if (approvedTx.approverCount + 1 == purposeThreshold[requiredKeyPurpose]) { //last one aproving! delete pendingTx[_executionId]; //prevent reexecution by deleting emit Approved(_executionId, _approval); //approved! return executeTransaction(_executionId, approvedTx.to, approvedTx.value, approvedTx.data); } else { //need more approving pendingTx[_executionId].approvals[_key] = true; pendingTx[_executionId].approverCount++; } } else { //woops, user changed mind, disapprove it now delete pendingTx[_executionId].approvals[_key]; if (pendingTx[_executionId].approverCount == 1) { //is last approval delete pendingTx[_executionId]; emit Approved(_executionId, _approval); //not approved (removed) } else { pendingTx[_executionId].approverCount--; //one less approver now } } } /** * @dev contract execute transactio * @return true if call didnt throw */ function executeTransaction( uint256 _executionId, address _to, uint256 _value, bytes _data ) internal returns(bool success) { success = _to.call.value(_value)(_data); if (success) { emit Executed(_executionId, _to, _value, _data); } else { emit ExecutionFailed(_executionId, _to, _value, _data); } } //////////////// // Private methods //////////////// /** * @dev store a new key or push purpose of already exists * @param _salt current salt * @return true if success */ function storeKey( bytes32 _key, uint256 _purpose, uint256 _type, uint256 _salt ) private returns(bool success) { require(_key != 0); require(_purpose != 0); bytes32 keySaltedHash = keccak256(abi.encode(_key, _salt)); //key storage pointer bytes32 saltedKeyPurposeHash = keccak256(abi.encode(keySaltedHash, _purpose)); // accounts by purpose hash element index pointer require(!isKeyPurpose[saltedKeyPurposeHash]); //cannot add a key already added isKeyPurpose[saltedKeyPurposeHash] = true; //set authorization uint256 keyElementIndex = keysByPurpose[saltedKeyPurposeHash].push(_key) - 1; //add key to list by purpose indexes[saltedKeyPurposeHash] = keyElementIndex; //save index of key in list by purpose if (keys[keySaltedHash].key == 0) { //is a new key uint256[] memory purposes = new uint256[](1); //create new array with first purpose purposes[0] = _purpose; keys[keySaltedHash] = Key(purposes,_type,_key); //add new key } else { uint256 addedPurposeElementIndex = keys[keySaltedHash].purposes.push(_purpose) - 1; //add purpose to key bytes32 keyPurposeSaltedHash = keccak256(abi.encode(_key, _purpose, _salt)); //index of purpose in key pointer indexes[keyPurposeSaltedHash] = addedPurposeElementIndex; //save index } emit KeyAdded(_key, _purpose, _type); return true; } }
prevent reexecution by deleting
delete pendingTx[_executionId];
5,507,131
[ 1, 29150, 283, 16414, 635, 12993, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7734, 1430, 4634, 4188, 63, 67, 16414, 548, 15533, 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 ]
pragma solidity ^0.4.18; contract owned { /* Owner definition. */ address public owner; // Owner address. function owned() internal { owner = msg.sender ; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { owner = newOwner; } } contract token { /* Base token definition. */ string public name; // Name for the token. string public symbol; // Symbol for the token. uint8 public decimals; // Number of decimals of the token. uint256 public totalSupply; // Total of tokens created. // Array containing the balance foreach address. mapping (address => uint256) public balanceOf; // Array containing foreach address, an array containing each approved address and the amount of tokens it can spend. mapping (address => mapping (address => uint256)) public allowance; /* This generates a public event on the blockchain that will notify about a transfer done. */ event Transfer(address indexed from, address indexed to, uint256 value); /* Initializes the contract */ function token(uint256 initialSupply, string tokenName, uint8 decimalUnits, string tokenSymbol) internal { balanceOf[msg.sender] = initialSupply; // Gives the creator all initial tokens. totalSupply = initialSupply; // Update total supply. name = tokenName; // Set the name for display purposes. symbol = tokenSymbol; // Set the symbol for display purposes. decimals = decimalUnits; // Amount of decimals for display purposes. } /* Internal transfer, only can be called by this contract. */ function _transfer(address _from, address _to, uint _value) internal { require(_to != 0x0); // Prevent transfer to 0x0 address. require(balanceOf[_from] > _value); // Check if the sender has enough. require(balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows. balanceOf[_from] -= _value; // Subtract from the sender. balanceOf[_to] += _value; // Add the same to the recipient. Transfer(_from, _to, _value); // Notifies the blockchain about the transfer. } /// @notice Send `_value` tokens to `_to` from your account. /// @param _to The address of the recipient. /// @param _value The amount to send. function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /// @notice Send `_value` tokens to `_to` in behalf of `_from`. /// @param _from The address of the sender. /// @param _to The address of the recipient. /// @param _value The amount to send. function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance. allowance[_from][msg.sender] -= _value; // Updates the allowance array, substracting the amount sent. _transfer(_from, _to, _value); // Makes the transfer. return true; } /// @notice Allows `_spender` to spend a maximum of `_value` tokens in your behalf. /// @param _spender The address authorized to spend. /// @param _value The max amount they can spend. function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; // Adds a new register to allowance, permiting _spender to use _value of your tokens. return true; } } contract PMHToken is owned, token { /* Specific token definition for -HormitechToken-. */ uint256 public sellPrice = 5000000000000000; // Price applied if someone wants to sell a token. uint256 public buyPrice = 10000000000000000; // Price applied if someone wants to buy a token. bool public closeBuy = false; // If true, nobody will be able to buy. bool public closeSell = false; // If true, nobody will be able to sell. uint256 public tokensAvailable = balanceOf[this]; // Number of tokens available for sell. uint256 public solvency = this.balance; // Amount of Ether available to pay sales. uint256 public profit = 0; // Shows the actual profit for the company. address public comisionGetter = 0x70B593f89DaCF6e3BD3e5bD867113FEF0B2ee7aD ; // The address that gets the comisions paid. // added MAR 2018 mapping (address => string ) public emails ; // Array containing the e-mail addresses of the token holders mapping (uint => uint) public dividends ; // for each period in the index, how many weis set for dividends distribution mapping (address => uint[]) public paidDividends ; // for each address, if the period dividend was paid or not and the amount // added MAR 2018 mapping (address => bool) public frozenAccount; // Array containing foreach address if it's frozen or not. /* This generates a public event on the blockchain that will notify about an address being freezed. */ event FrozenFunds(address target, bool frozen); /* This generates a public event on the blockchain that will notify about an addition of Ether to the contract. */ event LogDeposit(address sender, uint amount); /* This generates a public event on the blockchain that will notify about a Withdrawal of Ether from the contract. */ event LogWithdrawal(address receiver, uint amount); /* Initializes the contract */ function PMHToken(uint256 initialSupply, string tokenName, uint8 decimalUnits, string tokenSymbol) public token (initialSupply, tokenName, decimalUnits, tokenSymbol) {} /* Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { require(_to != 0x0); // Prevent transfer to 0x0 address. require(balanceOf[_from] >= _value); // Check if the sender has enough. require(balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows. require(!frozenAccount[_from]); // Check if sender is frozen. require(!frozenAccount[_to]); // Check if recipient is frozen. balanceOf[_from] -= _value; // Subtracts _value tokens from the sender. balanceOf[_to] += _value; // Adds the same amount to the recipient. _updateTokensAvailable(balanceOf[this]); // Update the balance of tokens available if necessary. Transfer(_from, _to, _value); // Notifies the blockchain about the transfer. } function refillTokens(uint256 _value) public onlyOwner{ // Owner sends tokens to the contract. _transfer(msg.sender, this, _value); } /* Overrides basic transfer function due to comision value */ function transfer(address _to, uint256 _value) public { // This function requires a comision value of 0.4% of the market value. uint market_value = _value * sellPrice; uint comision = market_value * 4 / 1000; // The token smart-contract pays comision, else the transfer is not possible. require(this.balance >= comision); comisionGetter.transfer(comision); // Transfers comision to the comisionGetter. _transfer(msg.sender, _to, _value); } /* Overrides basic transferFrom function due to comision value */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance. // This function requires a comision value of 0.4% of the market value. uint market_value = _value * sellPrice; uint comision = market_value * 4 / 1000; // The token smart-contract pays comision, else the transfer is not possible. require(this.balance >= comision); comisionGetter.transfer(comision); // Transfers comision to the comisionGetter. allowance[_from][msg.sender] -= _value; // Updates the allowance array, substracting the amount sent. _transfer(_from, _to, _value); // Makes the transfer. return true; } /* Internal, updates the balance of tokens available. */ function _updateTokensAvailable(uint256 _tokensAvailable) internal { tokensAvailable = _tokensAvailable; } /* Internal, updates the balance of Ether available in order to cover potential sales. */ function _updateSolvency(uint256 _solvency) internal { solvency = _solvency; } /* Internal, updates the profit value */ function _updateProfit(uint256 _increment, bool add) internal{ if (add){ // Increase the profit value profit = profit + _increment; }else{ // Decrease the profit value if(_increment > profit){ profit = 0; } else{ profit = profit - _increment; } } } /// @notice Create `mintedAmount` tokens and send it to `target`. /// @param target Address to receive the tokens. /// @param mintedAmount The amount of tokens target will receive. function mintToken(address target, uint256 mintedAmount) onlyOwner public { balanceOf[target] += mintedAmount; // Updates target's balance. totalSupply += mintedAmount; // Updates totalSupply. _updateTokensAvailable(balanceOf[this]); // Update the balance of tokens available if necessary. Transfer(0, this, mintedAmount); // Notifies the blockchain about the tokens created. Transfer(this, target, mintedAmount); // Notifies the blockchain about the transfer to target. } /// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens. /// @param target Address to be frozen. /// @param freeze Either to freeze target or not. function freezeAccount(address target, bool freeze) onlyOwner public { frozenAccount[target] = freeze; // Sets the target status. True if it's frozen, False if it's not. FrozenFunds(target, freeze); // Notifies the blockchain about the change of state. } /// @notice Allow addresses to pay `newBuyPrice`ETH when buying and receive `newSellPrice`ETH when selling, foreach token bought/sold. /// @param newSellPrice Price applied when an address sells its tokens, amount in WEI (1ETH = 10¹⁸WEI). /// @param newBuyPrice Price applied when an address buys tokens, amount in WEI (1ETH = 10¹⁸WEI). function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public { sellPrice = newSellPrice; // Updates the buying price. buyPrice = newBuyPrice; // Updates the selling price. } /// @notice Sets the state of buy and sell operations /// @param isClosedBuy True if buy operations are closed, False if opened. /// @param isClosedSell True if sell operations are closed, False if opened. function setStatus(bool isClosedBuy, bool isClosedSell) onlyOwner public { closeBuy = isClosedBuy; // Updates the state of buy operations. closeSell = isClosedSell; // Updates the state of sell operations. } /// @notice Deposits Ether to the contract function deposit() payable public returns(bool success) { require((this.balance + msg.value) > this.balance); // Checks for overflows. //Contract has already received the Ether when this function is executed. _updateSolvency(this.balance); // Updates the solvency value of the contract. _updateProfit(msg.value, false); // Decrease profit value. // Decrease because deposits will be done mostly by the owner. // Possible donations won't count as profit for the company, but in favor of the investors. LogDeposit(msg.sender, msg.value); // Notifies the blockchain about the Ether received. return true; } /// @notice The owner withdraws Ether from the contract. /// @param amountInWeis Amount of ETH in WEI which will be withdrawed. function withdraw(uint amountInWeis) onlyOwner public { LogWithdrawal(msg.sender, amountInWeis); // Notifies the blockchain about the withdrawal. _updateSolvency( (this.balance - amountInWeis) ); // Updates the solvency value of the contract. _updateProfit(amountInWeis, true); // Increase the profit value. owner.transfer(amountInWeis); // Sends the Ether to owner address. } function withdrawDividends(uint amountInWeis) internal returns(bool success) { LogWithdrawal(msg.sender, amountInWeis); // Notifies the blockchain about the withdrawal. _updateSolvency( (this.balance - amountInWeis) ); // Updates the solvency value of the contract. msg.sender.transfer(amountInWeis); // Sends the Ether to owner address. return true ; } /// @notice Buy tokens from contract by sending Ether. function buy() public payable { require(!closeBuy); //Buy operations must be opened uint amount = msg.value / buyPrice; //Calculates the amount of tokens to be sent uint market_value = amount * buyPrice; //Market value for this amount uint comision = market_value * 4 / 1000; //Calculates the comision for this transaction uint profit_in_transaction = market_value - (amount * sellPrice) - comision; //Calculates the relative profit for this transaction require(this.balance >= comision); //The token smart-contract pays comision, else the operation is not possible. comisionGetter.transfer(comision); //Transfers comision to the comisionGetter. _transfer(this, msg.sender, amount); //Makes the transfer of tokens. _updateSolvency((this.balance - profit_in_transaction)); //Updates the solvency value of the contract. _updateProfit(profit_in_transaction, true); //Increase the profit value. owner.transfer(profit_in_transaction); //Sends profit to the owner of the contract. } /// @notice Sell `amount` tokens to the contract. /// @param amount amount of tokens to be sold. function sell(uint256 amount) public { require(!closeSell); //Sell operations must be opened uint market_value = amount * sellPrice; //Market value for this amount uint comision = market_value * 4 / 1000; //Calculates the comision for this transaction uint amount_weis = market_value + comision; //Total in weis that must be paid require(this.balance >= amount_weis); //Contract must have enough weis comisionGetter.transfer(comision); //Transfers comision to the comisionGetter _transfer(msg.sender, this, amount); //Makes the transfer of tokens, the contract receives the tokens. _updateSolvency( (this.balance - amount_weis) ); //Updates the solvency value of the contract. msg.sender.transfer(market_value); //Sends Ether to the seller. } /// Default function, sender buys tokens by sending ether to the contract: function () public payable { buy(); } function setDividends(uint _period, uint _totalAmount) onlyOwner public returns (bool success) { require(this.balance >= _totalAmount ) ; // period is 201801 201802 etc. yyyymm - no more than 1 dividend distribution per month dividends[_period] = _totalAmount ; return true ; } function setEmail(string _email ) public returns (bool success) { require(balanceOf[msg.sender] > 0 ) ; // require(emails[msg.sender] == "" ) ; // checks the e-mail for this address was not already set emails[msg.sender] = _email ; return true ; } function dividendsGetPaid(uint _period) public returns (bool success) { uint percentageDividends ; uint qtyDividends ; require(!frozenAccount[msg.sender]); // frozen accounts are not allowed to withdraw ether require(balanceOf[msg.sender] > 0 ) ; // sender has a positive balance of tokens to get paid require(dividends[_period] > 0) ; // there is an active dividend period require(paidDividends[msg.sender][_period] == 0) ; // the dividend for this token holder was not yet paid // using here a 10000 (ten thousand) arbitrary multiplying factor for floating point precision percentageDividends = (balanceOf[msg.sender] / totalSupply ) * 10000 ; qtyDividends = ( percentageDividends * dividends[_period] ) / 10000 ; require(this.balance >= qtyDividends) ; // contract has enough ether to pay this dividend paidDividends[msg.sender][_period] = qtyDividends ; // record the dividend was paid require(withdrawDividends(qtyDividends)); return true ; } function adminResetEmail(address _address, string _newEmail ) public onlyOwner { require(balanceOf[_address] > 0 ) ; emails[_address] = _newEmail ; } }
Price applied if someone wants to sell a token.
uint256 public sellPrice = 5000000000000000;
12,123,644
[ 1, 5147, 6754, 309, 18626, 14805, 358, 357, 80, 279, 1147, 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 ]
[ 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, 2254, 5034, 1071, 357, 80, 5147, 540, 273, 1381, 12648, 17877, 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 ]
./partial_match/1/0x14cC8DfaF2258E1B8B2869300dBa1B734dc0fE43/sources/KtuneTokenBlocks.sol
* @dev Internal function that burns an amount of the token of a given account, deducting from the sender's allowance for said account. Uses the internal burn function. Emits an Approval event (reflecting the reduced allowance). @param account The account whose tokens will be burnt. @param value The amount that will be burnt./
function _burnFrom(address account, uint256 value) internal { _burn(account, value); _approve(account, msg.sender, _allowed[account][msg.sender].sub(value)); }
2,737,057
[ 1, 3061, 445, 716, 18305, 87, 392, 3844, 434, 326, 1147, 434, 279, 864, 2236, 16, 11140, 853, 310, 628, 326, 5793, 1807, 1699, 1359, 364, 7864, 350, 2236, 18, 14854, 326, 2713, 18305, 445, 18, 7377, 1282, 392, 1716, 685, 1125, 871, 261, 1734, 1582, 310, 326, 13162, 1699, 1359, 2934, 225, 2236, 1021, 2236, 8272, 2430, 903, 506, 18305, 88, 18, 225, 460, 1021, 3844, 716, 903, 506, 18305, 88, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 445, 389, 70, 321, 1265, 12, 2867, 2236, 16, 2254, 5034, 460, 13, 2713, 288, 203, 5411, 389, 70, 321, 12, 4631, 16, 460, 1769, 203, 5411, 389, 12908, 537, 12, 4631, 16, 1234, 18, 15330, 16, 389, 8151, 63, 4631, 6362, 3576, 18, 15330, 8009, 1717, 12, 1132, 10019, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* $$\ $$\ $$ | $$ | $$$$$$$\ $$$$$$\ $$$$$$$\ $$$$$$\ $$\ $$\ $$$$$$\ $$$$$$$\ $$$$$$\ $$ | $$ __$$\ $$ __$$\ $$ _____|\_$$ _| $$ | $$ |$$ __$$\ $$ __$$\ \____$$\ $$ | $$ | $$ |$$ / $$ |$$ / $$ | $$ | $$ |$$ | \__|$$ | $$ | $$$$$$$ |$$ | $$ | $$ |$$ | $$ |$$ | $$ |$$\ $$ | $$ |$$ | $$ | $$ |$$ __$$ |$$ | $$ | $$ |\$$$$$$ |\$$$$$$$\ \$$$$ |\$$$$$$ |$$ | $$ | $$ |\$$$$$$$ |$$ | \__| \__| \______/ \_______| \____/ \______/ \__| \__| \__| \_______|\__| */ pragma solidity 0.8.1; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import {LibBank} from "../libraries/LibBank.sol"; import {LibStrings} from "../libraries/LibStrings.sol"; import {BankAttributes, AppStorage} from "../libraries/LibAppStorage.sol"; import {LibMeta} from "../libraries/LibMeta.sol"; import {LibERC721} from "../libraries/LibERC721.sol"; import {IERC721TokenReceiver} from "../interfaces/IERC721TokenReceiver.sol"; import {LoanAttributes} from "../../Loans/libraries/LibAppStorage.sol"; import {LoanAttributesInterface} from "../interfaces/LoanAttributesInterface.sol"; import {LibSVG} from "../libraries/LibSVG.sol"; contract BankFacet { AppStorage internal s; using SafeMath for uint256; // ================= Test-net Events ================ // event tnTransferBank(uint256 _bankID, address _address); // ================================================== // function totalSupply() external view returns (uint256 totalSupply_) { totalSupply_ = s.bankIDs.length; } /// @notice Count all NFTs assigned to an owner /// @dev NFTs assigned to the zero address are considered invalid, and this. /// function throws for queries about the zero address. /// @param _owner An address for whom to query the balance /// @return balance_ The number of NFTs owned by `_owner`, possibly zero function balanceOf(address _owner) external view returns (uint256 balance_) { require(_owner != address(0), "LoanFacet: _owner can't be address(0"); balance_ = s.ownerBankIDs[_owner].length; } function getBankAttributes(uint256 _bankID) external view returns (BankAttributes memory bankAttributes_) { bankAttributes_ = LibBank.getBankAttributes(_bankID); } function pushLoanIDAttribute(uint256 _bankID, uint256 _loanID) external { require(LibMeta.msgSender() == s.loanDiamond, "Not Loan Diamond"); LibBank.pushLoanID(_bankID, _loanID); } function popLoanIDAttribute(uint256 _bankID, uint256 _loanID) external { require(LibMeta.msgSender() == s.loanDiamond, "Not Loan Diamond"); LibBank.popLoanID(_bankID, _loanID); } function decreaseBankBalance(uint256 _bankID, uint256 _amount) external { BankAttributes storage bankAttributes = s.banks[_bankID]; bankAttributes.availableLoanAmount = (bankAttributes.availableLoanAmount).sub(_amount); } function increaseBankBalance(uint256 _bankID, uint256 _amount) external { BankAttributes storage bankAttributes = s.banks[_bankID]; bankAttributes.availableLoanAmount = (bankAttributes.availableLoanAmount).add(_amount); } // /// @notice Enumerate valid NFTs // /// @dev Throws if `_index` >= `totalSupply()`. // /// @param _index A counter less than `totalSupply()` // /// @return The token identifier for the `_index`th NFT, // /// (sort bank not specified) function bankByIndex(uint256 _index) external view returns (uint256 bankID_) { require(_index < s.bankIDs.length, "BankFacet: index beyond supply"); bankID_ = s.bankIDs[_index]; } // /// @notice Enumerate NFTs assigned to an owner // /// @dev Throws if `_index` >= `balanceOf(_owner)` or if // /// `_owner` is the zero address, representing invalid NFTs. // /// @param _owner An address where we are interested in NFTs owned by them // /// @param _index A counter less than `balanceOf(_owner)` // /// @return The token identifier for the `_index`th NFT assigned to `_owner`, // /// (sort bank not specified) function bankOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 bankID_) { require(_index < s.ownerBankIDs[_owner].length, "BankFacet: index beyond owner balance"); bankID_ = s.ownerBankIDs[_owner][_index]; } function bankIDsOfOwner(address _owner) external view returns (uint32[] memory bankIDs_) { bankIDs_ = s.ownerBankIDs[_owner]; } function allBanksOfOwner(address _owner) external view returns (BankAttributes[] memory bankAttributes_) { uint256 length = s.ownerBankIDs[_owner].length; bankAttributes_ = new BankAttributes[](length); for (uint256 i; i < length; i++) { bankAttributes_[i] = LibBank.getBankAttributes(s.ownerBankIDs[_owner][i]); } } // call from front-end function allBankLoansOfOwner(address _owner) external view returns (uint32[] memory owner_loans) { uint256 length = s.ownerBankIDs[_owner].length; uint32[][] memory bank_loans = new uint32[][](length); uint256[] memory bank_loans_length = new uint256[](length); uint256 totalLoans; for (uint256 i; i < length; i++) { bank_loans[i] = s.banks[s.ownerBankIDs[_owner][i]].loanIDs; bank_loans_length[i] = bank_loans[i].length; totalLoans = totalLoans + bank_loans[i].length; } owner_loans = new uint32[](totalLoans); uint256 loanCount = 0; for (uint256 i; i < length; i++) { for (uint256 j; j < bank_loans_length[i]; j++) { owner_loans[loanCount] = bank_loans[i][j]; loanCount += 1; } } } // call from front-end function allBankLoanAttributesOfOwner(address _owner) external view returns (LoanAttributes[] memory loanAttributes_) { uint256 length = s.ownerBankIDs[_owner].length; uint32[][] memory bank_loans = new uint32[][](length); uint256[] memory bank_loans_length = new uint256[](length); uint256 totalLoans; for (uint256 i; i < length; i++) { bank_loans[i] = s.banks[s.ownerBankIDs[_owner][i]].loanIDs; bank_loans_length[i] = bank_loans[i].length; totalLoans = totalLoans + bank_loans[i].length; } loanAttributes_ = new LoanAttributes[](totalLoans); uint256 loanCount = 0; for (uint256 i; i < length; i++) { for (uint256 j; j < bank_loans_length[i]; j++) { loanAttributes_[loanCount] = LoanAttributesInterface(s.loanDiamond).getLoanAttributes(bank_loans[i][j]); loanCount += 1; } } } function banks() external view returns (uint32[] memory bankIDs_) { bankIDs_ = s.bankIDs; } function allBanks() external view returns (BankAttributes[] memory bankAttributes_) { uint256 length = s.bankIDs.length; bankAttributes_ = new BankAttributes[](length); for (uint256 i; i < length; i++) { bankAttributes_[i] = LibBank.getBankAttributes(s.bankIDs[i]); } } /// @notice Find the owner of an NFT /// @dev NFTs assigned to zero address are considered invalid, and queries /// about them do throw. /// @param _bankID The identifier for an NFT /// @return owner_ The address of the owner of the NFT function ownerOf(uint256 _bankID) external view returns (address owner_) { owner_ = s.banks[_bankID].owner; require(owner_ != address(0), "BankFacet: invalid _bankID"); } /// @notice Get the approved address for a single NFT /// @dev Throws if `_bankID` is not a valid NFT. /// @param _bankID The NFT to find the approved address for /// @return approved_ The approved address for this NFT, or the zero address if there is none function getApproved(uint256 _bankID) external view returns (address approved_) { require(_bankID < s.bankIDs.length, "BankFacet: _bankID is invalid"); approved_ = s.approved[_bankID]; } /// @notice Query if an address is an authorized operator for another address /// @param _owner The address that owns the NFTs /// @param _operator The address that acts on behalf of the owner /// @return approved_ True if `_operator` is an approved operator for `_owner`, false otherwise function isApprovedForAll(address _owner, address _operator) external view returns (bool approved_) { approved_ = s.operators[_owner][_operator]; } //==================================================================// //==================================================================// function mint(address _to, uint256 _bankID) external { require(_to != address(0), "BankFacet: Can't mint to 0 address"); LibBank.mint(address(0), _to, _bankID); LibERC721.checkOnERC721Received(LibMeta.msgSender(), address(0), _to, _bankID, ""); } function burn(uint256 _bankID) external { address owner = s.banks[_bankID].owner; LibBank.burn(owner, address(0), _bankID); } //==================================================================// //==================================================================// /// @notice Transfers the ownership of an NFT from one address to another address /// @dev Throws unless `LibMeta.msgSender()` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_bankID` is not a valid NFT. When transfer is complete, this function /// checks if `_to` is a smart contract (code size > 0). If so, it calls /// `onERC721Received` on `_to` and throws if the return value is not /// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _bankID The NFT to transfer /// @param _data Additional data with no specified format, sent in call to `_to` function safeTransferFrom( address _from, address _to, uint256 _bankID, bytes calldata _data ) external { address sender = LibMeta.msgSender(); internalTransferFrom(sender, _from, _to, _bankID); LibERC721.checkOnERC721Received(sender, _from, _to, _bankID, _data); } /// @notice Transfers the ownership of an NFT from one address to another address /// @dev This works identically to the other function with an extra data parameter, /// except this function just sets data to "". /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _bankID The NFT to transfer function safeTransferFrom( address _from, address _to, uint256 _bankID ) external { address sender = LibMeta.msgSender(); internalTransferFrom(sender, _from, _to, _bankID); LibERC721.checkOnERC721Received(sender, _from, _to, _bankID, ""); } /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE /// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE /// THEY MAY BE PERMANENTLY LOST /// @dev Throws unless `LibMeta.msgSender()` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_bankID` is not a valid NFT. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _bankID The NFT to transfer function transferFrom( address _from, address _to, uint256 _bankID ) external { internalTransferFrom(LibMeta.msgSender(), _from, _to, _bankID); } // This function is used by transfer functions function internalTransferFrom( address _sender, address _from, address _to, uint256 _bankID ) internal { require(_to != address(0), "BankFacet: Can't transfer to 0 address"); require(_from != address(0), "BankFacet: _from can't be 0 address"); require(_from == s.banks[_bankID].owner, "BankFacet: _from is not owner, transfer failed"); require( _sender == _from || s.operators[_from][_sender] || _sender == s.approved[_bankID], "BankFacet: Not owner or approved to transfer" ); LibBank.transfer(_from, _to, _bankID); // =============== Test-net Events ============ // if ((s.testDuration + s.initTimestamp) >= block.timestamp) { emit tnTransferBank(_bankID, LibMeta.msgSender()); } // ============================================ // } /// @notice Change or reaffirm the approved address for an NFT /// @dev The zero address indicates there is no approved address. /// Throws unless `LibMeta.msgSender()` is the current NFT owner, or an authorized /// operator of the current owner. /// @param _approved The new approved NFT controller /// @param _bankID The NFT to approve function approve(address _approved, uint256 _bankID) external { address owner = s.banks[_bankID].owner; require(owner == LibMeta.msgSender() || s.operators[owner][LibMeta.msgSender()], "BankFacet: Not owner or operator of token."); s.approved[_bankID] = _approved; emit LibERC721.Approval(owner, _approved, _bankID); } /// @notice Enable or disable approval for a third party ("operator") to manage /// all of `LibMeta.msgSender()`'s assets /// @dev Emits the ApprovalForAll event. The contract MUST allow /// multiple operators per owner. /// @param _operator Address to add to the set of authorized operators /// @param _approved True if the operator is approved, false to revoke approval function setApprovalForAll(address _operator, bool _approved) external { s.operators[LibMeta.msgSender()][_operator] = _approved; emit LibERC721.ApprovalForAll(LibMeta.msgSender(), _operator, _approved); } function name() external view returns (string memory) { // return "Nocturnal Bank"; return s.bankName; } /// @notice An abbreviated name for NFTs in this contract function symbol() external view returns (string memory) { //return "oNOCT"; return s.bankSymbol; } /// @notice A distinct Uniform Resource Identifier (URI) for a given asset. /// @dev Throws if `_bankID` is not a valid NFT. URIs are defined in RFC /// 3986. The URI may point to a JSON file that conforms to the "ERC721 /// Metadata JSON Schema". function bankURI(uint256 _bankID) external view returns (string memory) { BankAttributes memory bankAttributes = s.banks[_bankID]; return LibSVG.bankURI( LibSVG.MetaDataParams({ owner: bankAttributes.owner, bankID: _bankID, bankAddress: bankAttributes.bankAddress, poolAddress: bankAttributes.bankPoolAddress, loanTokenAddress: bankAttributes.loanTokenAddress, collateralTokenAddress: bankAttributes.collateralTokenAddress, collateralizationRate: bankAttributes.collateralizationRate, loanInterestRate: bankAttributes.loanInterestRate, maxDuration: bankAttributes.loanDuration, minDuration: bankAttributes.loanDurationMin, swapSlippage: bankAttributes.collateralSwapSlippage, settlementGratuity: bankAttributes.settlementGratuityRate })); } }
@notice Change or reaffirm the approved address for an NFT @dev The zero address indicates there is no approved address. Throws unless `LibMeta.msgSender()` is the current NFT owner, or an authorized operator of the current owner. @param _approved The new approved NFT controller @param _bankID The NFT to approve
function approve(address _approved, uint256 _bankID) external { address owner = s.banks[_bankID].owner; require(owner == LibMeta.msgSender() || s.operators[owner][LibMeta.msgSender()], "BankFacet: Not owner or operator of token."); s.approved[_bankID] = _approved; emit LibERC721.Approval(owner, _approved, _bankID); }
12,974,115
[ 1, 3043, 578, 283, 7329, 3985, 326, 20412, 1758, 364, 392, 423, 4464, 225, 1021, 3634, 1758, 8527, 1915, 353, 1158, 20412, 1758, 18, 225, 22435, 3308, 1375, 5664, 2781, 18, 3576, 12021, 20338, 353, 326, 783, 423, 4464, 3410, 16, 578, 392, 10799, 225, 3726, 434, 326, 783, 3410, 18, 225, 389, 25990, 1021, 394, 20412, 423, 4464, 2596, 225, 389, 10546, 734, 1021, 423, 4464, 358, 6617, 537, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 6617, 537, 12, 2867, 389, 25990, 16, 2254, 5034, 389, 10546, 734, 13, 3903, 288, 203, 3639, 1758, 3410, 273, 272, 18, 10546, 87, 63, 67, 10546, 734, 8009, 8443, 31, 203, 3639, 2583, 12, 8443, 422, 10560, 2781, 18, 3576, 12021, 1435, 747, 272, 18, 30659, 63, 8443, 6362, 5664, 2781, 18, 3576, 12021, 1435, 6487, 315, 16040, 11137, 30, 2288, 3410, 578, 3726, 434, 1147, 1199, 1769, 203, 3639, 272, 18, 25990, 63, 67, 10546, 734, 65, 273, 389, 25990, 31, 203, 3639, 3626, 10560, 654, 39, 27, 5340, 18, 23461, 12, 8443, 16, 389, 25990, 16, 389, 10546, 734, 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 ]
./full_match/5/0xc138a35532D9FC0558c01F0654719d7FD995736a/sources/src/ERC721MusicGame.sol
@dev Block transfers while cre8ing.
function _beforeTokenTransfers( address, address, uint256 startTokenId, uint256 quantity ) internal view override { uint256 tokenId = startTokenId; for (uint256 end = tokenId + quantity; tokenId < end; ++tokenId) { if (cre8ingStarted[tokenId] != 0 && cre8ingTransfer != 2) { revert Cre8ing_Cre8ing(); } } }
1,929,419
[ 1, 1768, 29375, 1323, 1519, 28, 310, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 5771, 1345, 1429, 18881, 12, 203, 3639, 1758, 16, 203, 3639, 1758, 16, 203, 3639, 2254, 5034, 787, 1345, 548, 16, 203, 3639, 2254, 5034, 10457, 203, 565, 262, 2713, 1476, 3849, 288, 203, 3639, 2254, 5034, 1147, 548, 273, 787, 1345, 548, 31, 203, 3639, 364, 261, 11890, 5034, 679, 273, 1147, 548, 397, 10457, 31, 1147, 548, 411, 679, 31, 965, 2316, 548, 13, 288, 203, 5411, 309, 261, 1793, 28, 310, 9217, 63, 2316, 548, 65, 480, 374, 597, 1519, 28, 310, 5912, 480, 576, 13, 288, 203, 7734, 15226, 5799, 28, 310, 67, 1996, 28, 310, 5621, 203, 5411, 289, 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 ]
/* solhint-disable-next-line compiler-fixed */ pragma solidity ^0.4.23; // Copyright 2017 OpenST Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // ---------------------------------------------------------------------------- // Auxiliary chain: UtilityTokenInterface // // http://www.simpletoken.org/ // // ---------------------------------------------------------------------------- /** * @title UtilityTokenInterface contract * * @notice Provides the interface to utility token contract. */ contract UtilityTokenInterface { /** Events */ /** Minted raised when new utility tokens are minted for a beneficiary */ event Minted( address indexed _beneficiary, uint256 _amount, uint256 _totalSupply, address _utilityToken ); /** Burnt raised when new utility tokens are burnt for an address */ event Burnt( address indexed _account, uint256 _amount, uint256 _totalSupply, address _utilityToken ); /** Public Functions */ /** * @notice Mints the utility token * * @dev Adds _amount tokens to beneficiary balance and increases the * totalTokenSupply. Can be called only by CoGateway. * * @param _beneficiary Address of tokens beneficiary. * @param _amount Amount of tokens to mint. * * @return bool `true` if mint is successful, false otherwise. */ function mint( address _beneficiary, uint256 _amount ) external returns (bool success); /** * @notice Burns the balance for the burner's address * * @dev only burns the amount from CoGateway address, So to burn * transfer the amount to CoGateway. * * @param _burner Burner address. * @param _amount Amount of tokens to burn. * * @return bool `true` if burn is successful, false otherwise. */ function burn( address _burner, uint256 _amount ) external returns (bool success); }
* @title UtilityTokenInterface contract @notice Provides the interface to utility token contract./
contract UtilityTokenInterface { event Minted( address indexed _beneficiary, uint256 _amount, uint256 _totalSupply, address _utilityToken ); event Burnt( address indexed _account, uint256 _amount, uint256 _totalSupply, address _utilityToken ); function mint( address _beneficiary, uint256 _amount ) external returns (bool success); function burn( address _burner, uint256 _amount ) external returns (bool success); pragma solidity ^0.4.23; }
951,437
[ 1, 6497, 1345, 1358, 6835, 282, 28805, 326, 1560, 358, 12788, 1147, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 13134, 1345, 1358, 288, 203, 203, 203, 565, 871, 490, 474, 329, 12, 203, 3639, 1758, 8808, 389, 70, 4009, 74, 14463, 814, 16, 203, 3639, 2254, 5034, 389, 8949, 16, 203, 3639, 2254, 5034, 389, 4963, 3088, 1283, 16, 203, 3639, 1758, 389, 1367, 560, 1345, 203, 565, 11272, 203, 203, 565, 871, 605, 321, 88, 12, 203, 3639, 1758, 8808, 389, 4631, 16, 203, 3639, 2254, 5034, 389, 8949, 16, 203, 3639, 2254, 5034, 389, 4963, 3088, 1283, 16, 203, 3639, 1758, 389, 1367, 560, 1345, 203, 565, 11272, 203, 203, 203, 565, 445, 312, 474, 12, 203, 3639, 1758, 389, 70, 4009, 74, 14463, 814, 16, 203, 3639, 2254, 5034, 389, 8949, 203, 565, 262, 203, 3639, 3903, 203, 3639, 1135, 261, 6430, 2216, 1769, 203, 203, 565, 445, 18305, 12, 203, 3639, 1758, 389, 70, 321, 264, 16, 203, 3639, 2254, 5034, 389, 8949, 203, 565, 262, 203, 3639, 3903, 203, 3639, 1135, 261, 6430, 2216, 1769, 203, 683, 9454, 18035, 560, 3602, 20, 18, 24, 18, 4366, 31, 203, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; import './SuperCoin.sol'; contract Election { /* The struct (Candidates) has the following attributes: Internal id, candidate name, candidate agenda, candidate voting counter, candidate picture */ struct Candidate { uint id; //0 string name; //1 string agenda; //2 uint counter; //3 string candidatePicture; //4 address candidateAddress; //5 } // The mapping (candidates) is between candidate id to the candidates attributes mapping(uint => Candidate) public candidates; /* The mapping (voters) is between the voter address and {0,1,2,3,4}. "0" stands for no voting rights "1" stands for the user has a voting right & question rights that wasn't exercised "2" stands for the user has a voting right but asked a question "3" stands for the user has voted "4" stands for pending request for voting rights */ mapping(address => uint) public voters; mapping(uint => address) public registeredVoters; uint public numberOfCandidates; address public admin; uint public votingStartDate; // Voting start date uint public votingEndDate; // Voting end date uint public numberOfVoters; bool public isVotingDatesConfigured; SuperCoin private coin; constructor () public { admin = msg.sender; votingStartDate = 0; votingEndDate = 1; isVotingDatesConfigured = false; registeredVoters[1] = msg.sender; numberOfVoters = 1; voters[msg.sender] = 1; coin = new SuperCoin(6262019); } // The modifier (onlyAdmin) insure that only an admin can use the function modifier onlyAdmin { require( msg.sender == admin, "Only Admin can call this function.");_; } // The modifier (whileVoting) limits changes after voting started (such as adding a candidate or adding voters) modifier whileVoting { require(now < votingEndDate && now >= votingStartDate, "Voting has NOT started yet.");_; } // The modifier (beforeVotingStarted) insure that now is prior to voting start date modifier beforeVotingStarted { require( votingStartDate > now, "Voting has started, this is not allowed during voting time");_; } //MARK: - Getters function isAdmin (address _checkAdmin) public view returns (bool TF) { return (_checkAdmin == admin); } // The function (voterStatus) will return the voting status of the sender {0,1,2} function voterStatus () public view returns (uint status) { return (voters[msg.sender]); } function endVoting () public view returns (bool index) { return (now > votingEndDate && isVotingDatesConfigured); } /* The function (balanceOf) returns the number of tokens that a particular address,
 in this case, the contract owner, has in their account. */ function balanceOf (address _coinOwner) public view returns (uint) { return coin.voterBalance(_coinOwner); } //MARK: - Setters /* The function (addingCandidate) is limited for admin use only (with the help of the onlyAdmin modifier) and can be used only before voting starts (with the help of the beforeVotingStarted modifier), that is, adding a new candidate should take place only before voting starts */ function addingCandidate (string memory _name, string memory _agenda, string memory _picture, address _address) public onlyAdmin beforeVotingStarted { // Adding a new candidate to candidates mapping numberOfCandidates++; candidates[numberOfCandidates] = Candidate(numberOfCandidates, _name, _agenda, 0, _picture, _address); emit CandidatesAdded(numberOfCandidates); } // The function (defineVotingDates) is limited for admin use only (with the help of the onlyAdmin modifier) function defineVotingDates (uint _startDate, uint _endDate) public onlyAdmin { require ( _endDate > _startDate && _startDate > now, "Dates are not valid"); require (votingStartDate == 0 && votingEndDate == 1, "Dates already defined"); // Dates can be defined only once votingStartDate = _startDate; votingEndDate = _endDate; isVotingDatesConfigured = true; } /* The function (vote) can be used only while voting time period (with the help of th whileVoting modifier), it insure the user has voting rights and didn't use them allredy, and pay the voter after he votes. With the first require we insure that voter didn't vote in the past and has the right to vote. The seconde require insure that the candidate exists */ function vote (uint _candidateId) public whileVoting { require(voters[msg.sender] >= 1 && voters[msg.sender] <= 2, "You can not vote, you voted in the past, or you do not have the right to vote"); require(_candidateId > 0 && _candidateId <= numberOfCandidates, "This candidate doesn't exist"); candidates[_candidateId].counter ++; // Increase candidate counter voters[msg.sender] = 3; // Update users status emit VotingTookPlace(_candidateId); getPaid(msg.sender); // after coin is good } /* The function (addVoters) is limited for admin use only (with the help of the onlyAdmin modifier) and can be used only before voting starts (with the help of the beforeVotingStarted modifier), that is, adding a new voter should take place only before voting starts */ function addVoters (address[] memory _voters) public onlyAdmin beforeVotingStarted { for (uint i = 0; i < _voters.length; i++) { if (voters[_voters[i]] != 1) { voters[_voters[i]] = 1; numberOfVoters++; registeredVoters[numberOfVoters] = _voters[i]; } } emit VotersAdded(); } //MARK: - Private /* The function (getPaid) will reward any voter which is entitle, that is, either the voter voted or he asked a question were all candidates answered */ function getPaid (address _receiver) private { //require(coin.voterBalance(admin) > 0, "Next time please vote earlier"); coin.transferCoin(_receiver, 1); // new line - 1 coin for a vote emit VoterGotPaidForVoting(_receiver); } //MARK: - Events event VoterGotPaidForVoting (address indexed receiver); event VotingTookPlace (uint indexed candidateId); event CandidatesAdded (uint indexed candidateId); event VotersAdded (); //----------------------------------------------------------------------------------------------------------------------------// /* Bonus part: Questions from voters and answers candidates + enabling user to request voting rights In order to encourage vote, debate and contact with candidates we thought about a mechanism of questions and answersץ Each voter, after voting started, has the right to ask all candidates one question, if all candidates answered this questions (that is the question was relevant) the voter receives a reward (coin).*/ // The mapping is between question id to question struct mapping (uint => Question) public questionList; // The mapping is between questions and answers mapping (uint => mapping (address => string)) public answerList; /* The struct (Question) has the following attributes: question, counter of answers, questioner address */ struct Question { string question; uint answerCounter; address questioner; } uint public numberOfQuestions; // Counter for the number of questions been asked /* The function (addQuestion) can be used only while voting time period (with the help of the whileVoting modifier), it insure that the voter has voting & question rights, saves the question and update the counter */ function addQuestion (string memory _question) public whileVoting { require(voters[msg.sender] == 1 , "Question can't be asked"); // make sure he has voting & asking rights numberOfQuestions++; voters[msg.sender] = 2; // mark he asked a question questionList[numberOfQuestions] = Question(_question, 0, msg.sender); emit NewQuestion(numberOfQuestions); } /* The function (addAnswer) can be used only be used only by candidates (with the help of isCandidate function), insure that the candidate didn't answer in the past, updates the answers, and check if the questioner entitled to the reward */ function addAnswer (string memory _answer, uint _questionId) public { require(getStringLength(answerList[_questionId][msg.sender]) == 0); // make sure he didn't answered this question require(isCandidate(msg.sender)); // make sure he is a candidate answerList[_questionId][msg.sender] = _answer; // save answer of the candidate questionList[_questionId].answerCounter++; // increase by 1 the answer counter if (questionList[_questionId].answerCounter == numberOfCandidates) { // if answer counter == number of candidates => pay the voter getPaid(questionList[_questionId].questioner); } emit NewAnswer(_questionId, msg.sender); } function getStringLength (string memory _string) private pure returns(uint _length) { bytes memory helper = bytes(_string); return (helper.length); } function isCandidate (address _helper) public view returns(bool ok) { for (uint i = 1; i <= numberOfCandidates; i++) { if (candidates[i].candidateAddress == _helper) { return(true); } } return(false); } event NewQuestion (uint indexed questionId); event NewAnswer (uint indexed questionId, address indexed candidateId); // Enabling user to request voting rights - voter can request from admin to get voting rights: mapping (uint => address) public pendingVoters; uint public numberOfPendingRequest; /* The function (addNewRequesst) can be used only before voting started (with the help of the beforeVoting modifer). It the the requester hasn't have voting rights and does n ot have anther pendding request. update requester status to pendding request (voters == 4) and updating the pendingVoters mapping */ function addNewRequest () public beforeVotingStarted { require(voters[msg.sender] == 0, "Your request is invalid"); // insure he hasn't have voting rights voters[msg.sender] = 4; // update requester status to pendding request numberOfPendingRequest++; // increase counter by one pendingVoters[numberOfPendingRequest] = msg.sender; } /* The function (getPendingRequesters) returns an array of address, oreder by the key in pending voters */ function getPendingRequesters() public view onlyAdmin returns(address[] memory _pendingRequesters) { address[] memory _pendingRequesters; for(uint i = 1; i <= numberOfPendingRequest; i++) { _pendingRequesters[i] = pendingVoters[i]; } return (_pendingRequesters); } function approveRequest(uint _requesterId) public onlyAdmin beforeVotingStarted { require(voters[pendingVoters[_requesterId]] == 4, "Can't approve"); voters[pendingVoters[_requesterId]] == 1; // update his voting rigths pendingVoters[_requesterId] = pendingVoters[numberOfPendingRequest]; numberOfPendingRequest--; } }
after coin is good
getPaid(msg.sender);
12,693,274
[ 1, 5205, 13170, 353, 7494, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1689, 20736, 12, 3576, 18, 15330, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.21; // 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, "You are not the owner of this contract."); _; } /** * @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: zeppelin-solidity/contracts/lifecycle/Destructible.sol /** * @title Destructible * @dev Base contract that can be destroyed by owner. All funds in contract will be sent to the owner. */ contract Destructible is Ownable { constructor() public payable { } /** * @dev Transfers the current balance to the owner and terminates the contract. */ function destroy() onlyOwner public { selfdestruct(owner); } function destroyAndSend(address _recipient) onlyOwner public { selfdestruct(_recipient); } } // File: zeppelin-solidity/contracts/lifecycle/Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused, "this contract is 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(); } } // 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) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // File: contracts/marketplace/Marketplace.sol /** * @title Interface for contracts conforming to ERC-20 */ contract ERC20Interface { function transferFrom(address from, address to, uint tokens) public returns (bool success); } /** * @title Interface for contracts conforming to ERC-721 */ contract ERC721Interface { function ownerOf(uint256 assetId) public view returns (address); function safeTransferFrom(address from, address to, uint256 assetId) public; function isAuthorized(address operator, uint256 assetId) public view returns (bool); function exists(uint256 assetId) public view returns (bool); } contract DCLEscrow is Ownable, Pausable, Destructible { using SafeMath for uint256; ERC20Interface public acceptedToken; ERC721Interface public nonFungibleRegistry; struct Escrow { bytes32 id; address seller; address buyer; uint256 price; uint256 offer; bool acceptsOffers; bool publicE; uint256 escrowByOwnerIdPos; uint256 parcelCount; address highestBidder; uint256 lastOfferPrice; } struct Offer { address highestOffer; uint256 highestOfferPrice; address previousOffer; } mapping (uint256 => Escrow) public escrowByAssetId; mapping (bytes32 => Escrow) public escrowByEscrowId; mapping (bytes32 => Offer) public offersByEscrowId; mapping (address => Escrow[]) public escrowByOwnerId; mapping(address => uint256) public openedEscrowsByOwnerId; mapping(address => uint256) public ownerEscrowsCounter; mapping(address => uint256[]) public allOwnerParcelsOnEscrow; mapping(bytes32 => uint256[]) public assetIdByEscrowId; mapping(address => bool) public whitelistAddresses; uint256 public whitelistCounter; uint256 public publicationFeeInWei; //15000000000000000000 uint256 private publicationFeeTotal; bytes32[] public allEscrowIds; //address[] public whitelistAddressGetter; /* EVENTS */ event EscrowCreated( bytes32 id, address indexed seller, address indexed buyer, uint256 priceInWei, bool acceptsOffers, bool publicE, uint256 parcels ); event EscrowSuccessful( bytes32 id, address indexed seller, uint256 totalPrice, address indexed winner ); event EscrowCancelled( bytes32 id, address indexed seller ); function addAddressWhitelist(address toWhitelist) public onlyOwner { require(toWhitelist != address(0), "Address cannot be empty."); whitelistAddresses[toWhitelist] = true; } /* function getwhitelistCounter() public onlyOwner view returns(uint256) { return whitelistCounter; } function getwhitelistAddress(uint256 index) public onlyOwner view returns(address) { return whitelistAddressGetter[index]; } function deleteWhitelistAddress(address toDelete, uint256 index) public onlyOwner { require(toDelete != address(0), "Address cannot be blank."); require(index > 0, "index needs to be greater than zero."); delete whitelistAddresses[toDelete]; delete whitelistAddressGetter[index]; } */ function updateEscrow(address _acceptedToken, address _nonFungibleRegistry) public onlyOwner { acceptedToken = ERC20Interface(_acceptedToken); nonFungibleRegistry = ERC721Interface(_nonFungibleRegistry); } constructor (address _acceptedToken, address _nonFungibleRegistry) public { acceptedToken = ERC20Interface(_acceptedToken); nonFungibleRegistry = ERC721Interface(_nonFungibleRegistry); } function setPublicationFee(uint256 publicationFee) onlyOwner public { publicationFeeInWei = publicationFee; } function getPublicationFeeTotal() public onlyOwner view returns(uint256) { return publicationFeeTotal; } function getTotalEscrowCount() public view returns(uint256) { return allEscrowIds.length; } function getSingleEscrowAdmin(bytes32 index) public view returns (bytes32, address, address,uint256, uint256, bool, bool, uint256, uint256, address, uint256) { Escrow storage tempEscrow = escrowByEscrowId[index]; return ( tempEscrow.id, tempEscrow.seller, tempEscrow.buyer, tempEscrow.price, tempEscrow.offer, tempEscrow.publicE, tempEscrow.acceptsOffers, tempEscrow.escrowByOwnerIdPos, tempEscrow.parcelCount, tempEscrow.highestBidder, tempEscrow.lastOfferPrice); } function getAssetByEscrowIdLength(bytes32 escrowId) public view returns (uint256) { return assetIdByEscrowId[escrowId].length; } function getSingleAssetByEscrowIdLength(bytes32 escrowId, uint index) public view returns (uint256) { return assetIdByEscrowId[escrowId][index]; } function getEscrowCountByAssetIdArray(address ownerAddress) public view returns (uint256) { return ownerEscrowsCounter[ownerAddress]; } function getAllOwnedParcelsOnEscrow(address ownerAddress) public view returns (uint256) { return allOwnerParcelsOnEscrow[ownerAddress].length; } function getParcelAssetIdOnEscrow(address ownerAddress,uint index) public view returns (uint256) { return allOwnerParcelsOnEscrow[ownerAddress][index]; } function getEscrowCountById(address ownerAddress) public view returns (uint) { return escrowByOwnerId[ownerAddress].length; } function getEscrowInfo(address ownerAddress, uint index) public view returns (bytes32, address, address,uint256, uint256, bool, bool, uint256, uint256, address, uint256) { Escrow storage tempEscrow = escrowByOwnerId[ownerAddress][index]; return ( tempEscrow.id, tempEscrow.seller, tempEscrow.buyer, tempEscrow.price, tempEscrow.offer, tempEscrow.publicE, tempEscrow.acceptsOffers, tempEscrow.escrowByOwnerIdPos, tempEscrow.parcelCount, tempEscrow.highestBidder, tempEscrow.lastOfferPrice); } function placeOffer(bytes32 escrowId, uint256 offerPrice) public whenNotPaused { address seller = escrowByEscrowId[escrowId].seller; require(seller != msg.sender, "You are the owner of this escrow."); require(seller != address(0)); require(offerPrice > 0, "Offer Price needs to be greater than zero"); require(escrowByEscrowId[escrowId].id != '0x0', "That escrow ID is no longer valid."); bool acceptsOffers = escrowByEscrowId[escrowId].acceptsOffers; require(acceptsOffers, "This escrow does not accept offers."); //address buyer = escrowByEscrowId[escrowId].buyer; bool isPublic = escrowByEscrowId[escrowId].publicE; if(!isPublic) { require(msg.sender == escrowByEscrowId[escrowId].buyer, "You are not authorized for this escrow."); } Escrow memory tempEscrow = escrowByEscrowId[escrowId]; tempEscrow.lastOfferPrice = tempEscrow.offer; tempEscrow.offer = offerPrice; tempEscrow.highestBidder = msg.sender; escrowByEscrowId[escrowId] = tempEscrow; } function createNewEscrow(uint256[] memory assedIds, uint256 escrowPrice, bool doesAcceptOffers, bool isPublic, address buyer) public whenNotPaused{ //address tempAssetOwner = msg.sender; uint256 tempParcelCount = assedIds.length; for(uint i = 0; i < tempParcelCount; i++) { address assetOwner = nonFungibleRegistry.ownerOf(assedIds[i]); require(msg.sender == assetOwner, "You are not the owner of this parcel."); require(nonFungibleRegistry.exists(assedIds[i]), "This parcel does not exist."); require(nonFungibleRegistry.isAuthorized(address(this), assedIds[i]), "You have not authorized DCL Escrow to manage your LAND tokens."); allOwnerParcelsOnEscrow[assetOwner].push(assedIds[i]); } require(escrowPrice > 0, "Please pass a price greater than zero."); bytes32 escrowId = keccak256(abi.encodePacked( block.timestamp, msg.sender, assedIds[0], escrowPrice )); assetIdByEscrowId[escrowId] = assedIds; //uint256 memEscrowByOwnerIdPos = openedEscrowsByOwnerId[assetOwner]; Escrow memory memEscrow = Escrow({ id: escrowId, seller: msg.sender, buyer: buyer, price: escrowPrice, offer:0, publicE:isPublic, acceptsOffers: doesAcceptOffers, escrowByOwnerIdPos: 0, parcelCount: tempParcelCount, highestBidder: address(0), lastOfferPrice: 0 }); escrowByEscrowId[escrowId] = memEscrow; escrowByOwnerId[msg.sender].push(memEscrow); //ownerEscrowsCounter[msg.sender] = getEscrowCountByAssetIdArray(msg.sender) + 1; allEscrowIds.push(escrowId); emit EscrowCreated( escrowId, msg.sender, buyer, escrowPrice, doesAcceptOffers, isPublic, tempParcelCount ); } function cancelAllEscrows() public onlyOwner { //need to delete each escrow by escrow id pause(); for(uint e = 0; e < getTotalEscrowCount(); e++) { adminRemoveEscrow(allEscrowIds[e]); } delete allEscrowIds; unpause(); } function adminRemoveEscrow(bytes32 escrowId) public onlyOwner { address seller = escrowByEscrowId[escrowId].seller; //require(seller == msg.sender || msg.sender == owner); //uint256 escrowOwnerPos = escrowByEscrowId[escrowId].escrowByOwnerIdPos; delete escrowByEscrowId[escrowId]; for(uint t = 0; t < escrowByOwnerId[seller].length; t++) { if(escrowByOwnerId[seller][t].id == escrowId) { delete escrowByOwnerId[seller][t]; } } //escrowByOwnerId[seller].splice //ownerEscrowsCounter[seller] = getEscrowCountByAssetIdArray(seller) - 1; uint256[] memory assetIds = assetIdByEscrowId[escrowId]; for(uint i = 0; i < assetIds.length; i++) { for(uint j = 0; j < allOwnerParcelsOnEscrow[seller].length; j++) { if(assetIds[i] == allOwnerParcelsOnEscrow[seller][j]) { delete allOwnerParcelsOnEscrow[seller][j]; } } } emit EscrowCancelled(escrowId, seller); } function removeEscrow(bytes32 escrowId) public whenNotPaused { address seller = escrowByEscrowId[escrowId].seller; require(seller == msg.sender || msg.sender == owner); //uint256 escrowOwnerPos = escrowByEscrowId[escrowId].escrowByOwnerIdPos; delete escrowByEscrowId[escrowId]; for(uint t = 0; t < escrowByOwnerId[seller].length; t++) { if(escrowByOwnerId[seller][t].id == escrowId) { delete escrowByOwnerId[seller][t]; } } //escrowByOwnerId[seller].splice //ownerEscrowsCounter[seller] = getEscrowCountByAssetIdArray(seller) - 1; uint256[] memory assetIds = assetIdByEscrowId[escrowId]; for(uint i = 0; i < assetIds.length; i++) { for(uint j = 0; j < allOwnerParcelsOnEscrow[seller].length; j++) { if(assetIds[i] == allOwnerParcelsOnEscrow[seller][j]) { delete allOwnerParcelsOnEscrow[seller][j]; } } } delete allEscrowIds; emit EscrowCancelled(escrowId, seller); } function acceptEscrow(bytes32 escrowId) public whenNotPaused { address seller = escrowByEscrowId[escrowId].seller; require(seller != msg.sender); require(seller != address(0)); address buyer = escrowByEscrowId[escrowId].buyer; bool isPublic = escrowByEscrowId[escrowId].publicE; if(!isPublic) { require(msg.sender == escrowByEscrowId[escrowId].buyer, "You are not authorized for this escrow."); } //need to add check that offer price is accepted uint256[] memory assetIds = assetIdByEscrowId[escrowId]; for(uint a = 0; a < assetIds.length; a++) { require(seller == nonFungibleRegistry.ownerOf(assetIds[a])); } uint escrowPrice = escrowByEscrowId[escrowId].price; if (publicationFeeInWei > 0) { if(!whitelistAddresses[msg.sender]) { acceptedToken.transferFrom( msg.sender, owner, publicationFeeInWei ); } if(!whitelistAddresses[seller]) { acceptedToken.transferFrom( seller, owner, publicationFeeInWei ); } } // Transfer sale amount to seller acceptedToken.transferFrom( msg.sender, seller, escrowPrice ); for(uint counter = 0; counter < assetIds.length; counter++) { uint256 tempId = assetIds[counter]; nonFungibleRegistry.safeTransferFrom( seller, msg.sender, tempId ); } for(uint t = 0; t < escrowByOwnerId[seller].length; t++) { if(escrowByOwnerId[seller][t].id == escrowId) { delete escrowByOwnerId[seller][t]; } } for(uint i = 0; i < assetIds.length; i++) { for(uint j = 0; j < allOwnerParcelsOnEscrow[seller].length; j++) { if(assetIds[i] == allOwnerParcelsOnEscrow[seller][j]) { delete allOwnerParcelsOnEscrow[seller][j]; } } } delete escrowByEscrowId[escrowId]; delete assetIdByEscrowId[escrowId]; emit EscrowSuccessful( escrowId, seller, escrowPrice, buyer ); } }
address buyer = escrowByEscrowId[escrowId].buyer;
function placeOffer(bytes32 escrowId, uint256 offerPrice) public whenNotPaused { address seller = escrowByEscrowId[escrowId].seller; require(seller != msg.sender, "You are the owner of this escrow."); require(seller != address(0)); require(offerPrice > 0, "Offer Price needs to be greater than zero"); require(escrowByEscrowId[escrowId].id != '0x0', "That escrow ID is no longer valid."); bool acceptsOffers = escrowByEscrowId[escrowId].acceptsOffers; require(acceptsOffers, "This escrow does not accept offers."); bool isPublic = escrowByEscrowId[escrowId].publicE; if(!isPublic) { require(msg.sender == escrowByEscrowId[escrowId].buyer, "You are not authorized for this escrow."); } Escrow memory tempEscrow = escrowByEscrowId[escrowId]; tempEscrow.lastOfferPrice = tempEscrow.offer; tempEscrow.offer = offerPrice; tempEscrow.highestBidder = msg.sender; escrowByEscrowId[escrowId] = tempEscrow; }
15,881,877
[ 1, 2867, 27037, 273, 2904, 492, 858, 6412, 492, 548, 63, 742, 492, 548, 8009, 70, 16213, 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 ]
[ 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, 3166, 10513, 12, 3890, 1578, 2904, 492, 548, 16, 2254, 5034, 10067, 5147, 13, 1071, 1347, 1248, 28590, 203, 565, 288, 203, 3639, 1758, 29804, 273, 2904, 492, 858, 6412, 492, 548, 63, 742, 492, 548, 8009, 1786, 749, 31, 203, 3639, 2583, 12, 1786, 749, 480, 1234, 18, 15330, 16, 315, 6225, 854, 326, 3410, 434, 333, 2904, 492, 1199, 1769, 203, 3639, 2583, 12, 1786, 749, 480, 1758, 12, 20, 10019, 203, 3639, 2583, 12, 23322, 5147, 405, 374, 16, 315, 10513, 20137, 4260, 358, 506, 6802, 2353, 3634, 8863, 203, 3639, 2583, 12, 742, 492, 858, 6412, 492, 548, 63, 742, 492, 548, 8009, 350, 480, 296, 20, 92, 20, 2187, 315, 18163, 2904, 492, 1599, 353, 1158, 7144, 923, 1199, 1769, 203, 203, 540, 203, 3639, 1426, 8104, 7210, 414, 273, 2904, 492, 858, 6412, 492, 548, 63, 742, 492, 548, 8009, 9436, 87, 7210, 414, 31, 203, 3639, 2583, 12, 9436, 87, 7210, 414, 16, 315, 2503, 2904, 492, 1552, 486, 2791, 28641, 1199, 1769, 203, 203, 3639, 1426, 19620, 273, 2904, 492, 858, 6412, 492, 548, 63, 742, 492, 548, 8009, 482, 41, 31, 203, 3639, 309, 12, 5, 291, 4782, 13, 203, 3639, 288, 203, 5411, 2583, 12, 3576, 18, 15330, 422, 2904, 492, 858, 6412, 492, 548, 63, 742, 492, 548, 8009, 70, 16213, 16, 315, 6225, 854, 486, 10799, 364, 333, 2904, 492, 1199, 1769, 203, 3639, 289, 203, 540, 203, 3639, 512, 1017, 492, 3778, 1906, 6412, 492, 273, 2904, 492, 858, 2 ]
./full_match/42/0x0303582606A1E6bc3b5de7A71016F3C739ec83e9/sources/cache/solpp-generated-contracts/utils/Common.sol
These are the factors we used to determine how to settle or liquidate an account Aggregate amount of free collateral Net available amounts in local currency Net available amounts in collateral currency Cash claim amount in local currency Cash claim amount in collateral currency
struct FreeCollateralFactors { int256 aggregate; int256 localNetAvailable; int256 collateralNetAvailable; int256 localCashClaim; int256 collateralCashClaim; }
16,218,300
[ 1, 29690, 854, 326, 14490, 732, 1399, 358, 4199, 3661, 358, 444, 5929, 578, 4501, 26595, 340, 392, 2236, 18059, 3844, 434, 4843, 4508, 2045, 287, 8503, 2319, 30980, 316, 1191, 5462, 8503, 2319, 30980, 316, 4508, 2045, 287, 5462, 385, 961, 7516, 3844, 316, 1191, 5462, 385, 961, 7516, 3844, 316, 4508, 2045, 287, 5462, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1958, 15217, 13535, 2045, 287, 23535, 288, 203, 3639, 509, 5034, 7047, 31, 203, 3639, 509, 5034, 1191, 7308, 5268, 31, 203, 3639, 509, 5034, 4508, 2045, 287, 7308, 5268, 31, 203, 3639, 509, 5034, 1191, 39, 961, 9762, 31, 203, 3639, 509, 5034, 4508, 2045, 287, 39, 961, 9762, 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 ]
pragma solidity ^0.6.0; // import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract VulnerabilityContract is Ownable { // States enum Status {Pending, Invalid, Valid, Acknowledged, Patched, Disclosed} enum RewardStatus {NULL, SET, TOCLAIM, TOREFUND, SENT} // TODO evaluate if we need TOREFUND // Reward RewardStatus public rewStatus; // Metadata address public vendor; // The address of the vendor bytes32 public vendorName; // The name of the vendor bytes32 public productName; // The name of the product bytes32 public productVersion; // The version of the product bytes32 public vulnerabilityHash; // The hash of the vulnerability information // Contract info uint public timestamp; // The timestamp of the creation of the vulnerability address payable public researcher; // Researcher address Status public status; // The status of the vulnerability bytes32 public hashlock; // Sha-2 sha256 the secret used as hashlock uint public timelock; // UNIX timestamp seconds - locked UNTIL this time //deadline uint public secret; // The secret string public vulnerabilityLocation; // A pointer to a location with the vulnerability information constructor ( address payable _researcher, bytes32 _vendorName, bytes32 _productName, bytes32 _productVersion, bytes32 _vulnerabilityHash, bytes32 _hashlock) public { // Store the new vulnerability entry //Set Reward rewStatus=RewardStatus.NULL; // Set Metadata vendorName=_vendorName; productName=_productName; productVersion=_productVersion; vulnerabilityHash=_vulnerabilityHash; // Set info timestamp=block.timestamp; researcher= _researcher; hashlock=_hashlock; timelock=0; vulnerabilityLocation= ""; status=Status.Pending; secret= 0; } function setVendor(address _vendor) external onlyOwner{ require(vendor==address(0), "Vendor has been set already"); vendor=_vendor; } function setStatus(Status _status) external onlyOwner{ status=_status; } function setRewardStatus(RewardStatus _rewStatus) external onlyOwner{ rewStatus=_rewStatus; } function setTimelock(uint _timelock) external onlyOwner{ require(timelock==0, "Timelock has been set already"); timelock=_timelock; } function setSecret(uint _secret) external onlyOwner{ require(secret==0, "Secret has been set already"); secret=_secret; } function setLocation(string calldata _location) external onlyOwner{ vulnerabilityLocation=_location; } }
The timestamp of the creation of the vulnerability
uint public timestamp;
994,617
[ 1, 1986, 2858, 434, 326, 6710, 434, 326, 331, 26064, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 1071, 2858, 31, 5375, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0x9386c0a3e4a641de38a2f054102383a6c20f24bf //Contract name: LamdenPhases //Balance: 0.25 Ether //Verification Date: 10/11/2017 //Transacion Count: 5 // CODE STARTS HERE pragma solidity ^0.4.13; 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. */ address newOwner; function transferOwnership(address _newOwner) onlyOwner { if (_newOwner != address(0)) { newOwner = _newOwner; } } function acceptOwnership() { if (msg.sender == newOwner) { owner = newOwner; } } } contract tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData); } contract ERC20 is Ownable { /* Public variables of the token */ string public standard; string public name; string public symbol; uint8 public decimals; uint256 public initialSupply; bool public locked; uint256 public creationBlock; mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) public allowance; /* This generates a public event on the blockchain that will notify clients */ event Transfer(address indexed from, address indexed to, uint256 value); modifier onlyPayloadSize(uint numwords) { assert(msg.data.length == numwords * 32 + 4); _; } /* Initializes contract with initial supply tokens to the creator of the contract */ function ERC20( uint256 _initialSupply, string tokenName, uint8 decimalUnits, string tokenSymbol, bool transferAllSupplyToOwner, bool _locked ) { standard = 'ERC20 0.1'; initialSupply = _initialSupply; if (transferAllSupplyToOwner) { setBalance(msg.sender, initialSupply); } else { setBalance(this, initialSupply); } name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes decimals = decimalUnits; // Amount of decimals for display purposes locked = _locked; creationBlock = block.number; } /* internal balances */ function setBalance(address holder, uint256 amount) internal { balances[holder] = amount; } function transferInternal(address _from, address _to, uint256 value) internal returns (bool success) { if (value == 0) { return true; } if (balances[_from] < value) { return false; } if (balances[_to] + value <= balances[_to]) { return false; } setBalance(_from, balances[_from] - value); setBalance(_to, balances[_to] + value); Transfer(_from, _to, value); return true; } /* public methods */ function totalSupply() returns (uint256) { return initialSupply; } function balanceOf(address _address) returns (uint256) { return balances[_address]; } function transfer(address _to, uint256 _value) onlyPayloadSize(2) returns (bool) { require(locked == false); bool status = transferInternal(msg.sender, _to, _value); require(status == true); return true; } function approve(address _spender, uint256 _value) returns (bool success) { if(locked) { return false; } allowance[msg.sender][_spender] = _value; return true; } function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { if (locked) { return false; } tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if (locked) { return false; } if (allowance[_from][msg.sender] < _value) { return false; } bool _success = transferInternal(_from, _to, _value); if (_success) { allowance[_from][msg.sender] -= _value; } return _success; } } contract MintingERC20 is ERC20 { mapping (address => bool) public minters; uint256 public maxSupply; function MintingERC20( uint256 _initialSupply, uint256 _maxSupply, string _tokenName, uint8 _decimals, string _symbol, bool _transferAllSupplyToOwner, bool _locked ) ERC20(_initialSupply, _tokenName, _decimals, _symbol, _transferAllSupplyToOwner, _locked) { standard = "MintingERC20 0.1"; minters[msg.sender] = true; maxSupply = _maxSupply; } function addMinter(address _newMinter) onlyOwner { minters[_newMinter] = true; } function removeMinter(address _minter) onlyOwner { minters[_minter] = false; } function mint(address _addr, uint256 _amount) onlyMinters returns (uint256) { if (locked == true) { return uint256(0); } if (_amount == uint256(0)) { return uint256(0); } if (initialSupply + _amount <= initialSupply){ return uint256(0); } if (initialSupply + _amount > maxSupply) { return uint256(0); } initialSupply += _amount; balances[_addr] += _amount; Transfer(this, _addr, _amount); return _amount; } modifier onlyMinters () { require(true == minters[msg.sender]); _; } } contract Lamden is MintingERC20 { uint8 public decimals = 18; string public tokenName = "Lamden Tau"; string public tokenSymbol = "TAU"; uint256 public maxSupply = 500 * 10 ** 6 * uint(10) ** decimals; // 500,000,000 // We block token transfers till ICO end. bool public transferFrozen = true; function Lamden( uint256 initialSupply, bool _locked ) MintingERC20(initialSupply, maxSupply, tokenName, decimals, tokenSymbol, false, _locked) { standard = 'Lamden 0.1'; } function setLocked(bool _locked) onlyOwner { locked = _locked; } // Allow token transfer. function freezing(bool _transferFrozen) onlyOwner { transferFrozen = _transferFrozen; } // ERC20 functions // ========================= function transfer(address _to, uint _value) returns (bool) { require(!transferFrozen); return super.transfer(_to, _value); } // should not have approve/transferFrom function approve(address, uint) returns (bool success) { require(false); return false; // super.approve(_spender, _value); } function approveAndCall(address, uint256, bytes) returns (bool success) { require(false); return false; } function transferFrom(address, address, uint) returns (bool success) { require(false); return false; // super.transferFrom(_from, _to, _value); } } contract LamdenTokenAllocation is Ownable { Lamden public tau; uint256 public constant LAMDEN_DECIMALS = 10 ** 18; uint256 allocatedTokens = 0; Allocation[] allocations; struct Allocation { address _address; uint256 amount; } function LamdenTokenAllocation( address _tau, address[] addresses ){ require(uint8(addresses.length) == uint8(14)); allocations.push(Allocation(addresses[0], 20000000 * LAMDEN_DECIMALS)); //Stu allocations.push(Allocation(addresses[1], 12500000 * LAMDEN_DECIMALS)); //Nick allocations.push(Allocation(addresses[2], 8750000 * LAMDEN_DECIMALS)); //James allocations.push(Allocation(addresses[3], 8750000 * LAMDEN_DECIMALS)); //Mario allocations.push(Allocation(addresses[4], 250000 * LAMDEN_DECIMALS)); // Advisor allocations.push(Allocation(addresses[5], 250000 * LAMDEN_DECIMALS)); // Advisor allocations.push(Allocation(addresses[6], 250000 * LAMDEN_DECIMALS)); // Advisor allocations.push(Allocation(addresses[7], 250000 * LAMDEN_DECIMALS)); // Advisor allocations.push(Allocation(addresses[8], 250000 * LAMDEN_DECIMALS)); // Advisor allocations.push(Allocation(addresses[9], 250000 * LAMDEN_DECIMALS)); // Advisor allocations.push(Allocation(addresses[10], 250000 * LAMDEN_DECIMALS)); // Advisor allocations.push(Allocation(addresses[11], 250000 * LAMDEN_DECIMALS)); // Advisor allocations.push(Allocation(addresses[12], 48000000 * LAMDEN_DECIMALS)); // enterpriseCaseStudies allocations.push(Allocation(addresses[13], 50000000 * LAMDEN_DECIMALS)); // AKA INNOVATION FUND tau = Lamden(_tau); } function allocateTokens(){ require(uint8(allocations.length) == uint8(14)); require(address(tau) != 0x0); require(allocatedTokens == 0); for (uint8 i = 0; i < allocations.length; i++) { Allocation storage allocation = allocations[i]; uint256 mintedAmount = tau.mint(allocation._address, allocation.amount); require(mintedAmount == allocation.amount); allocatedTokens += allocation.amount; } } function setTau(address _tau) onlyOwner { tau = Lamden(_tau); } } contract LamdenPhases is Ownable { uint256 public constant LAMDEN_DECIMALS = 10 ** 18; uint256 public soldTokens; uint256 public collectedEthers; uint256 todayCollectedEthers; uint256 icoInitialThresholds; uint256 currentDay; Phase[] public phases; Lamden public tau; uint8 currentPhase; address etherHolder; address investor = 0x3669ad54675E94e14196528786645c858b8391F1; mapping(address => uint256) alreadyContributed; struct Phase { uint256 price; uint256 maxAmount; uint256 since; uint256 till; uint256 soldTokens; uint256 collectedEthers; bool isFinished; mapping (address => bool) whitelist; } function LamdenPhases( address _etherHolder, address _tau, uint256 _tokenPreIcoPrice, uint256 _preIcoSince, uint256 _preIcoTill, uint256 preIcoMaxAmount, // 1,805,067.01326114 + 53,280,090 uint256 _tokenIcoPrice, uint256 _icoSince, uint256 _icoTill, uint256 icoMaxAmount, uint256 icoThresholds ) { phases.push(Phase(_tokenPreIcoPrice, preIcoMaxAmount, _preIcoSince, _preIcoTill, 0, 0, false)); phases.push(Phase(_tokenIcoPrice, icoMaxAmount, _icoSince, _icoTill, 0, 0, false)); etherHolder = _etherHolder; icoInitialThresholds = icoThresholds; tau = Lamden(_tau); } // call add minter from TAU token after contract deploying function sendTokensToInvestor() onlyOwner { uint256 mintedAmount = mintInternal(investor, (1805067013261140000000000)); require(mintedAmount == uint256(1805067013261140000000000)); } function getIcoTokensAmount(uint256 value, uint256 time, address _address) returns (uint256) { if (value == 0) { return uint256(0); } uint256 amount = 0; for (uint8 i = 0; i < phases.length; i++) { Phase storage phase = phases[i]; if (phase.whitelist[_address] == false) { continue; } if(phase.isFinished){ continue; } if (phase.since > time) { continue; } if (phase.till < time) { continue; } currentPhase = i; // should we be multiplying by 10 ** 18??? // 1 eth = 1000000000000000000 / uint256 phaseAmount = value * LAMDEN_DECIMALS / phase.price; amount += phaseAmount; if (phase.maxAmount < amount + soldTokens) { return uint256(0); } // phase.soldTokens += amount; phase.collectedEthers += value; } return amount; } function() payable { bool status = buy(msg.sender, msg.value); require(status == true); } function setInternalFinished(uint8 phaseId, bool _finished) internal returns (bool){ if (phases.length < phaseId) { return false; } Phase storage phase = phases[phaseId]; if (phase.isFinished == true) { return true; } phase.isFinished = _finished; return true; } function setFinished(uint8 phaseId, bool _finished) onlyOwner returns (bool){ return setInternalFinished(phaseId, _finished); } function buy(address _address, uint256 _value) internal returns (bool) { if (_value == 0) { return false; } if (phases.length < currentPhase) { return false; } Phase storage icoPhase = phases[1]; if (icoPhase.since <= now) { currentPhase = 1; uint256 daysInterval = (now - icoPhase.since) / uint256(86400); uint256 todayMaxEthers = icoInitialThresholds; if (daysInterval != currentDay) { currentDay = daysInterval; todayCollectedEthers = 0; } todayMaxEthers = icoInitialThresholds * (2 ** daysInterval); if(alreadyContributed[_address] + _value > todayMaxEthers) { return false; } alreadyContributed[_address] += _value; } uint256 tokenAmount = getIcoTokensAmount(_value, now, _address); if (tokenAmount == 0) { return false; } uint256 mintedAmount = mintInternal(_address, tokenAmount); require(mintedAmount == tokenAmount); collectedEthers += _value; Phase storage phase = phases[currentPhase]; if (soldTokens == phase.maxAmount) { setInternalFinished(currentPhase, true); } return true; } function setTau(address _tau) onlyOwner { tau = Lamden(_tau); } function setPhase(uint8 phaseId, uint256 since, uint256 till, uint256 price) onlyOwner returns (bool) { if (phases.length <= phaseId) { return false; } if (price == 0) { return false; } Phase storage phase = phases[phaseId]; if (phase.isFinished == true) { return false; } phase.since = since; phase.till = till; phase.price = price; return true; } function transferEthers() onlyOwner { require(etherHolder != 0x0); etherHolder.transfer(this.balance); } function addToWhitelist(uint8 phaseId, address _address) onlyOwner { require(phases.length > phaseId); Phase storage phase = phases[phaseId]; phase.whitelist[_address] = true; } function removeFromWhitelist(uint8 phaseId, address _address) onlyOwner { require(phases.length > phaseId); Phase storage phase = phases[phaseId]; phase.whitelist[_address] = false; } function mint(address _address, uint256 tokenAmount) onlyOwner returns (uint256) { return mintInternal(_address, tokenAmount); } function mintInternal(address _address, uint256 tokenAmount) internal returns (uint256) { require(address(tau) != 0x0); uint256 mintedAmount = tau.mint(_address, tokenAmount); require(mintedAmount == tokenAmount); require(phases.length > currentPhase); Phase storage phase = phases[currentPhase]; phase.soldTokens += tokenAmount; soldTokens += tokenAmount; return tokenAmount; } function getPhase(uint8 phaseId) returns (uint256, uint256, uint256, uint256, uint256, uint256, bool) { require(phases.length > phaseId); Phase storage phase = phases[phaseId]; return (phase.price, phase.maxAmount, phase.since, phase.till, phase.soldTokens, phase.collectedEthers, phase.isFinished); } }
* @dev Allows the current owner to transfer control of the contract to a newOwner. @param newOwner The address to transfer ownership to./
address newOwner;
12,717,851
[ 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, 565, 1758, 394, 5541, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: UNLICENSED pragma solidity >=0.8.0; /// @notice Standard ERC-20 token interface with EIP-2612 {permit} extension. interface IERC20 { /// @dev ERC-20: function allowance(address owner, address spender) external view returns (uint); function balanceOf(address account) external view returns (uint); function totalSupply() external view returns (uint); function approve(address spender, uint amount) external returns (bool); function transfer(address to, uint amount) external returns (bool); function transferFrom(address from, address to, uint amount) external returns (bool); event Approval(address indexed owner, address indexed spender, uint amount); event Transfer(address indexed from, address indexed to, uint amount); /// @dev EIP-2612: function permit(address owner, address spender, uint amount, uint deadline, uint8 v, bytes32 r, bytes32 s) external; } /// @dev Hacked by LexDAO LLC. contract LivingTrustV1 { address public grantor; // supplies funds to vault - initial trustee address public beneficiary; // can claim trust funds - initially grantor address public successorTrustee; address public trustee; // @dev Updates to successor trustee following dead man switch uint256 public lastDeadManSwitched; // timestamp tracking last dead man switch call constructor(address _grantor, address _beneficiary, address _trustee, address _successorTrustee) { grantor = _grantor; beneficiary = _beneficiary; trustee = _trustee; successorTrustee = _successorTrustee; } function deadManSwitch() external { require(grantor == msg.sender); lastDeadManSwitched = block.timestamp; } function claimTrust() external { if (30 days > lastDeadManSwitched) { trustee = successorTrustee; } } function distribute(IERC20 asset, uint256 amount, address destination) external { require(trustee == msg.sender || grantor == msg.sender); asset.transfer(destination, amount); } function transferRoles(address _grantor, address _beneficiary, address _successorTrustee, address _trustee) external { grantor = _grantor; beneficiary = _beneficiary; successorTrustee = _successorTrustee; trustee = _trustee; } }
@dev Hacked by LexDAO LLC.
contract LivingTrustV1 { address public successorTrustee; } constructor(address _grantor, address _beneficiary, address _trustee, address _successorTrustee) { grantor = _grantor; beneficiary = _beneficiary; trustee = _trustee; successorTrustee = _successorTrustee; } function deadManSwitch() external { require(grantor == msg.sender); lastDeadManSwitched = block.timestamp; } function claimTrust() external { if (30 days > lastDeadManSwitched) { trustee = successorTrustee; } } function claimTrust() external { if (30 days > lastDeadManSwitched) { trustee = successorTrustee; } } function distribute(IERC20 asset, uint256 amount, address destination) external { require(trustee == msg.sender || grantor == msg.sender); asset.transfer(destination, amount); } function transferRoles(address _grantor, address _beneficiary, address _successorTrustee, address _trustee) external { grantor = _grantor; beneficiary = _beneficiary; successorTrustee = _successorTrustee; trustee = _trustee; } }
5,547,449
[ 1, 44, 484, 329, 635, 15123, 18485, 511, 13394, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 511, 9288, 14146, 58, 21, 288, 203, 565, 1758, 1071, 19532, 14146, 1340, 31, 203, 377, 203, 377, 203, 97, 203, 565, 3885, 12, 2867, 389, 16243, 280, 16, 1758, 389, 70, 4009, 74, 14463, 814, 16, 1758, 389, 21879, 1340, 16, 1758, 389, 4768, 280, 14146, 1340, 13, 288, 203, 540, 7936, 280, 273, 389, 16243, 280, 31, 203, 540, 27641, 74, 14463, 814, 273, 389, 70, 4009, 74, 14463, 814, 31, 203, 540, 10267, 1340, 273, 389, 21879, 1340, 31, 203, 540, 19532, 14146, 1340, 273, 389, 4768, 280, 14146, 1340, 31, 203, 565, 289, 203, 377, 203, 565, 445, 8363, 5669, 10200, 1435, 3903, 288, 203, 3639, 2583, 12, 16243, 280, 422, 1234, 18, 15330, 1769, 203, 3639, 1142, 11852, 5669, 10200, 329, 273, 1203, 18, 5508, 31, 203, 565, 289, 203, 377, 203, 565, 445, 7516, 14146, 1435, 3903, 288, 203, 3639, 309, 261, 5082, 4681, 405, 1142, 11852, 5669, 10200, 329, 13, 288, 203, 5411, 10267, 1340, 273, 19532, 14146, 1340, 31, 203, 3639, 289, 203, 565, 289, 203, 377, 203, 565, 445, 7516, 14146, 1435, 3903, 288, 203, 3639, 309, 261, 5082, 4681, 405, 1142, 11852, 5669, 10200, 329, 13, 288, 203, 5411, 10267, 1340, 273, 19532, 14146, 1340, 31, 203, 3639, 289, 203, 565, 289, 203, 377, 203, 565, 445, 25722, 12, 45, 654, 39, 3462, 3310, 16, 2254, 5034, 3844, 16, 1758, 2929, 13, 3903, 288, 203, 3639, 2583, 12, 21879, 1340, 422, 1234, 18, 15330, 747, 7936, 280, 422, 1234, 18, 15330, 1769, 203, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-07-08 */ pragma solidity 0.6.11; pragma experimental ABIEncoderV2; // /** * @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 Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; // constructor () internal { // _status = _NOT_ENTERED; // } function _ReentrancyGuard() internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // // solhint-disable-next-line compiler-version /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 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); } // /** * @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); } } } } // /** * @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"); } } } // interface IERC20Decimals { function decimals() external pure returns (uint8); } // interface IMintable { function mint(address account, uint256 amount) external; } // interface IBurnable { function burnFrom(address account, uint256 amount) external; } // interface IOracle { function getLatestPrice() external view returns (uint256); } // interface IWrappedNativeToken { function deposit() external payable; function withdraw(uint256 wad) external; } // interface IFlashLoanReceiver { function execute(address token, uint256 amount, uint256 fee, address back, bytes calldata params) external; } // /* * @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 Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // contract Admined is AccessControl { function _Admined(address admin) internal { _setupRole(DEFAULT_ADMIN_ROLE, admin); } modifier onlyAdmin() { require(isAdmin(msg.sender), "Restricted to admins"); _; } function isAdmin(address account) public view returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, account); } function getAdminCount() public view returns(uint256) { return getRoleMemberCount(DEFAULT_ADMIN_ROLE); } function addAdmin(address account) public virtual onlyAdmin { grantRole(DEFAULT_ADMIN_ROLE, account); } function renounceAdmin() public virtual { renounceRole(DEFAULT_ADMIN_ROLE, msg.sender); require( getRoleMemberCount(DEFAULT_ADMIN_ROLE) >= 1, "At least one admin required" ); } uint256[50] private __gap; } // contract Owned is Admined { bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE"); event AddedOwner(address indexed account); event RemovedOwner(address indexed account); event RenouncedOwner(address indexed account); //constructor function _Owned(address admin, address owner) internal { _Admined(admin); _setRoleAdmin(OWNER_ROLE, DEFAULT_ADMIN_ROLE); _setupRole(OWNER_ROLE, owner); } modifier onlyOwner() { require(isOwner(msg.sender), "restricted-to-owners"); _; } function isOwner(address account) public view returns (bool) { return hasRole(OWNER_ROLE, account); } function getOwners() public view returns (address[] memory) { uint256 count = getRoleMemberCount(OWNER_ROLE); address[] memory owners = new address[](count); for (uint256 i = 0; i < count; ++i) { owners[i] = getRoleMember(OWNER_ROLE, i); } return owners; } function addOwner(address account) public onlyAdmin { grantRole(OWNER_ROLE, account); emit AddedOwner(account); } function removeOwner(address account) public onlyAdmin { revokeRole(OWNER_ROLE, account); emit RemovedOwner(account); } function renounceOwner() public { renounceRole(OWNER_ROLE, msg.sender); emit RenouncedOwner(msg.sender); } uint256[50] private __gap; } // contract Lockable is Owned { mapping(bytes4 => bool) public disabledList; bool public globalDisable; function _Lockable() internal { } modifier notLocked() { require(!globalDisable && !disabledList[msg.sig], "locked"); _; } function enableListAccess(bytes4 sig) public onlyOwner { disabledList[sig] = false; } function disableListAccess(bytes4 sig) public onlyOwner { disabledList[sig] = true; } function enableGlobalAccess() public onlyOwner { globalDisable = false; } function disableGlobalAccess() public onlyOwner { globalDisable = true; } uint256[50] private __gap; } // contract Vault is Initializable, ReentrancyGuard, Lockable { using SafeMath for uint256; using EnumerableSet for EnumerableSet.AddressSet; using SafeERC20 for IERC20; event MintCollateral(address indexed sender, address indexed collateralToken, uint256 collateralAmount, uint256 mintAmount, uint256 mintFeeAmount); event MintShare(address indexed sender, uint256 shareAmount, uint256 mintAmount); event MintCollateralAndShare(address indexed sender, address indexed collateralToken, uint256 collateralAmount, uint256 shareAmount, uint256 mintAmount, uint256 mintFeeCollateralAmount, uint256 globalCollateralRatio); event RedeemCollateral(address indexed sender, uint256 stableAmount, address indexed collateralToken, uint256 redeemAmount, uint256 redeemFeeAmount); event RedeemShare(address indexed sender, uint256 shareAmount, uint256 redeemAmount); event RedeemCollateralAndShare(address indexed sender, uint256 stableAmount, address indexed collateralToken, uint256 redeemCollateralAmount, uint256 redeemShareAmount, uint256 redeemCollateralFeeAmount, uint256 globalCollateralRatio); event ExchangeShareBond(address indexed sender, uint256 shareBondAmount); event Recollateralize(address indexed sender, uint256 recollateralizeAmount, address indexed collateralToken, uint256 paidbackShareAmount); event Buyback(address indexed sender, uint256 shareAmount, address indexed receivedCollateralToken, uint256 buybackAmount, uint256 buybackFeeAmount); event FlashLoan(address indexed receiver, address indexed token, uint256 amount, uint256 fee, uint256 timestamp); address constant public NATIVE_TOKEN_ADDRESS = address(0x0000000000000000000000000000000000000000); uint256 constant public TARGET_PRICE = 1000000000000000000; //$1 uint256 constant public SHARE_TOKEN_PRECISION = 1000000000000000000; //1e18 uint256 constant public STABLE_TOKEN_PRECISION = 1000000000000000000; //1e18 uint256 constant public DELAY_CLAIM_BLOCK = 3; //prevent flash redeem!! uint256 public redeemFee; //赎回手续费率 [1e18] 0.45% => 4500000000000000 uint256 public mintFee; //增发手续费率 [1e18] 0.45% => 4500000000000000 uint256 public buybackFee; //回购手续费率 [1e18] 0.45% => 4500000000000000 uint256 public globalCollateralRatio; //全局质押率 [1e18] 1000000000000000000 uint256 public flashloanFee; //闪电贷手续费率 uint256 public shareBondCeiling; //股份币债券发行上限. uint256 public shareBondSupply; //股份币债券当前发行量 uint256 public lastRefreshTime; //全局质押率的最后调节时间. uint256 public refreshStep; //全局质押率的单次调节幅度 [1e18] 0.05 => 50000000000000000 uint256 public refreshPeriod; //全局质押率的调节周期(seconds) uint256 public refreshBand; //全局质押率的调节线 [1e18] 0.05 => 50000000000000000 address public stableToken; //stable token address public shareToken; //share token address public stableBondToken; //锚定稳定币的债券代币, 在适当的时候可以赎回. [废弃] address public shareBondToken; //锚定股份币的债券代币, 在适当的时候可以赎回 address payable public protocolFund; //收益基金 struct Collateral { bool deprecated; //抵押物废弃标记 uint256 recollateralizeFee; //在抵押奖励率 [1e18] uint256 ceiling; //抵押物的铸币上限 uint256 precision; //抵押物的精度 address oracle; //抵押物的预言机 } mapping(address => uint256) public lastRedeemBlock; //账户的最后赎回交易块号. account => block.number mapping(address => uint256) public redeemedShareBonds; //账户已赎回但未取回的share代币总量. account => shareAmount mapping(address => uint256) public unclaimedCollaterals; //系统内已赎回但未取回的某抵押物总量. collateralToken => collateralAmount mapping(address => mapping(address => uint256)) public redeemedCollaterals; //账户已赎回但未取回的某抵押物总量. account => token => amount address public shareTokenOracle; address public stableTokenOracle; EnumerableSet.AddressSet private collateralTokens; //抵押物代币集合. mapping(address => Collateral) public collaterals; //抵押物配置. collateralToken => Collateral address public wrappedNativeToken; bool public kbtToKunImmediately; uint256 public buybackBonus; function initialize( address _stableToken, address _shareToken, address _shareBondToken, address _wrappedNativeToken, address _admin, address _stableTokenOracle, address _shareTokenOracle ) public initializer { _Owned(_admin, msg.sender); _ReentrancyGuard(); stableToken = _stableToken; shareToken = _shareToken; wrappedNativeToken = _wrappedNativeToken; shareBondToken = _shareBondToken; stableTokenOracle = _stableTokenOracle; shareTokenOracle = _shareTokenOracle; globalCollateralRatio = 1e18; } //计算抵押物价值 function calculateCollateralValue(address collateralToken, uint256 collateralAmount) public view returns (uint256) { return collateralAmount.mul(getCollateralPrice(collateralToken)).div(collaterals[collateralToken].precision); } //计算抵押物的铸币数量和手续费(以抵押物计) function calculateCollateralMintAmount(address collateralToken, uint256 collateralAmount) public view returns (uint256, uint256) { uint256 mintFeeAmount = collateralAmount.mul(mintFee).div(1e18); collateralAmount = collateralAmount.sub(mintFeeAmount); return (calculateCollateralValue(collateralToken, collateralAmount), mintFeeAmount); } //计算股份币的铸币数量 function calculateShareMintAmount(uint256 shareAmount) public view returns(uint256) { return shareAmount.mul(getShareTokenPrice()).div(SHARE_TOKEN_PRECISION); } //计算抵押物和股份币的铸币数量 //@RETURN1 铸币量 //@RETURN2 所需的股份币的数量 //@RETURN3 抵押物部分的手续费(以抵押物计) function calculateCollateralAndShareMintAmount(address collateralToken, uint256 collateralAmount) public view returns(uint256, uint256, uint256) { uint256 collateralValue = calculateCollateralValue(collateralToken, collateralAmount); uint256 shareTokenPrice = getShareTokenPrice(); //https://docs.qian.finance/qian-v2-whitepaper/minting //(1 - Cr) * Cv = Cr * Sv //Sv = ((1 - Cr) * Cv) / Cr // = (Cv - (Cv * Cr)) / Cr // = (Cv / Cr) - ((Cv * Cr) / Cr) // = (Cv / Cr) - Cv uint256 shareValue = collateralValue.mul(1e18).div(globalCollateralRatio).sub(collateralValue); uint256 shareAmount = shareValue.mul(SHARE_TOKEN_PRECISION).div(shareTokenPrice); uint256 mintFeeValue = collateralValue.mul(mintFee).div(1e18); uint256 mintFeeCollateralAmount = calculateEquivalentCollateralAmount(mintFeeValue, collateralToken); uint256 mintAmount = collateralValue.sub(mintFeeValue).add(shareValue); return (mintAmount, shareAmount, mintFeeCollateralAmount); } //计算赎回抵押物的数量和手续费(以抵押物计) function calculateCollateralRedeemAmount(uint256 stableAmount, address collateralToken) public view returns (uint256, uint256) { uint256 redeemAmount = calculateEquivalentCollateralAmount(stableAmount, collateralToken); uint256 redeemFeeAmount = redeemAmount.mul(redeemFee).div(1e18); return (redeemAmount.sub(redeemFeeAmount), redeemFeeAmount); } //计算赎回股份币的数量(以股份币计) function calculateShareRedeemAmount(uint256 stableAmount) public view returns (uint256) { uint256 shareAmount = stableAmount.mul(SHARE_TOKEN_PRECISION).div(getShareTokenPrice()); return shareAmount; } //计算赎回股份币和抵押物的数量. //@RETURN1 抵押物的数量 //@RETURN2 股份币的数量 //@RETURN4 抵押物部分的手续费 function calculateCollateralAndShareRedeemAmount(uint256 stableAmount, address collateralToken) public view returns (uint256, uint256, uint256) { uint256 collateralValue = stableAmount.mul(globalCollateralRatio).div(1e18); uint256 collateralAmount = calculateEquivalentCollateralAmount(collateralValue, collateralToken); uint256 shareValue = stableAmount.sub(collateralValue); uint256 shareAmount = shareValue.mul(SHARE_TOKEN_PRECISION).div(getShareTokenPrice()); uint256 redeemFeeCollateralAmount = collateralAmount.mul(redeemFee).div(1e18); return (collateralAmount.sub(redeemFeeCollateralAmount), shareAmount, redeemFeeCollateralAmount); } //计算同等美元价值的抵押物数量 //注: 系统中@stableToken的价格总是$1, 所以@stableAmount等价于相同数量的美元. function calculateEquivalentCollateralAmount(uint256 stableAmount, address collateralToken) public view returns (uint256) { //stableAmount / collateralPrice return stableAmount.mul(collaterals[collateralToken].precision).div(getCollateralPrice(collateralToken)); //1e18 } //100% collateral-backed function mint(address collateralToken, uint256 collateralAmount, uint256 minimumReceived) external payable notLocked nonReentrant { require(isCollateralToken(collateralToken) && !collaterals[collateralToken].deprecated, "invalid/deprecated-collateral-token"); require(globalCollateralRatio >= 1e18, "mint-not-allowed"); (uint256 mintAmount, uint256 mintFeeAmount) = calculateCollateralMintAmount(collateralToken, collateralAmount); require(minimumReceived <= mintAmount, "slippage-limit-reached"); require(getCollateralizedBalance(collateralToken).add(collateralAmount) <= collaterals[collateralToken].ceiling, "ceiling-reached"); _depositFrom(collateralToken, msg.sender, collateralAmount); _withdrawTo(collateralToken, protocolFund, mintFeeAmount); IMintable(stableToken).mint(msg.sender, mintAmount); emit MintCollateral(msg.sender, collateralToken, collateralAmount, mintAmount, mintFeeAmount); } // 0% collateral-backed function mint(uint256 shareAmount, uint256 minimumReceived) external notLocked nonReentrant { require(globalCollateralRatio == 0, "mint-not-allowed"); uint256 mintAmount = calculateShareMintAmount(shareAmount); require(minimumReceived <= mintAmount, "slippage-limit-reached"); IBurnable(shareToken).burnFrom(msg.sender, shareAmount); IMintable(stableToken).mint(msg.sender, mintAmount); emit MintShare(msg.sender, shareAmount, mintAmount); } // > 0% and < 100% collateral-backed function mint(address collateralToken, uint256 collateralAmount, uint256 shareAmount, uint256 minimumReceived) external payable notLocked nonReentrant { require(isCollateralToken(collateralToken) && !collaterals[collateralToken].deprecated, "invalid/deprecated-collateral-token"); require(globalCollateralRatio < 1e18 && globalCollateralRatio > 0, "mint-not-allowed"); require(getCollateralizedBalance(collateralToken).add(collateralAmount) <= collaterals[collateralToken].ceiling, "ceiling-reached"); (uint256 mintAmount, uint256 shareNeeded, uint256 mintFeeCollateralAmount) = calculateCollateralAndShareMintAmount(collateralToken, collateralAmount); require(minimumReceived <= mintAmount, "slippage-limit-reached"); require(shareNeeded <= shareAmount, "need-more-shares"); IBurnable(shareToken).burnFrom(msg.sender, shareNeeded); _depositFrom(collateralToken, msg.sender, collateralAmount); _withdrawTo(collateralToken, protocolFund, mintFeeCollateralAmount); IMintable(stableToken).mint(msg.sender, mintAmount); emit MintCollateralAndShare(msg.sender, collateralToken, collateralAmount, shareNeeded, mintAmount, mintFeeCollateralAmount, globalCollateralRatio); } // Redeem collateral. 100% collateral-backed function redeem(uint256 stableAmount, address receivedCollateralToken, uint256 minimumReceivedCollateralAmount) external notLocked nonReentrant { require(globalCollateralRatio == 1e18, "redeem-not-allowed"); (uint256 redeemAmount, uint256 redeemFeeAmount) = calculateCollateralRedeemAmount(stableAmount, receivedCollateralToken); require(redeemAmount.add(redeemFeeAmount) <= getCollateralizedBalance(receivedCollateralToken), "not-enough-collateral"); require(minimumReceivedCollateralAmount <= redeemAmount, "slippage-limit-reached"); redeemedCollaterals[msg.sender][receivedCollateralToken] = redeemedCollaterals[msg.sender][receivedCollateralToken].add(redeemAmount); unclaimedCollaterals[receivedCollateralToken] = unclaimedCollaterals[receivedCollateralToken].add(redeemAmount); lastRedeemBlock[msg.sender] = block.number; IBurnable(stableToken).burnFrom(msg.sender, stableAmount); _withdrawTo(receivedCollateralToken, protocolFund, redeemFeeAmount); emit RedeemCollateral(msg.sender, stableAmount, receivedCollateralToken, redeemAmount, redeemFeeAmount); } // Redeem QSD for collateral and KUN. > 0% and < 100% collateral-backed function redeem(uint256 stableAmount, address collateralToken, uint256 minimumReceivedCollateralAmount, uint256 minimumReceivedShareAmount) external notLocked nonReentrant { require(globalCollateralRatio < 1e18 && globalCollateralRatio > 0, "redeem-not-allowed"); (uint256 collateralAmount, uint256 shareAmount, uint256 redeemFeeCollateralAmount) = calculateCollateralAndShareRedeemAmount(stableAmount, collateralToken); require(collateralAmount.add(redeemFeeCollateralAmount) <= getCollateralizedBalance(collateralToken), "not-enough-collateral"); require(minimumReceivedCollateralAmount <= collateralAmount && minimumReceivedShareAmount <= shareAmount, "collaterals/shares-slippage-limit-reached"); redeemedCollaterals[msg.sender][collateralToken] = redeemedCollaterals[msg.sender][collateralToken].add(collateralAmount); unclaimedCollaterals[collateralToken] = unclaimedCollaterals[collateralToken].add(collateralAmount); redeemedShareBonds[msg.sender] = redeemedShareBonds[msg.sender].add(shareAmount); shareBondSupply = shareBondSupply.add(shareAmount); require(shareBondSupply <= shareBondCeiling, "sharebond-ceiling-reached"); lastRedeemBlock[msg.sender] = block.number; IBurnable(stableToken).burnFrom(msg.sender, stableAmount); _withdrawTo(collateralToken, protocolFund, redeemFeeCollateralAmount); emit RedeemCollateralAndShare(msg.sender, stableAmount, collateralToken, collateralAmount, shareAmount, redeemFeeCollateralAmount, globalCollateralRatio); } // Redeem QSD for KUN. 0% collateral-backed function redeem(uint256 stableAmount, uint256 minimumReceivedShareAmount) external notLocked nonReentrant { require(globalCollateralRatio == 0, "redeem-not-allowed"); uint256 shareAmount = calculateShareRedeemAmount(stableAmount); require(minimumReceivedShareAmount <= shareAmount, "slippage-limit-reached"); redeemedShareBonds[msg.sender] = redeemedShareBonds[msg.sender].add(shareAmount); shareBondSupply = shareBondSupply.add(shareAmount); require(shareBondSupply <= shareBondCeiling, "sharebond-ceiling-reached"); lastRedeemBlock[msg.sender] = block.number; IBurnable(stableToken).burnFrom(msg.sender, stableAmount); emit RedeemShare(msg.sender, stableAmount, shareAmount); } function claim() external notLocked nonReentrant { require(lastRedeemBlock[msg.sender].add(DELAY_CLAIM_BLOCK) <= block.number,"not-delay-claim-redeemed"); uint256 length = collateralTokens.length(); for (uint256 i = 0; i < length; ++i) { address collateralToken = collateralTokens.at(i); if (redeemedCollaterals[msg.sender][collateralToken] > 0) { uint256 collateralAmount = redeemedCollaterals[msg.sender][collateralToken]; redeemedCollaterals[msg.sender][collateralToken] = 0; unclaimedCollaterals[collateralToken] = unclaimedCollaterals[collateralToken].sub(collateralAmount); _withdrawTo(collateralToken, msg.sender, collateralAmount); } } if (redeemedShareBonds[msg.sender] > 0) { uint256 shareAmount = redeemedShareBonds[msg.sender]; redeemedShareBonds[msg.sender] = 0; IMintable(shareBondToken).mint(msg.sender, shareAmount); } } //当系统的实际质押率低于全局质押率时, 需要用户向系统补充抵押物。 用户会获得相应价值的KUN债券和部分额外的KUN债券奖励. function recollateralize(address collateralToken, uint256 collateralAmount, uint256 minimumReceivedShareAmount) external payable notLocked nonReentrant { require(isCollateralToken(collateralToken) && !collaterals[collateralToken].deprecated, "deprecated-collateral-token"); uint256 gapCollateralValue = getGapCollateralValue(); require(gapCollateralValue > 0, "no-gap-collateral-to-recollateralize"); uint256 recollateralizeValue = Math.min(gapCollateralValue, calculateCollateralValue(collateralToken, collateralAmount)); uint256 paidbackShareAmount = recollateralizeValue.mul(uint256(1e18).add(collaterals[collateralToken].recollateralizeFee)).div(getShareTokenPrice()); require(minimumReceivedShareAmount <= paidbackShareAmount, "slippage-limit-reached"); uint256 recollateralizeAmount = recollateralizeValue.mul(1e18).div(getCollateralPrice(collateralToken)); require(getCollateralizedBalance(collateralToken).add(recollateralizeAmount) <= collaterals[collateralToken].ceiling, "ceiling-reached"); shareBondSupply = shareBondSupply.add(paidbackShareAmount); require(shareBondSupply <= shareBondCeiling, "sharebond-ceiling-reached"); _depositFrom(collateralToken, msg.sender, collateralAmount); _withdrawTo(collateralToken, msg.sender, collateralAmount.sub(recollateralizeAmount)); IMintable(shareBondToken).mint(msg.sender, paidbackShareAmount); emit Recollateralize(msg.sender, recollateralizeAmount, collateralToken, paidbackShareAmount); } //当系统的实际质押率高于全局质押率时, 需要可以使用KUN向系统购买抵押物。 function buyback(uint256 shareAmount, address receivedCollateralToken) external notLocked nonReentrant { uint256 excessCollateralValue = getExcessCollateralValue(); require(excessCollateralValue > 0, "no-excess-collateral-to-buyback"); uint256 shareTokenPrice = getShareTokenPrice(); uint256 shareValue = shareAmount.mul(shareTokenPrice).div(1e18); shareValue = shareValue.mul(uint256(1e18).add(buybackBonus)).div(1e18); //0.01e18 uint256 buybackValue = excessCollateralValue > shareValue ? shareValue : excessCollateralValue; uint256 neededAmount = buybackValue.mul(1e18).div(shareTokenPrice); neededAmount = neededAmount.mul(1e18).div(uint256(1e18).add(buybackBonus)); IBurnable(shareToken).burnFrom(msg.sender, neededAmount); uint256 buybackAmount = calculateEquivalentCollateralAmount(buybackValue, receivedCollateralToken); require(buybackAmount <= getCollateralizedBalance(receivedCollateralToken), "insufficient-collateral-amount"); uint256 buybackFeeAmount = buybackAmount.mul(buybackFee).div(1e18); buybackAmount = buybackAmount.sub(buybackFeeAmount); _withdrawTo(receivedCollateralToken, msg.sender, buybackAmount); _withdrawTo(receivedCollateralToken, protocolFund, buybackFeeAmount); emit Buyback(msg.sender, shareAmount, receivedCollateralToken, buybackAmount, buybackFeeAmount); } //在同时满足下面两个条件的时候, KUN债券可以1:1兑换为KUN: // 1. 当系统的实际质押率高于全局质押率时 // && // 2. QSD的价格在目标价格以上(>$1) function exchangeShareBond(uint256 shareBondAmount) external notLocked nonReentrant { if(!kbtToKunImmediately) { uint256 excessCollateralValue = getExcessCollateralValue(); require(excessCollateralValue > 0, "no-excess-collateral-to-buyback"); uint256 stableTokenPrice = getStableTokenPrice(); require(stableTokenPrice > TARGET_PRICE, "price-not-eligible-for-bond-redeem"); } shareBondSupply = shareBondSupply.sub(shareBondAmount); IBurnable(shareBondToken).burnFrom(msg.sender, shareBondAmount); IMintable(shareToken).mint(msg.sender, shareBondAmount); emit ExchangeShareBond(msg.sender, shareBondAmount); } //调节全局质押率. function refreshCollateralRatio() public notLocked { uint256 stableTokenPrice = getStableTokenPrice(); require(block.timestamp - lastRefreshTime >= refreshPeriod, "refresh-cooling-period"); if (stableTokenPrice > TARGET_PRICE.add(refreshBand)) { //decrease collateral ratio if (globalCollateralRatio <= refreshStep) { globalCollateralRatio = 0; //if within a step of 0, go to 0 } else { globalCollateralRatio = globalCollateralRatio.sub(refreshStep); } } else if (stableTokenPrice < TARGET_PRICE.sub(refreshBand)) { //increase collateral ratio if (globalCollateralRatio.add(refreshStep) >= 1e18) { globalCollateralRatio = 1e18; // cap collateral ratio at 1 } else { globalCollateralRatio = globalCollateralRatio.add(refreshStep); } } lastRefreshTime = block.timestamp; // Set the time of the last expansion } function flashloan( address receiver, address token, uint256 amount, bytes memory params ) public notLocked nonReentrant { require(isCollateralToken(token), "invalid-collateral-token"); require(amount > 0, "invalid-flashloan-amount"); address t = (token == NATIVE_TOKEN_ADDRESS) ? wrappedNativeToken : token; uint256 balancesBefore = IERC20(t).balanceOf(address(this)); require(balancesBefore >= amount, "insufficient-balance"); uint256 balance = address(this).balance; uint256 fee = amount.mul(flashloanFee).div(1e18); require(fee > 0, "invalid-flashloan-fee"); IFlashLoanReceiver flashLoanReceiver = IFlashLoanReceiver(receiver); address payable _receiver = address(uint160(receiver)); // withdraw ether from WXXX to _receiver _withdrawTo(token, _receiver, amount); flashLoanReceiver.execute(token, amount, fee, address(this), params); if(token == NATIVE_TOKEN_ADDRESS) { //move _receiver repaid ether to WXXX require(address(this).balance >= balance.add(amount).add(fee), "ether-balance-exception"); IWrappedNativeToken(wrappedNativeToken).deposit{value: amount.add(fee)}(); } uint256 balancesAfter = IERC20(t).balanceOf(address(this)); require(balancesAfter >= balancesBefore.add(fee), "balance-exception"); _withdrawTo(token, protocolFund, fee); emit FlashLoan(receiver, token, amount, fee, block.timestamp); } function getNeededCollateralValue() public view returns(uint256) { uint256 stableSupply = IERC20(stableToken).totalSupply(); // Calculates collateral needed to back each 1 QSD with $1 of collateral at current collat ratio return stableSupply.mul(globalCollateralRatio).div(1e18); } // Returns the value of excess collateral held in this pool, compared to what is needed to maintain the global collateral ratio function getExcessCollateralValue() public view returns (uint256) { uint256 totalCollateralValue = getTotalCollateralValue(); uint256 neededCollateralValue = getNeededCollateralValue(); if (totalCollateralValue > neededCollateralValue) return totalCollateralValue.sub(neededCollateralValue); return 0; } function getGapCollateralValue() public view returns(uint256) { uint256 totalCollateralValue = getTotalCollateralValue(); uint256 neededCollateralValue = getNeededCollateralValue(); if(totalCollateralValue < neededCollateralValue) return neededCollateralValue.sub(totalCollateralValue); return 0; } function getShareTokenPrice() public view returns(uint256) { return IOracle(shareTokenOracle).getLatestPrice(); } function getStableTokenPrice() public view returns(uint256) { return IOracle(stableTokenOracle).getLatestPrice(); } function getCollateralPrice(address token) public view returns (uint256) { return IOracle(collaterals[token].oracle).getLatestPrice(); } function getTotalCollateralValue() public view returns (uint256) { uint256 totalCollateralValue = 0; uint256 length = collateralTokens.length(); for (uint256 i = 0; i < length; ++i) totalCollateralValue = totalCollateralValue.add(getCollateralValue(collateralTokens.at(i))); return totalCollateralValue; } function getCollateralValue(address token) public view returns (uint256) { if(isCollateralToken(token)) return getCollateralizedBalance(token).mul(getCollateralPrice(token)).div(collaterals[token].precision); return 0; } function isCollateralToken(address token) public view returns (bool) { return collateralTokens.contains(token); } function getCollateralTokens() public view returns (address[] memory) { uint256 length = collateralTokens.length(); address[] memory tokens = new address[](length); for (uint256 i = 0; i < length; ++i) tokens[i] = collateralTokens.at(i); return tokens; } function getCollateralizedBalance(address token) public view returns(uint256) { address tt = (token == NATIVE_TOKEN_ADDRESS) ? wrappedNativeToken : token; uint256 balance = IERC20(tt).balanceOf(address(this)); return balance.sub(Math.min(balance, unclaimedCollaterals[token])); } function setStableTokenOracle(address newStableTokenOracle) public onlyOwner { stableTokenOracle = newStableTokenOracle; } function setShareTokenOracle(address newShareTokenOracle) public onlyOwner { shareTokenOracle = newShareTokenOracle; } function setRedeemFee(uint256 newRedeemFee) external onlyOwner { redeemFee = newRedeemFee; } function setMintFee(uint256 newMintFee) external onlyOwner { mintFee = newMintFee; } function setBuybackFee(uint256 newBuybackFee) external onlyOwner { buybackFee = newBuybackFee; } function addCollateralToken(address token, address oracle, uint256 ceiling, uint256 recollateralizeFee) external onlyOwner { require(collateralTokens.add(token) || collaterals[token].deprecated, "duplicated-collateral-token"); if(token == NATIVE_TOKEN_ADDRESS) { collaterals[token].precision = 10**18; } else { uint256 decimals = IERC20Decimals(token).decimals(); require(decimals <= 18, "unexpected-collateral-token"); collaterals[token].precision = 10**decimals; } collaterals[token].deprecated = false; collaterals[token].oracle = oracle; collaterals[token].ceiling = ceiling; collaterals[token].recollateralizeFee = recollateralizeFee; } function deprecateCollateralToken(address token) external onlyOwner { require(isCollateralToken(token), "not-found-collateral-token"); collaterals[token].deprecated = true; } function removeCollateralToken(address token) external onlyOwner { require(collaterals[token].deprecated, "undeprecated-collateral-token"); require(collateralTokens.remove(token), "not-found-token"); delete collaterals[token]; } function updateCollateralToken(address token, address newOracle, uint256 newCeiling, uint256 newRecollateralizeFee) public onlyOwner { require(isCollateralToken(token), "not-found-collateral-token"); collaterals[token].ceiling = newCeiling; collaterals[token].oracle = newOracle; collaterals[token].recollateralizeFee = newRecollateralizeFee; } function setRefreshPeriod(uint256 newRefreshPeriod) external onlyOwner { refreshPeriod = newRefreshPeriod; } function setRefreshStep(uint256 newRefreshStep) external onlyOwner { refreshStep = newRefreshStep; } function setRefreshBand(uint256 newRefreshBand) external onlyOwner { refreshBand = newRefreshBand; } function setProtocolFund(address payable newProtocolFund) public onlyOwner { protocolFund = newProtocolFund; } function setFlashloanFee(uint256 newFlashloanFee) public onlyOwner { flashloanFee = newFlashloanFee; } function setGlobalCollateralRatio(uint256 newGlobalCollateralRatio) public onlyOwner { globalCollateralRatio = newGlobalCollateralRatio; } function setShareBondCeiling(uint256 newShareBondCeiling) public onlyOwner { shareBondCeiling = newShareBondCeiling; } function setBuybackBonus(uint256 newBuybackBonus) public onlyOwner { buybackBonus = newBuybackBonus; } function setKbtToKunImmediately() public onlyOwner { kbtToKunImmediately = !kbtToKunImmediately; } function _withdrawTo(address token, address payable to, uint256 amount) internal { if(token == NATIVE_TOKEN_ADDRESS) { IWrappedNativeToken(wrappedNativeToken).withdraw(amount); to.transfer(amount); } else { IERC20(token).transfer(to, amount); } } function _depositFrom(address token, address from, uint256 amount) internal { if(token == NATIVE_TOKEN_ADDRESS) { require(msg.value == amount, "msg.value != amount"); IWrappedNativeToken(wrappedNativeToken).deposit{value: amount}(); } else { IERC20(token).transferFrom(from, address(this), amount); } } receive() external payable { // require(msg.sender == wrappedNativeToken, "Only WXXX can send ether"); } }
计算赎回抵押物的数量和手续费(以抵押物计)
function calculateCollateralRedeemAmount(uint256 stableAmount, address collateralToken) public view returns (uint256, uint256) { uint256 redeemAmount = calculateEquivalentCollateralAmount(stableAmount, collateralToken); uint256 redeemFeeAmount = redeemAmount.mul(redeemFee).div(1e18); return (redeemAmount.sub(redeemFeeAmount), redeemFeeAmount); }
2,099,506
[ 1, 169, 111, 99, 168, 111, 250, 169, 118, 241, 166, 254, 257, 167, 237, 118, 167, 237, 125, 168, 236, 107, 168, 253, 231, 167, 248, 113, 170, 234, 242, 166, 245, 239, 167, 236, 238, 168, 124, 260, 169, 117, 122, 12, 165, 124, 103, 167, 237, 118, 167, 237, 125, 168, 236, 107, 169, 111, 99, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4604, 13535, 2045, 287, 426, 24903, 6275, 12, 11890, 5034, 14114, 6275, 16, 1758, 4508, 2045, 287, 1345, 13, 1071, 1476, 1135, 261, 11890, 5034, 16, 2254, 5034, 13, 288, 203, 3639, 2254, 5034, 283, 24903, 6275, 273, 4604, 22606, 13535, 2045, 287, 6275, 12, 15021, 6275, 16, 4508, 2045, 287, 1345, 1769, 203, 3639, 2254, 5034, 283, 24903, 14667, 6275, 273, 283, 24903, 6275, 18, 16411, 12, 266, 24903, 14667, 2934, 2892, 12, 21, 73, 2643, 1769, 203, 3639, 327, 261, 266, 24903, 6275, 18, 1717, 12, 266, 24903, 14667, 6275, 3631, 283, 24903, 14667, 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 ]
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; pragma abicoder v2; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./libraries/UniswapLibrary.sol"; import "./BlockLock.sol"; import "./interfaces/IxTokenManager.sol"; import "./interfaces/IxAsset.sol"; contract xAssetCLR is Initializable, ERC20Upgradeable, OwnableUpgradeable, PausableUpgradeable, BlockLock { using SafeMath for uint256; using SafeERC20 for IERC20; uint256 private constant SWAP_SLIPPAGE = 50; // 2% uint256 private constant MINT_BURN_SLIPPAGE = 100; // 1% // Used to give an identical token representation uint8 private constant TOKEN_DECIMAL_REPRESENTATION = 18; int24 tickLower; int24 tickUpper; // Prices calculated using above ticks from TickMath.getSqrtRatioAtTick() uint160 priceLower; uint160 priceUpper; int128 lastTwap; // Last stored oracle twap // Max current twap vs last twap deviation percentage divisor (100 = 1%) uint256 maxTwapDeviationDivisor; IERC20 token0; IERC20 token1; uint256 public tokenId; // token id representing this uniswap position uint256 public token0DecimalMultiplier; // 10 ** (18 - token0 decimals) uint256 public token1DecimalMultiplier; // 10 ** (18 - token1 decimals) uint256 public tokenDiffDecimalMultiplier; // 10 ** (token0 decimals - token1 decimals) uint24 public poolFee; uint8 public token0Decimals; uint8 public token1Decimals; UniswapContracts public uniContracts; IxTokenManager xTokenManager; // xToken manager contract uint32 twapPeriod; struct UniswapContracts { address pool; address router; address quoter; address positionManager; } event Rebalance(); event FeeCollected(uint256 token0Fee, uint256 token1Fee); function initialize( string memory _symbol, int24 _tickLower, int24 _tickUpper, IERC20 _token0, IERC20 _token1, UniswapContracts memory contracts, address _xTokenManagerAddress, uint256 _maxTwapDeviationDivisor, uint8 _token0Decimals, uint8 _token1Decimals ) external initializer { __Context_init_unchained(); __Ownable_init_unchained(); __Pausable_init_unchained(); __ERC20_init_unchained("xAssetCLR", _symbol); tickLower = _tickLower; tickUpper = _tickUpper; priceLower = UniswapLibrary.getSqrtRatio(_tickLower); priceUpper = UniswapLibrary.getSqrtRatio(_tickUpper); token0 = _token0; token1 = _token1; token0Decimals = _token0Decimals; token1Decimals = _token1Decimals; token0DecimalMultiplier = 10**(TOKEN_DECIMAL_REPRESENTATION - token0Decimals); token1DecimalMultiplier = 10**(TOKEN_DECIMAL_REPRESENTATION - token1Decimals); tokenDiffDecimalMultiplier = 10**((UniswapLibrary.subAbs(token0Decimals, token1Decimals))); maxTwapDeviationDivisor = _maxTwapDeviationDivisor; poolFee = 3000; uniContracts = contracts; token0.safeIncreaseAllowance(uniContracts.router, type(uint256).max); token1.safeIncreaseAllowance(uniContracts.router, type(uint256).max); token0.safeIncreaseAllowance( uniContracts.positionManager, type(uint256).max ); token1.safeIncreaseAllowance( uniContracts.positionManager, type(uint256).max ); UniswapLibrary.approveOneInch(token0, token1); xTokenManager = IxTokenManager(_xTokenManagerAddress); lastTwap = getAsset0Price(); twapPeriod = 3600; } /* ========================================================================================= */ /* User-facing */ /* ========================================================================================= */ /** * @dev Mint xAssetCLR tokens by sending *amount* of *inputAsset* tokens * @dev amount of the other asset is auto-calculated */ function mint(uint8 inputAsset, uint256 amount) external notLocked(msg.sender) whenNotPaused() { require(amount > 0); lock(msg.sender); checkTwap(); (uint256 amount0, uint256 amount1) = calculateAmountsMintedSingleToken(inputAsset, amount); // Check if address has enough balance uint256 token0Balance = token0.balanceOf(msg.sender); uint256 token1Balance = token1.balanceOf(msg.sender); if (amount0 > token0Balance || amount1 > token1Balance) { amount0 = amount0 > token0Balance ? token0Balance : amount0; amount1 = amount1 > token1Balance ? token1Balance : amount1; (amount0, amount1) = calculatePoolMintedAmounts(amount0, amount1); } token0.safeTransferFrom(msg.sender, address(this), amount0); token1.safeTransferFrom(msg.sender, address(this), amount1); uint128 liquidityAmount = getLiquidityForAmounts(amount0, amount1); _mintInternal(liquidityAmount); // stake tokens in pool _stake(amount0, amount1); } /** * @dev Burn *amount* of xAssetCLR tokens to receive proportional * amount of pool tokens */ function burn(uint256 amount) external notLocked(msg.sender) { require(amount > 0); lock(msg.sender); checkTwap(); uint256 totalLiquidity = getTotalLiquidity(); uint256 proRataBalance = amount.mul(totalLiquidity).div(totalSupply()); super._burn(msg.sender, amount); (uint256 amount0, uint256 amount1) = getAmountsForLiquidity(uint128(proRataBalance)); uint256 unstakeAmount0 = amount0.add(amount0.div(MINT_BURN_SLIPPAGE)); uint256 unstakeAmount1 = amount1.add(amount1.div(MINT_BURN_SLIPPAGE)); _unstake(unstakeAmount0, unstakeAmount1); token0.safeTransfer(msg.sender, amount0); token1.safeTransfer(msg.sender, amount1); } function transfer(address recipient, uint256 amount) public override notLocked(msg.sender) returns (bool) { return super.transfer(recipient, amount); } function transferFrom( address sender, address recipient, uint256 amount ) public override notLocked(sender) returns (bool) { return super.transferFrom(sender, recipient, amount); } /** * @notice Get Net Asset Value in terms of token 1 * @dev NAV = token 0 amt * token 0 price + token1 amt */ function getNav() public view returns (uint256) { return getStakedBalance().add(getBufferBalance()); } /** * @dev Returns amount in terms of asset 0 * @dev amount * asset 1 price */ function getAmountInAsset0Terms(uint256 amount) public view returns (uint256) { return UniswapLibrary.getAmountInAsset0Terms( amount, uniContracts.pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ); } /** * @dev Returns amount in terms of asset 1 * @dev amount * asset 0 price */ function getAmountInAsset1Terms(uint256 amount) public view returns (uint256) { return UniswapLibrary.getAmountInAsset1Terms( amount, uniContracts.pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ); } /** * @notice Get balance in xAssetCLR contract * @notice amount is represented in token 1 terms: * @dev token 0 amt * token 0 price + token1 amt */ function getBufferBalance() public view returns (uint256) { (uint256 balance0, uint256 balance1) = getBufferTokenBalance(); return getAmountInAsset1Terms(balance0).add(balance1); } /** * @notice Get total balance in the position * @notice amount is represented in token 1 terms: * @dev token 0 amt * token 0 price + token1 amt */ function getStakedBalance() public view returns (uint256) { (uint256 amount0, uint256 amount1) = getStakedTokenBalance(); return getAmountInAsset1Terms(amount0).add(amount1); } /** * @notice Get token balances in xAssetCLR contract * @dev returned balances are represented with 18 decimals */ function getBufferTokenBalance() public view returns (uint256 amount0, uint256 amount1) { return (getBufferToken0Balance(), getBufferToken1Balance()); } /** * @notice Get token0 balance in xAssetCLR * @dev returned balance is represented with 18 decimals */ function getBufferToken0Balance() public view returns (uint256 amount0) { return getToken0AmountInWei(token0.balanceOf(address(this))); } /** * @notice Get token1 balance in xAssetCLR * @dev returned balance is represented with 18 decimals */ function getBufferToken1Balance() public view returns (uint256 amount1) { return getToken1AmountInWei(token1.balanceOf(address(this))); } /** * @notice Get token balances in the position * @dev returned balance is represented with 18 decimals */ function getStakedTokenBalance() public view returns (uint256 amount0, uint256 amount1) { (amount0, amount1) = getAmountsForLiquidity(getPositionLiquidity()); amount0 = getToken0AmountInWei(amount0); amount1 = getToken1AmountInWei(amount1); } /** * @notice Get total liquidity * @dev buffer liquidity + position liquidity */ function getTotalLiquidity() public view returns (uint256 amount) { (uint256 buffer0, uint256 buffer1) = getBufferTokenBalance(); uint128 bufferLiquidity = getLiquidityForAmounts(buffer0, buffer1); uint128 positionLiquidity = getPositionLiquidity(); return uint256(bufferLiquidity).add(uint256(positionLiquidity)); } /** * @dev Check how much xAssetCLR tokens will be minted on mint * @dev Uses position liquidity to calculate the amount */ function calculateMintAmount(uint256 _amount, uint256 totalSupply) public view returns (uint256 mintAmount) { if (totalSupply == 0) return _amount; uint256 previousLiquidity = getTotalLiquidity().sub(_amount); mintAmount = (_amount).mul(totalSupply).div(previousLiquidity); return mintAmount; } /* ========================================================================================= */ /* Management */ /* ========================================================================================= */ /** * @dev Collect rewards from pool and stake them in position * @dev may leave unstaked tokens in contract */ function collectAndRestake() external onlyOwnerOrManager { (uint256 amount0, uint256 amount1) = collect(); (uint256 stakeAmount0, uint256 stakeAmount1) = calculatePoolMintedAmounts(amount0, amount1); _stake(stakeAmount0, stakeAmount1); } /** * @dev Collect fees generated from position */ function collect() public onlyOwnerOrManager returns (uint256 collected0, uint256 collected1) { (collected0, collected1) = collectPosition( type(uint128).max, type(uint128).max ); emit FeeCollected(collected0, collected1); } /** * @dev Migrate the current position to a new position with different ticks */ function migratePosition(int24 newTickLower, int24 newTickUpper) public onlyOwnerOrManager { require(newTickLower != tickLower || newTickUpper != tickUpper); // withdraw entire liquidity from the position (uint256 _amount0, uint256 _amount1) = withdrawAll(); // burn current position NFT UniswapLibrary.burn(uniContracts.positionManager, tokenId); // set new ticks and prices tickLower = newTickLower; tickUpper = newTickUpper; priceLower = UniswapLibrary.getSqrtRatio(newTickLower); priceUpper = UniswapLibrary.getSqrtRatio(newTickUpper); (uint256 amount0, uint256 amount1) = calculatePoolMintedAmounts(_amount0, _amount1); // mint the position NFT and deposit the liquidity // set new NFT token id tokenId = createPosition(amount0, amount1); } /** * @dev Migrate the current position to a new position with different ticks * @dev Migrates position tick lower and upper by same amount of ticks * @dev Tick spacing (minimum tick difference) in pool w/ 3000 fee is 60 * @param ticks how many ticks to shift up or down * @param up whether to move tick range up or down */ function migrateParallel(uint24 ticks, bool up) external onlyOwnerOrManager { require(ticks != 0); int24 newTickLower; int24 newTickUpper; int24 ticksToShift = int24(ticks) * 60; if (up) { newTickLower = tickLower + ticksToShift; newTickUpper = tickUpper + ticksToShift; } else { newTickLower = tickLower - ticksToShift; newTickUpper = tickUpper - ticksToShift; } migratePosition(newTickLower, newTickUpper); } /** * @dev Mint function which initializes the pool position * @dev Must be called before any liquidity can be deposited */ function mintInitial(uint256 amount0, uint256 amount1) external onlyOwnerOrManager { require(tokenId == 0); require(amount0 > 0 || amount1 > 0); checkTwap(); (uint256 amount0Minted, uint256 amount1Minted) = calculatePoolMintedAmounts(amount0, amount1); token0.safeTransferFrom(msg.sender, address(this), amount0Minted); token1.safeTransferFrom(msg.sender, address(this), amount1Minted); tokenId = createPosition(amount0Minted, amount1Minted); uint256 liquidity = uint256(getLiquidityForAmounts(amount0Minted, amount1Minted)); _mintInternal(liquidity); } /** * @dev Admin function to stake tokens * @dev used in case there's leftover tokens in the contract */ function adminRebalance() external onlyOwnerOrManager { UniswapLibrary.adminRebalance( UniswapLibrary.TokenDetails({ token0: address(token0), token1: address(token1), token0DecimalMultiplier: token0DecimalMultiplier, token1DecimalMultiplier: token1DecimalMultiplier, tokenDiffDecimalMultiplier: tokenDiffDecimalMultiplier, token0Decimals: token0Decimals, token1Decimals: token1Decimals }), UniswapLibrary.PositionDetails({ poolFee: poolFee, twapPeriod: twapPeriod, priceLower: priceLower, priceUpper: priceUpper, tokenId: tokenId, positionManager: uniContracts.positionManager, router: uniContracts.router, quoter: uniContracts.quoter, pool: uniContracts.pool }) ); emit Rebalance(); } /** * @dev Admin function for staking in position */ function adminStake(uint256 amount0, uint256 amount1) external onlyOwnerOrManager { (uint256 stakeAmount0, uint256 stakeAmount1) = calculatePoolMintedAmounts(amount0, amount1); _stake(stakeAmount0, stakeAmount1); } /** * @dev Admin function for unstaking from position */ function adminUnstake(uint256 amount0, uint256 amount1) external onlyOwnerOrManager { _unstake(amount0, amount1); } /** * @dev Admin function for swapping LP tokens in xAssetCLR * @param amount - swap amount (in t0 terms if _0for1 is true, in t1 terms if false) * @param _0for1 - swap token 0 for 1 if true, token 1 for 0 if false */ function adminSwap(uint256 amount, bool _0for1) external onlyOwnerOrManager { if (_0for1) { swapToken0ForToken1(amount.add(amount.div(SWAP_SLIPPAGE)), amount); } else { swapToken1ForToken0(amount.add(amount.div(SWAP_SLIPPAGE)), amount); } } /** * @dev Admin function for swapping LP tokens in xAssetCLR using 1inch v3 exchange * @param minReturn - how much output tokens to receive on swap, in 18 decimals * @param _0for1 - swap token 0 for token 1 if true, token 1 for token 0 if false * @param _oneInchData - 1inch calldata, generated off-chain using their v3 api */ function adminSwapOneInch( uint256 minReturn, bool _0for1, bytes memory _oneInchData ) external onlyOwnerOrManager { UniswapLibrary.oneInchSwap( minReturn, _0for1, UniswapLibrary.TokenDetails({ token0: address(token0), token1: address(token1), token0DecimalMultiplier: token0DecimalMultiplier, token1DecimalMultiplier: token1DecimalMultiplier, tokenDiffDecimalMultiplier: tokenDiffDecimalMultiplier, token0Decimals: token0Decimals, token1Decimals: token1Decimals }), _oneInchData ); } /** * @dev Stake liquidity in position */ function _stake(uint256 amount0, uint256 amount1) private returns (uint256 stakedAmount0, uint256 stakedAmount1) { return UniswapLibrary.stake( amount0, amount1, uniContracts.positionManager, tokenId ); } /** * @dev Unstake liquidity from position */ function _unstake(uint256 amount0, uint256 amount1) private returns (uint256 collected0, uint256 collected1) { uint128 liquidityAmount = getLiquidityForAmounts(amount0, amount1); (uint256 _amount0, uint256 _amount1) = unstakePosition(liquidityAmount); return collectPosition(uint128(_amount0), uint128(_amount1)); } /** * @dev Withdraws all current liquidity from the position */ function withdrawAll() private returns (uint256 _amount0, uint256 _amount1) { // Collect fees collect(); (_amount0, _amount1) = unstakePosition(getPositionLiquidity()); collectPosition(uint128(_amount0), uint128(_amount1)); } /** * @dev Creates the NFT token representing the pool position * @dev Mint initial liquidity */ function createPosition(uint256 amount0, uint256 amount1) private returns (uint256 _tokenId) { UniswapLibrary.TokenDetails memory tokenDetails = UniswapLibrary.TokenDetails({ token0: address(token0), token1: address(token1), token0DecimalMultiplier: token0DecimalMultiplier, token1DecimalMultiplier: token1DecimalMultiplier, tokenDiffDecimalMultiplier: tokenDiffDecimalMultiplier, token0Decimals: token0Decimals, token1Decimals: token1Decimals }); UniswapLibrary.PositionDetails memory positionDetails = UniswapLibrary.PositionDetails({ poolFee: poolFee, twapPeriod: twapPeriod, priceLower: priceLower, priceUpper: priceUpper, tokenId: tokenId, positionManager: uniContracts.positionManager, router: uniContracts.router, quoter: uniContracts.quoter, pool: uniContracts.pool }); return UniswapLibrary.createPosition( amount0, amount1, uniContracts.positionManager, tokenDetails, positionDetails ); } /** * @dev Unstakes a given amount of liquidity from the Uni V3 position * @param liquidity amount of liquidity to unstake * @return amount0 token0 amount unstaked * @return amount1 token1 amount unstaked */ function unstakePosition(uint128 liquidity) private returns (uint256 amount0, uint256 amount1) { UniswapLibrary.PositionDetails memory positionDetails = UniswapLibrary.PositionDetails({ poolFee: poolFee, twapPeriod: twapPeriod, priceLower: priceLower, priceUpper: priceUpper, tokenId: tokenId, positionManager: uniContracts.positionManager, router: uniContracts.router, quoter: uniContracts.quoter, pool: uniContracts.pool }); return UniswapLibrary.unstakePosition(liquidity, positionDetails); } function _mintInternal(uint256 _amount) private { uint256 mintAmount = calculateMintAmount(_amount, totalSupply()); return super._mint(msg.sender, mintAmount); } /* * Emergency function in case of errant transfer * of any token directly to contract */ function withdrawToken(address token, address receiver) external onlyOwnerOrManager { require(token != address(token0) && token != address(token1)); uint256 tokenBal = IERC20(address(token)).balanceOf(address(this)); IERC20(address(token)).safeTransfer(receiver, tokenBal); } /** * Mint xAsset tokens using underlying * xAsset contract needs to be approved * @param amount amount to mint * @param isToken0 if true, call mint on token0, else on token1 */ function adminMint(uint256 amount, bool isToken0) external onlyOwnerOrManager { if(isToken0) { IxAsset(address(token0)).mintWithToken(amount); } else { IxAsset(address(token1)).mintWithToken(amount); } } /** * Burn xAsset tokens using underlying * @param amount amount to burn * @param isToken0 if true, call burn on token0, else on token1 */ function adminBurn(uint256 amount, bool isToken0) external onlyOwnerOrManager { if(isToken0) { IxAsset(address(token0)).burn(amount, false, 1); } else { IxAsset(address(token1)).burn(amount, false, 1); } } /** * Approve underlying token to xAsset tokens * @param isToken0 if token 0 is xAsset token, set to true, otherwise false */ function adminApprove(bool isToken0) external onlyOwnerOrManager { if(isToken0) { token1.safeApprove(address(token0), type(uint256).max); } else { token0.safeApprove(address(token1), type(uint256).max); } } function pauseContract() external onlyOwnerOrManager returns (bool) { _pause(); return true; } function unpauseContract() external onlyOwnerOrManager returns (bool) { _unpause(); return true; } modifier onlyOwnerOrManager { require( msg.sender == owner() || xTokenManager.isManager(msg.sender, address(this)), "Function may be called only by owner or manager" ); _; } /* ========================================================================================= */ /* Uniswap helpers */ /* ========================================================================================= */ /** * @dev Swap token 0 for token 1 in xAssetCLR using Uni V3 Pool * @dev amounts should be in 18 decimals * @param amountIn - amount as maximum input for swap, in token 0 terms * @param amountOut - amount as output for swap, in token 0 terms */ function swapToken0ForToken1(uint256 amountIn, uint256 amountOut) private { UniswapLibrary.swapToken0ForToken1( amountIn, amountOut, UniswapLibrary.PositionDetails({ poolFee: poolFee, twapPeriod: twapPeriod, priceLower: priceLower, priceUpper: priceUpper, tokenId: tokenId, positionManager: uniContracts.positionManager, router: uniContracts.router, quoter: uniContracts.quoter, pool: uniContracts.pool }), UniswapLibrary.TokenDetails({ token0: address(token0), token1: address(token1), token0DecimalMultiplier: token0DecimalMultiplier, token1DecimalMultiplier: token1DecimalMultiplier, tokenDiffDecimalMultiplier: tokenDiffDecimalMultiplier, token0Decimals: token0Decimals, token1Decimals: token1Decimals }) ); } /** * @dev Swap token 1 for token 0 in xAssetCLR using Uni V3 Pool * @dev amounts should be in 18 decimals * @param amountIn - amount as maximum input for swap, in token 1 terms * @param amountOut - amount as output for swap, in token 1 terms */ function swapToken1ForToken0(uint256 amountIn, uint256 amountOut) private { UniswapLibrary.swapToken1ForToken0( amountIn, amountOut, UniswapLibrary.PositionDetails({ poolFee: poolFee, twapPeriod: twapPeriod, priceLower: priceLower, priceUpper: priceUpper, tokenId: tokenId, positionManager: uniContracts.positionManager, router: uniContracts.router, quoter: uniContracts.quoter, pool: uniContracts.pool }), UniswapLibrary.TokenDetails({ token0: address(token0), token1: address(token1), token0DecimalMultiplier: token0DecimalMultiplier, token1DecimalMultiplier: token1DecimalMultiplier, tokenDiffDecimalMultiplier: tokenDiffDecimalMultiplier, token0Decimals: token0Decimals, token1Decimals: token1Decimals }) ); } /** * @dev Collect token amounts from pool position */ function collectPosition(uint128 amount0, uint128 amount1) private returns (uint256 collected0, uint256 collected1) { return UniswapLibrary.collectPosition( amount0, amount1, tokenId, uniContracts.positionManager ); } /** * @dev Change pool fee and address */ function changePool(address _poolAddress, uint24 _poolFee) external onlyOwnerOrManager { uniContracts.pool = _poolAddress; poolFee = _poolFee; } // Returns the current liquidity in the position function getPositionLiquidity() public view returns (uint128 liquidity) { return UniswapLibrary.getPositionLiquidity( uniContracts.positionManager, tokenId ); } /** * @dev Get asset 0 twap * @dev Uses Uni V3 oracle, reading the TWAP from twap period * @dev or the earliest oracle observation time if twap period is not set */ function getAsset0Price() public view returns (int128) { return UniswapLibrary.getAsset0Price( uniContracts.pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ); } /** * @dev Get asset 1 twap * @dev Uses Uni V3 oracle, reading the TWAP from twap period * @dev or the earliest oracle observation time if twap period is not set */ function getAsset1Price() public view returns (int128) { return UniswapLibrary.getAsset1Price( uniContracts.pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ); } /** * @dev Checks if twap deviates too much from the previous twap */ function checkTwap() private { lastTwap = UniswapLibrary.checkTwap( uniContracts.pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier, lastTwap, maxTwapDeviationDivisor ); } /** * @dev Reset last twap if oracle price is consistently above the max deviation */ function resetTwap() external onlyOwnerOrManager { lastTwap = getAsset0Price(); } /** * @dev Set the max twap deviation divisor * @dev if twap moves more than the divisor specified * @dev mint, burn and mintInitial functions are locked */ function setMaxTwapDeviationDivisor(uint256 newDeviationDivisor) external onlyOwnerOrManager { maxTwapDeviationDivisor = newDeviationDivisor; } /** * @dev Set the oracle reading twap period * @dev Twap used is [now - twapPeriod, now] */ function setTwapPeriod(uint32 newPeriod) external onlyOwnerOrManager { require(newPeriod >= 360); twapPeriod = newPeriod; } /** * @dev Calculates the amounts deposited/withdrawn from the pool * amount0, amount1 - amounts to deposit/withdraw * amount0Minted, amount1Minted - actual amounts which can be deposited */ function calculatePoolMintedAmounts(uint256 amount0, uint256 amount1) public view returns (uint256 amount0Minted, uint256 amount1Minted) { uint128 liquidityAmount = getLiquidityForAmounts(amount0, amount1); (amount0Minted, amount1Minted) = getAmountsForLiquidity( liquidityAmount ); } /** * @dev Calculates single-side minted amount * @param inputAsset - use token0 if 0, token1 else * @param amount - amount to deposit/withdraw */ function calculateAmountsMintedSingleToken(uint8 inputAsset, uint256 amount) public view returns (uint256 amount0Minted, uint256 amount1Minted) { uint128 liquidityAmount; if (inputAsset == 0) { liquidityAmount = getLiquidityForAmounts(amount, type(uint112).max); } else { liquidityAmount = getLiquidityForAmounts(type(uint112).max, amount); } (amount0Minted, amount1Minted) = getAmountsForLiquidity( liquidityAmount ); } function getLiquidityForAmounts(uint256 amount0, uint256 amount1) public view returns (uint128 liquidity) { liquidity = UniswapLibrary.getLiquidityForAmounts( amount0, amount1, priceLower, priceUpper, uniContracts.pool ); } function getAmountsForLiquidity(uint128 liquidity) public view returns (uint256 amount0, uint256 amount1) { (amount0, amount1) = UniswapLibrary.getAmountsForLiquidity( liquidity, priceLower, priceUpper, uniContracts.pool ); } /** * @dev Get lower and upper ticks of the pool position */ function getTicks() external view returns (int24 tick0, int24 tick1) { return (tickLower, tickUpper); } /** * Returns token0 amount in TOKEN_DECIMAL_REPRESENTATION */ function getToken0AmountInWei(uint256 amount) private view returns (uint256) { return UniswapLibrary.getToken0AmountInWei( amount, token0Decimals, token0DecimalMultiplier ); } /** * Returns token1 amount in TOKEN_DECIMAL_REPRESENTATION */ function getToken1AmountInWei(uint256 amount) private view returns (uint256) { return UniswapLibrary.getToken1AmountInWei( amount, token1Decimals, token1DecimalMultiplier ); } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../../utils/ContextUpgradeable.sol"; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { using SafeMathUpgradeable 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. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view 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 { } uint256[44] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; pragma abicoder v2; import "@uniswap/v3-periphery/contracts/interfaces/INonfungiblePositionManager.sol"; import "@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol"; import "@uniswap/v3-periphery/contracts/interfaces/IQuoter.sol"; import "@uniswap/v3-periphery/contracts/libraries/LiquidityAmounts.sol"; import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; import "@uniswap/v3-core/contracts/libraries/TickMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./ABDKMath64x64.sol"; import "./Utils.sol"; /** * Helper library for Uniswap functions * Used in xAssetCLR */ library UniswapLibrary { using SafeMath for uint256; using SafeERC20 for IERC20; uint8 private constant TOKEN_DECIMAL_REPRESENTATION = 18; uint256 private constant SWAP_SLIPPAGE = 50; // 2% uint256 private constant MINT_BURN_SLIPPAGE = 100; // 1% // 1inch v3 exchange address address private constant oneInchExchange = 0x11111112542D85B3EF69AE05771c2dCCff4fAa26; struct TokenDetails { address token0; address token1; uint256 token0DecimalMultiplier; uint256 token1DecimalMultiplier; uint256 tokenDiffDecimalMultiplier; uint8 token0Decimals; uint8 token1Decimals; } struct PositionDetails { uint24 poolFee; uint32 twapPeriod; uint160 priceLower; uint160 priceUpper; uint256 tokenId; address positionManager; address router; address quoter; address pool; } struct AmountsMinted { uint256 amount0ToMint; uint256 amount1ToMint; uint256 amount0Minted; uint256 amount1Minted; } /* ========================================================================================= */ /* Uni V3 Pool Helper functions */ /* ========================================================================================= */ /** * @dev Returns the current pool price in X96 notation */ function getPoolPrice(address _pool) public view returns (uint160) { IUniswapV3Pool pool = IUniswapV3Pool(_pool); (uint160 sqrtRatioX96, , , , , , ) = pool.slot0(); return sqrtRatioX96; } /** * Get pool price in decimal notation with 12 decimals */ function getPoolPriceWithDecimals(address _pool) public view returns (uint256 price) { uint160 sqrtRatioX96 = getPoolPrice(_pool); return uint256(sqrtRatioX96).mul(uint256(sqrtRatioX96)).mul(1e12) >> 192; } /** * @dev Returns the current pool liquidity */ function getPoolLiquidity(address _pool) public view returns (uint128) { IUniswapV3Pool pool = IUniswapV3Pool(_pool); return pool.liquidity(); } /** * @dev Calculate pool liquidity for given token amounts */ function getLiquidityForAmounts( uint256 amount0, uint256 amount1, uint160 priceLower, uint160 priceUpper, address pool ) public view returns (uint128 liquidity) { liquidity = LiquidityAmounts.getLiquidityForAmounts( getPoolPrice(pool), priceLower, priceUpper, amount0, amount1 ); } /** * @dev Calculate token amounts for given pool liquidity */ function getAmountsForLiquidity( uint128 liquidity, uint160 priceLower, uint160 priceUpper, address pool ) public view returns (uint256 amount0, uint256 amount1) { (amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity( getPoolPrice(pool), priceLower, priceUpper, liquidity ); } /** * @dev Calculates the amounts deposited/withdrawn from the pool * @param amount0 - token0 amount to deposit/withdraw * @param amount1 - token1 amount to deposit/withdraw */ function calculatePoolMintedAmounts( uint256 amount0, uint256 amount1, uint160 priceLower, uint160 priceUpper, address pool ) public view returns (uint256 amount0Minted, uint256 amount1Minted) { uint128 liquidityAmount = getLiquidityForAmounts( amount0, amount1, priceLower, priceUpper, pool ); (amount0Minted, amount1Minted) = getAmountsForLiquidity( liquidityAmount, priceLower, priceUpper, pool ); } /** * @dev Get asset 0 twap * @dev Uses Uni V3 oracle, reading the TWAP from twap period * @dev or the earliest oracle observation time if twap period is not set */ function getAsset0Price( address pool, uint32 twapPeriod, uint8 token0Decimals, uint8 token1Decimals, uint256 tokenDiffDecimalMultiplier ) public view returns (int128) { uint32[] memory secondsArray = new uint32[](2); // get earliest oracle observation time IUniswapV3Pool poolImpl = IUniswapV3Pool(pool); uint32 observationTime = getObservationTime(poolImpl); uint32 currTimestamp = uint32(block.timestamp); uint32 earliestObservationSecondsAgo = currTimestamp - observationTime; if ( twapPeriod == 0 || !Utils.lte( currTimestamp, observationTime, currTimestamp - twapPeriod ) ) { // set to earliest observation time if: // a) twap period is 0 (not set) // b) now - twap period is before earliest observation secondsArray[0] = earliestObservationSecondsAgo; } else { secondsArray[0] = twapPeriod; } secondsArray[1] = 0; (int56[] memory prices, ) = poolImpl.observe(secondsArray); int128 twap = Utils.getTWAP(prices, secondsArray[0]); if (token1Decimals > token0Decimals) { // divide twap by token decimal difference twap = ABDKMath64x64.mul( twap, ABDKMath64x64.divu(1, tokenDiffDecimalMultiplier) ); } else if (token0Decimals > token1Decimals) { // multiply twap by token decimal difference int128 multiplierFixed = ABDKMath64x64.fromUInt(tokenDiffDecimalMultiplier); twap = ABDKMath64x64.mul(twap, multiplierFixed); } return twap; } /** * @dev Get asset 1 twap * @dev Uses Uni V3 oracle, reading the TWAP from twap period * @dev or the earliest oracle observation time if twap period is not set */ function getAsset1Price( address pool, uint32 twapPeriod, uint8 token0Decimals, uint8 token1Decimals, uint256 tokenDiffDecimalMultiplier ) public view returns (int128) { return ABDKMath64x64.inv( getAsset0Price( pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ) ); } /** * @dev Returns amount in terms of asset 0 * @dev amount * asset 1 price */ function getAmountInAsset0Terms( uint256 amount, address pool, uint32 twapPeriod, uint8 token0Decimals, uint8 token1Decimals, uint256 tokenDiffDecimalMultiplier ) public view returns (uint256) { return ABDKMath64x64.mulu( getAsset1Price( pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ), amount ); } /** * @dev Returns amount in terms of asset 1 * @dev amount * asset 0 price */ function getAmountInAsset1Terms( uint256 amount, address pool, uint32 twapPeriod, uint8 token0Decimals, uint8 token1Decimals, uint256 tokenDiffDecimalMultiplier ) public view returns (uint256) { return ABDKMath64x64.mulu( getAsset0Price( pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ), amount ); } /** * @dev Returns the earliest oracle observation time */ function getObservationTime(IUniswapV3Pool _pool) public view returns (uint32) { IUniswapV3Pool pool = _pool; (, , uint16 index, uint16 cardinality, , , ) = pool.slot0(); uint16 oldestObservationIndex = (index + 1) % cardinality; (uint32 observationTime, , , bool initialized) = pool.observations(oldestObservationIndex); if (!initialized) (observationTime, , , ) = pool.observations(0); return observationTime; } /** * @dev Checks if twap deviates too much from the previous twap * @return current twap */ function checkTwap( address pool, uint32 twapPeriod, uint8 token0Decimals, uint8 token1Decimals, uint256 tokenDiffDecimalMultiplier, int128 lastTwap, uint256 maxTwapDeviationDivisor ) public view returns (int128) { int128 twap = getAsset0Price( pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ); int128 _lastTwap = lastTwap; int128 deviation = _lastTwap > twap ? _lastTwap - twap : twap - _lastTwap; int128 maxDeviation = ABDKMath64x64.mul( twap, ABDKMath64x64.divu(1, maxTwapDeviationDivisor) ); require(deviation <= maxDeviation, "Wrong twap"); return twap; } /* ========================================================================================= */ /* Uni V3 Swap Router Helper functions */ /* ========================================================================================= */ /** * @dev Swap token 0 for token 1 in xAssetCLR contract * @dev amountIn and amountOut should be in 18 decimals always * @dev amountIn and amountOut are in token 0 terms */ function swapToken0ForToken1( uint256 amountIn, uint256 amountOut, PositionDetails memory positionDetails, TokenDetails memory tokenDetails ) public returns (uint256 _amountOut) { uint256 midPrice = getPoolPriceWithDecimals(positionDetails.pool); amountOut = amountOut.mul(midPrice).div(1e12); uint256 token0Balance = getBufferToken0Balance( IERC20(tokenDetails.token0), tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); require( token0Balance >= amountIn, "Swap token 0 for token 1: not enough token 0 balance" ); amountIn = getToken0AmountInNativeDecimals( amountIn, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); amountOut = getToken1AmountInNativeDecimals( amountOut, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); uint256 amountOutExpected = IQuoter(positionDetails.quoter).quoteExactInputSingle( tokenDetails.token0, tokenDetails.token1, positionDetails.poolFee, amountIn, TickMath.MIN_SQRT_RATIO + 1 ); if (amountOutExpected < amountOut) { amountOut = amountOutExpected; } ISwapRouter(positionDetails.router).exactOutputSingle( ISwapRouter.ExactOutputSingleParams({ tokenIn: tokenDetails.token0, tokenOut: tokenDetails.token1, fee: positionDetails.poolFee, recipient: address(this), deadline: block.timestamp, amountOut: amountOut, amountInMaximum: amountIn, sqrtPriceLimitX96: TickMath.MIN_SQRT_RATIO + 1 }) ); return amountOut; } /** * @dev Swap token 1 for token 0 in xAssetCLR contract * @dev amountIn and amountOut should be in 18 decimals always * @dev amountIn and amountOut are in token 1 terms */ function swapToken1ForToken0( uint256 amountIn, uint256 amountOut, PositionDetails memory positionDetails, TokenDetails memory tokenDetails ) public returns (uint256 _amountIn) { uint256 midPrice = getPoolPriceWithDecimals(positionDetails.pool); amountOut = amountOut.mul(1e12).div(midPrice); uint256 token1Balance = getBufferToken1Balance( IERC20(tokenDetails.token1), tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); require( token1Balance >= amountIn, "Swap token 1 for token 0: not enough token 1 balance" ); amountIn = getToken1AmountInNativeDecimals( amountIn, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); amountOut = getToken0AmountInNativeDecimals( amountOut, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); uint256 amountOutExpected = IQuoter(positionDetails.quoter).quoteExactInputSingle( tokenDetails.token1, tokenDetails.token0, positionDetails.poolFee, amountIn, TickMath.MAX_SQRT_RATIO - 1 ); if (amountOutExpected < amountOut) { amountOut = amountOutExpected; } ISwapRouter(positionDetails.router).exactOutputSingle( ISwapRouter.ExactOutputSingleParams({ tokenIn: tokenDetails.token1, tokenOut: tokenDetails.token0, fee: positionDetails.poolFee, recipient: address(this), deadline: block.timestamp, amountOut: amountOut, amountInMaximum: amountIn, sqrtPriceLimitX96: TickMath.MAX_SQRT_RATIO - 1 }) ); return amountIn; } /* ========================================================================================= */ /* 1inch Swap Helper functions */ /* ========================================================================================= */ /** * @dev Swap tokens in xAssetCLR using 1inch v3 exchange * @param minReturn - required min amount out from swap, in 18 decimals * @param _0for1 - swap token0 for token1 if true, token1 for token0 if false * @param tokenDetails - xAssetCLR token 0 and token 1 details * @param _oneInchData - One inch calldata, generated off-chain from their v3 api for the swap */ function oneInchSwap( uint256 minReturn, bool _0for1, TokenDetails memory tokenDetails, bytes memory _oneInchData ) public { uint256 token0AmtSwapped; uint256 token1AmtSwapped; bool success; // inline code to prevent stack too deep errors { IERC20 token0 = IERC20(tokenDetails.token0); IERC20 token1 = IERC20(tokenDetails.token1); uint256 balanceBeforeToken0 = token0.balanceOf(address(this)); uint256 balanceBeforeToken1 = token1.balanceOf(address(this)); (success, ) = oneInchExchange.call(_oneInchData); require(success, "One inch swap call failed"); uint256 balanceAfterToken0 = token0.balanceOf(address(this)); uint256 balanceAfterToken1 = token1.balanceOf(address(this)); token0AmtSwapped = subAbs(balanceAfterToken0, balanceBeforeToken0); token1AmtSwapped = subAbs(balanceAfterToken1, balanceBeforeToken1); } uint256 amountInSwapped; uint256 amountOutReceived; if (_0for1) { amountInSwapped = getToken0AmountInWei( token0AmtSwapped, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); amountOutReceived = getToken1AmountInWei( token1AmtSwapped, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); } else { amountInSwapped = getToken1AmountInWei( token1AmtSwapped, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); amountOutReceived = getToken0AmountInWei( token0AmtSwapped, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); } // require minimum amount received is > min return require( amountOutReceived > minReturn, "One inch swap not enough output token amount" ); } /** * Approve 1inch v3 for swaps */ function approveOneInch(IERC20 token0, IERC20 token1) public { token0.safeApprove(oneInchExchange, type(uint256).max); token1.safeApprove(oneInchExchange, type(uint256).max); } /* ========================================================================================= */ /* NFT Position Manager Helpers */ /* ========================================================================================= */ /** * @dev Returns the current liquidity in a position represented by tokenId NFT */ function getPositionLiquidity(address positionManager, uint256 tokenId) public view returns (uint128 liquidity) { (, , , , , , , liquidity, , , , ) = INonfungiblePositionManager( positionManager ) .positions(tokenId); } /** * @dev Stake liquidity in position represented by tokenId NFT */ function stake( uint256 amount0, uint256 amount1, address positionManager, uint256 tokenId ) public returns (uint256 stakedAmount0, uint256 stakedAmount1) { (, stakedAmount0, stakedAmount1) = INonfungiblePositionManager( positionManager ) .increaseLiquidity( INonfungiblePositionManager.IncreaseLiquidityParams({ tokenId: tokenId, amount0Desired: amount0, amount1Desired: amount1, amount0Min: amount0.sub(amount0.div(MINT_BURN_SLIPPAGE)), amount1Min: amount1.sub(amount1.div(MINT_BURN_SLIPPAGE)), deadline: block.timestamp }) ); } /** * @dev Unstakes a given amount of liquidity from the Uni V3 position * @param liquidity amount of liquidity to unstake * @return amount0 token0 amount unstaked * @return amount1 token1 amount unstaked */ function unstakePosition( uint128 liquidity, PositionDetails memory positionDetails ) public returns (uint256 amount0, uint256 amount1) { INonfungiblePositionManager positionManager = INonfungiblePositionManager(positionDetails.positionManager); (uint256 _amount0, uint256 _amount1) = getAmountsForLiquidity( liquidity, positionDetails.priceLower, positionDetails.priceUpper, positionDetails.pool ); (amount0, amount1) = positionManager.decreaseLiquidity( INonfungiblePositionManager.DecreaseLiquidityParams({ tokenId: positionDetails.tokenId, liquidity: liquidity, amount0Min: _amount0.sub(_amount0.div(MINT_BURN_SLIPPAGE)), amount1Min: _amount1.sub(_amount1.div(MINT_BURN_SLIPPAGE)), deadline: block.timestamp }) ); } /** * @dev Collect token amounts from pool position */ function collectPosition( uint128 amount0, uint128 amount1, uint256 tokenId, address positionManager ) public returns (uint256 collected0, uint256 collected1) { (collected0, collected1) = INonfungiblePositionManager(positionManager) .collect( INonfungiblePositionManager.CollectParams({ tokenId: tokenId, recipient: address(this), amount0Max: amount0, amount1Max: amount1 }) ); } /** * @dev Creates the NFT token representing the pool position * @dev Mint initial liquidity */ function createPosition( uint256 amount0, uint256 amount1, address positionManager, TokenDetails memory tokenDetails, PositionDetails memory positionDetails ) public returns (uint256 _tokenId) { (_tokenId, , , ) = INonfungiblePositionManager(positionManager).mint( INonfungiblePositionManager.MintParams({ token0: tokenDetails.token0, token1: tokenDetails.token1, fee: positionDetails.poolFee, tickLower: getTickFromPrice(positionDetails.priceLower), tickUpper: getTickFromPrice(positionDetails.priceUpper), amount0Desired: amount0, amount1Desired: amount1, amount0Min: amount0.sub(amount0.div(MINT_BURN_SLIPPAGE)), amount1Min: amount1.sub(amount1.div(MINT_BURN_SLIPPAGE)), recipient: address(this), deadline: block.timestamp }) ); } /** * @dev burn NFT representing a pool position with tokenId * @dev uses NFT Position Manager */ function burn(address positionManager, uint256 tokenId) public { INonfungiblePositionManager(positionManager).burn(tokenId); } /* ========================================================================================= */ /* xAssetCLR Helpers */ /* ========================================================================================= */ /** * @notice Admin function to stake tokens * @dev used in case there's leftover tokens in the contract * @dev Function differs from adminStake in that * @dev it calculates token amounts to stake so as to have * @dev all or most of the tokens in the position, and * @dev no tokens in buffer balance ; swaps as necessary */ function adminRebalance( TokenDetails memory tokenDetails, PositionDetails memory positionDetails ) public { (uint256 token0Balance, uint256 token1Balance) = getBufferTokenBalance(tokenDetails); token0Balance = getToken0AmountInNativeDecimals( token0Balance, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); token1Balance = getToken1AmountInNativeDecimals( token1Balance, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); (uint256 stakeAmount0, uint256 stakeAmount1) = checkIfAmountsMatchAndSwap( token0Balance, token1Balance, positionDetails, tokenDetails ); (token0Balance, token1Balance) = getBufferTokenBalance(tokenDetails); token0Balance = getToken0AmountInNativeDecimals( token0Balance, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); token1Balance = getToken1AmountInNativeDecimals( token1Balance, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); if (stakeAmount0 > token0Balance) { stakeAmount0 = token0Balance; } if (stakeAmount1 > token1Balance) { stakeAmount1 = token1Balance; } (uint256 amount0, uint256 amount1) = calculatePoolMintedAmounts( stakeAmount0, stakeAmount1, positionDetails.priceLower, positionDetails.priceUpper, positionDetails.pool ); require( amount0 != 0 || amount1 != 0, "Rebalance amounts are 0" ); stake( amount0, amount1, positionDetails.positionManager, positionDetails.tokenId ); } /** * @dev Check if token amounts match before attempting rebalance in xAssetCLR * @dev Uniswap contract requires deposits at a precise token ratio * @dev If they don't match, swap the tokens so as to deposit as much as possible * @param amount0ToMint how much token0 amount we want to deposit/withdraw * @param amount1ToMint how much token1 amount we want to deposit/withdraw */ function checkIfAmountsMatchAndSwap( uint256 amount0ToMint, uint256 amount1ToMint, PositionDetails memory positionDetails, TokenDetails memory tokenDetails ) public returns (uint256 amount0, uint256 amount1) { (uint256 amount0Minted, uint256 amount1Minted) = calculatePoolMintedAmounts( amount0ToMint, amount1ToMint, positionDetails.priceLower, positionDetails.priceUpper, positionDetails.pool ); if ( amount0Minted < amount0ToMint.sub(amount0ToMint.div(MINT_BURN_SLIPPAGE)) || amount1Minted < amount1ToMint.sub(amount1ToMint.div(MINT_BURN_SLIPPAGE)) ) { // calculate liquidity ratio = // minted liquidity / total pool liquidity // used to calculate swap impact in pool uint256 mintLiquidity = getLiquidityForAmounts( amount0ToMint, amount1ToMint, positionDetails.priceLower, positionDetails.priceUpper, positionDetails.pool ); uint256 poolLiquidity = getPoolLiquidity(positionDetails.pool); int128 liquidityRatio = poolLiquidity == 0 ? 0 : int128(ABDKMath64x64.divuu(mintLiquidity, poolLiquidity)); (amount0, amount1) = restoreTokenRatios( liquidityRatio, AmountsMinted({ amount0ToMint: amount0ToMint, amount1ToMint: amount1ToMint, amount0Minted: amount0Minted, amount1Minted: amount1Minted }), tokenDetails, positionDetails ); } else { (amount0, amount1) = (amount0ToMint, amount1ToMint); } } /** * @dev Swap tokens in xAssetCLR so as to keep a ratio which is required for * @dev depositing/withdrawing liquidity to/from Uniswap pool */ function restoreTokenRatios( int128 liquidityRatio, AmountsMinted memory amountsMinted, TokenDetails memory tokenDetails, PositionDetails memory positionDetails ) private returns (uint256 amount0, uint256 amount1) { // after normalization, returned swap amount will be in wei representation uint256 swapAmount; { uint256 midPrice = getPoolPriceWithDecimals(positionDetails.pool); // Swap amount returned is always in asset 0 terms swapAmount = Utils.calculateSwapAmount( Utils.AmountsMinted({ amount0ToMint: getToken0AmountInWei( amountsMinted.amount0ToMint, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ), amount1ToMint: getToken1AmountInWei( amountsMinted.amount1ToMint, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ), amount0Minted: getToken0AmountInWei( amountsMinted.amount0Minted, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ), amount1Minted: getToken1AmountInWei( amountsMinted.amount1Minted, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ) }), liquidityRatio, midPrice ); if (swapAmount == 0) { return ( amountsMinted.amount0ToMint, amountsMinted.amount1ToMint ); } } uint256 swapAmountWithSlippage = swapAmount.add(swapAmount.div(SWAP_SLIPPAGE)); uint256 mul1 = amountsMinted.amount0ToMint.mul(amountsMinted.amount1Minted); uint256 mul2 = amountsMinted.amount1ToMint.mul(amountsMinted.amount0Minted); (uint256 balance0, uint256 balance1) = getBufferTokenBalance(tokenDetails); if (mul1 > mul2) { if (balance0 < swapAmountWithSlippage) { swapAmountWithSlippage = balance0; } // Swap tokens uint256 amountOut = swapToken0ForToken1( swapAmountWithSlippage, swapAmount, positionDetails, tokenDetails ); amount0 = amountsMinted.amount0ToMint.sub( getToken0AmountInNativeDecimals( swapAmount, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ) ); // amountOut is already in native decimals amount1 = amountsMinted.amount1ToMint.add(amountOut); } else if (mul1 < mul2) { balance1 = getAmountInAsset0Terms( balance1, positionDetails.pool, positionDetails.twapPeriod, tokenDetails.token0Decimals, tokenDetails.token1Decimals, tokenDetails.tokenDiffDecimalMultiplier ); if (balance1 < swapAmountWithSlippage) { swapAmountWithSlippage = balance1; } uint256 midPrice = getPoolPriceWithDecimals(positionDetails.pool); // Swap tokens uint256 amountIn = swapToken1ForToken0( swapAmountWithSlippage.mul(midPrice).div(1e12), swapAmount.mul(midPrice).div(1e12), positionDetails, tokenDetails ); amount0 = amountsMinted.amount0ToMint.add( getToken0AmountInNativeDecimals( swapAmount, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ) ); // amountIn is already in native decimals amount1 = amountsMinted.amount1ToMint.sub(amountIn); } } /** * @dev Get token balances in xAssetCLR contract * @dev returned balances are in wei representation */ function getBufferTokenBalance(TokenDetails memory tokenDetails) public view returns (uint256 amount0, uint256 amount1) { IERC20 token0 = IERC20(tokenDetails.token0); IERC20 token1 = IERC20(tokenDetails.token1); return ( getBufferToken0Balance( token0, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ), getBufferToken1Balance( token1, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ) ); } /** * @dev Get token0 balance in xAssetCLR */ function getBufferToken0Balance( IERC20 token0, uint8 token0Decimals, uint256 token0DecimalMultiplier ) public view returns (uint256 amount0) { return getToken0AmountInWei( token0.balanceOf(address(this)), token0Decimals, token0DecimalMultiplier ); } /** * @dev Get token1 balance in xAssetCLR */ function getBufferToken1Balance( IERC20 token1, uint8 token1Decimals, uint256 token1DecimalMultiplier ) public view returns (uint256 amount1) { return getToken1AmountInWei( token1.balanceOf(address(this)), token1Decimals, token1DecimalMultiplier ); } /* ========================================================================================= */ /* Miscellaneous */ /* ========================================================================================= */ /** * @dev Returns token0 amount in token0Decimals */ function getToken0AmountInNativeDecimals( uint256 amount, uint8 token0Decimals, uint256 token0DecimalMultiplier ) public pure returns (uint256) { if (token0Decimals < TOKEN_DECIMAL_REPRESENTATION) { amount = amount.div(token0DecimalMultiplier); } return amount; } /** * @dev Returns token1 amount in token1Decimals */ function getToken1AmountInNativeDecimals( uint256 amount, uint8 token1Decimals, uint256 token1DecimalMultiplier ) public pure returns (uint256) { if (token1Decimals < TOKEN_DECIMAL_REPRESENTATION) { amount = amount.div(token1DecimalMultiplier); } return amount; } /** * @dev Returns token0 amount in TOKEN_DECIMAL_REPRESENTATION */ function getToken0AmountInWei( uint256 amount, uint8 token0Decimals, uint256 token0DecimalMultiplier ) public pure returns (uint256) { if (token0Decimals < TOKEN_DECIMAL_REPRESENTATION) { amount = amount.mul(token0DecimalMultiplier); } return amount; } /** * @dev Returns token1 amount in TOKEN_DECIMAL_REPRESENTATION */ function getToken1AmountInWei( uint256 amount, uint8 token1Decimals, uint256 token1DecimalMultiplier ) public pure returns (uint256) { if (token1Decimals < TOKEN_DECIMAL_REPRESENTATION) { amount = amount.mul(token1DecimalMultiplier); } return amount; } /** * @dev get price from tick */ function getSqrtRatio(int24 tick) public pure returns (uint160) { return TickMath.getSqrtRatioAtTick(tick); } /** * @dev get tick from price */ function getTickFromPrice(uint160 price) public pure returns (int24) { return TickMath.getTickAtSqrtRatio(price); } /** * @dev Subtract two numbers and return absolute value */ function subAbs(uint256 amount0, uint256 amount1) public pure returns (uint256) { return amount0 >= amount1 ? amount0.sub(amount1) : amount1.sub(amount0); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; /** Contract which implements locking of functions via a notLocked modifier Functions are locked per address. */ contract BlockLock { // how many blocks are the functions locked for uint256 private constant BLOCK_LOCK_COUNT = 6; // last block for which this address is timelocked mapping(address => uint256) public lastLockedBlock; function lock(address _address) internal { lastLockedBlock[_address] = block.number + BLOCK_LOCK_COUNT; } modifier notLocked(address lockedAddress) { require( lastLockedBlock[lockedAddress] <= block.number, "Address is temporarily locked" ); _; } } //SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface IxTokenManager { /** * @dev Add a manager to an xAsset fund */ function addManager(address manager, address fund) external; /** * @dev Remove a manager from an xAsset fund */ function removeManager(address manager, address fund) external; /** * @dev Check if an address is a manager for a fund */ function isManager(address manager, address fund) external view returns (bool); /** * @dev Set revenue controller */ function setRevenueController(address controller) external; /** * @dev Check if address is revenue controller */ function isRevenueController(address caller) external view returns (bool); } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * Minimal xAsset interface * Only mintWithToken and burn functions */ interface IxAsset is IERC20 { /* * @dev Mint xAsset using Asset * @notice Must run ERC20 approval first * @param amount: Asset amount to contribute */ function mintWithToken(uint256 amount) external; /* * @dev Burn xAsset tokens * @notice Will fail if redemption value exceeds available liquidity * @param amount: xAsset amount to redeem * @param redeemForEth: if true, redeem xAsset for ETH * @param minRate: Kyber.getExpectedRate xAsset=>ETH if redeemForEth true (no-op if false) */ function burn(uint256 amount, bool redeemForEth, uint256 minRate) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.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 SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.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: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; import '@openzeppelin/contracts/token/ERC721/IERC721Metadata.sol'; import '@openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol'; import './IPoolInitializer.sol'; import './IERC721Permit.sol'; import './IPeripheryImmutableState.sol'; import '../libraries/PoolAddress.sol'; /// @title Non-fungible token for positions /// @notice Wraps Uniswap V3 positions in a non-fungible token interface which allows for them to be transferred /// and authorized. interface INonfungiblePositionManager is IPoolInitializer, IPeripheryImmutableState, IERC721Metadata, IERC721Enumerable, IERC721Permit { /// @notice Emitted when liquidity is increased for a position NFT /// @dev Also emitted when a token is minted /// @param tokenId The ID of the token for which liquidity was increased /// @param liquidity The amount by which liquidity for the NFT position was increased /// @param amount0 The amount of token0 that was paid for the increase in liquidity /// @param amount1 The amount of token1 that was paid for the increase in liquidity event IncreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1); /// @notice Emitted when liquidity is decreased for a position NFT /// @param tokenId The ID of the token for which liquidity was decreased /// @param liquidity The amount by which liquidity for the NFT position was decreased /// @param amount0 The amount of token0 that was accounted for the decrease in liquidity /// @param amount1 The amount of token1 that was accounted for the decrease in liquidity event DecreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1); /// @notice Emitted when tokens are collected for a position NFT /// @dev The amounts reported may not be exactly equivalent to the amounts transferred, due to rounding behavior /// @param tokenId The ID of the token for which underlying tokens were collected /// @param recipient The address of the account that received the collected tokens /// @param amount0 The amount of token0 owed to the position that was collected /// @param amount1 The amount of token1 owed to the position that was collected event Collect(uint256 indexed tokenId, address recipient, uint256 amount0, uint256 amount1); /// @notice Returns the position information associated with a given token ID. /// @dev Throws if the token ID is not valid. /// @param tokenId The ID of the token that represents the position /// @return nonce The nonce for permits /// @return operator The address that is approved for spending /// @return token0 The address of the token0 for a specific pool /// @return token1 The address of the token1 for a specific pool /// @return fee The fee associated with the pool /// @return tickLower The lower end of the tick range for the position /// @return tickUpper The higher end of the tick range for the position /// @return liquidity The liquidity of the position /// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position /// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position /// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation /// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation function positions(uint256 tokenId) external view returns ( uint96 nonce, address operator, address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); struct MintParams { address token0; address token1; uint24 fee; int24 tickLower; int24 tickUpper; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; address recipient; uint256 deadline; } /// @notice Creates a new position wrapped in a NFT /// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized /// a method does not exist, i.e. the pool is assumed to be initialized. /// @param params The params necessary to mint a position, encoded as `MintParams` in calldata /// @return tokenId The ID of the token that represents the minted position /// @return liquidity The amount of liquidity for this position /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function mint(MintParams calldata params) external payable returns ( uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1 ); struct IncreaseLiquidityParams { uint256 tokenId; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; uint256 deadline; } /// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender` /// @param params tokenId The ID of the token for which liquidity is being increased, /// amount0Desired The desired amount of token0 to be spent, /// amount1Desired The desired amount of token1 to be spent, /// amount0Min The minimum amount of token0 to spend, which serves as a slippage check, /// amount1Min The minimum amount of token1 to spend, which serves as a slippage check, /// deadline The time by which the transaction must be included to effect the change /// @return liquidity The new liquidity amount as a result of the increase /// @return amount0 The amount of token0 to acheive resulting liquidity /// @return amount1 The amount of token1 to acheive resulting liquidity function increaseLiquidity(IncreaseLiquidityParams calldata params) external payable returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ); struct DecreaseLiquidityParams { uint256 tokenId; uint128 liquidity; uint256 amount0Min; uint256 amount1Min; uint256 deadline; } /// @notice Decreases the amount of liquidity in a position and accounts it to the position /// @param params tokenId The ID of the token for which liquidity is being decreased, /// amount The amount by which liquidity will be decreased, /// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity, /// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity, /// deadline The time by which the transaction must be included to effect the change /// @return amount0 The amount of token0 accounted to the position's tokens owed /// @return amount1 The amount of token1 accounted to the position's tokens owed function decreaseLiquidity(DecreaseLiquidityParams calldata params) external payable returns (uint256 amount0, uint256 amount1); struct CollectParams { uint256 tokenId; address recipient; uint128 amount0Max; uint128 amount1Max; } /// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient /// @param params tokenId The ID of the NFT for which tokens are being collected, /// recipient The account that should receive the tokens, /// amount0Max The maximum amount of token0 to collect, /// amount1Max The maximum amount of token1 to collect /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1); /// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens /// must be collected first. /// @param tokenId The ID of the token that is being burned function burn(uint256 tokenId) external payable; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol'; /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface ISwapRouter is IUniswapV3SwapCallback { struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata /// @return amountOut The amount of the received token function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut); struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata /// @return amountOut The amount of the received token function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata /// @return amountIn The amount of the input token function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata /// @return amountIn The amount of the input token function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; /// @title Quoter Interface /// @notice Supports quoting the calculated amounts from exact input or exact output swaps /// @dev These functions are not marked view because they rely on calling non-view functions and reverting /// to compute the result. They are also not gas efficient and should not be called on-chain. interface IQuoter { /// @notice Returns the amount out received for a given exact input swap without executing the swap /// @param path The path of the swap, i.e. each token pair and the pool fee /// @param amountIn The amount of the first token to swap /// @return amountOut The amount of the last token that would be received function quoteExactInput(bytes memory path, uint256 amountIn) external returns (uint256 amountOut); /// @notice Returns the amount out received for a given exact input but for a swap of a single pool /// @param tokenIn The token being swapped in /// @param tokenOut The token being swapped out /// @param fee The fee of the token pool to consider for the pair /// @param amountIn The desired input amount /// @param sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap /// @return amountOut The amount of `tokenOut` that would be received function quoteExactInputSingle( address tokenIn, address tokenOut, uint24 fee, uint256 amountIn, uint160 sqrtPriceLimitX96 ) external returns (uint256 amountOut); /// @notice Returns the amount in required for a given exact output swap without executing the swap /// @param path The path of the swap, i.e. each token pair and the pool fee /// @param amountOut The amount of the last token to receive /// @return amountIn The amount of first token required to be paid function quoteExactOutput(bytes memory path, uint256 amountOut) external returns (uint256 amountIn); /// @notice Returns the amount in required to receive the given exact output amount but for a swap of a single pool /// @param tokenIn The token being swapped in /// @param tokenOut The token being swapped out /// @param fee The fee of the token pool to consider for the pair /// @param amountOut The desired output amount /// @param sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap /// @return amountIn The amount required as the input for the swap in order to receive `amountOut` function quoteExactOutputSingle( address tokenIn, address tokenOut, uint24 fee, uint256 amountOut, uint160 sqrtPriceLimitX96 ) external returns (uint256 amountIn); } // SPDX-License-Identifier: 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: GPL-2.0-or-later pragma solidity >=0.5.0; import './pool/IUniswapV3PoolImmutables.sol'; import './pool/IUniswapV3PoolState.sol'; import './pool/IUniswapV3PoolDerivedState.sol'; import './pool/IUniswapV3PoolActions.sol'; import './pool/IUniswapV3PoolOwnerActions.sol'; import './pool/IUniswapV3PoolEvents.sol'; /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions, IUniswapV3PoolOwnerActions, IUniswapV3PoolEvents { } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title 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: BSD-4-Clause /* * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected].com> */ pragma solidity 0.7.6; /** * Smart contract library of mathematical functions operating with signed * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is * basically a simple fraction whose numerator is signed 128-bit integer and * denominator is 2^64. As long as denominator is always the same, there is no * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are * represented by int128 type holding only the numerator. */ library ABDKMath64x64 { /* * Minimum value signed 64.64-bit fixed point number may have. */ int128 private constant MIN_64x64 = -0x80000000000000000000000000000000; /* * Maximum value signed 64.64-bit fixed point number may have. */ int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Convert signed 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromInt(int256 x) internal pure returns (int128) { require(x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF); return int128(x << 64); } /** * Convert signed 64.64 fixed point number into signed 64-bit integer number * rounding down. * * @param x signed 64.64-bit fixed point number * @return signed 64-bit integer number */ function toInt(int128 x) internal pure returns (int64) { return int64(x >> 64); } /** * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromUInt(uint256 x) internal pure returns (int128) { require(x <= 0x7FFFFFFFFFFFFFFF); return int128(x << 64); } /** * Convert signed 64.64 fixed point number into unsigned 64-bit integer * number rounding down. Revert on underflow. * * @param x signed 64.64-bit fixed point number * @return unsigned 64-bit integer number */ function toUInt(int128 x) internal pure returns (uint64) { require(x >= 0); return uint64(x >> 64); } /** * Calculate x + y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function add(int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) + y; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } /** * Calculate x - y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sub(int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) - y; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } /** * Calculate x * y rounding down. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function mul(int128 x, int128 y) internal pure returns (int128) { int256 result = (int256(x) * y) >> 64; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } /** * Calculate x * y rounding down, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y unsigned 256-bit integer number * @return unsigned 256-bit integer number */ function mulu(int128 x, uint256 y) internal pure returns (uint256) { if (y == 0) return 0; require(x >= 0); uint256 lo = (uint256(x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64; uint256 hi = uint256(x) * (y >> 128); require(hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); hi <<= 64; require( hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo ); return hi + lo; } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function divu(uint256 x, uint256 y) internal pure returns (int128) { require(y != 0); uint128 result = divuu(x, y); require(result <= uint128(MAX_64x64)); return int128(result); } /** * Calculate 1 / x rounding towards zero. Revert on overflow or when x is * zero. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function inv(int128 x) internal pure returns (int128) { require(x != 0); int256 result = int256(0x100000000000000000000000000000000) / x; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } /** * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y uint256 value * @return signed 64.64-bit fixed point number */ function pow(int128 x, uint256 y) internal pure returns (int128) { uint256 absoluteResult; bool negativeResult = false; if (x >= 0) { absoluteResult = powu(uint256(x) << 63, y); } else { // We rely on overflow behavior here absoluteResult = powu(uint256(uint128(-x)) << 63, y); negativeResult = y & 1 > 0; } absoluteResult >>= 63; if (negativeResult) { require(absoluteResult <= 0x80000000000000000000000000000000); return -int128(absoluteResult); // We rely on overflow behavior here } else { require(absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128(absoluteResult); // We rely on overflow behavior here } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return unsigned 64.64-bit fixed point number */ function divuu(uint256 x, uint256 y) internal pure returns (uint128) { require(y != 0); uint256 result; if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y; else { uint256 msb = 192; uint256 xc = x >> 192; if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore result = (x << (255 - msb)) / (((y - 1) >> (msb - 191)) + 1); require(result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 hi = result * (y >> 128); uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 xh = x >> 192; uint256 xl = x << 64; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here lo = hi << 128; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here assert(xh == hi >> 128); result += xl / y; } require(result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return uint128(result); } /** * Calculate x^y assuming 0^0 is 1, where x is unsigned 129.127 fixed point * number and y is unsigned 256-bit integer number. Revert on overflow. * * @param x unsigned 129.127-bit fixed point number * @param y uint256 value * @return unsigned 129.127-bit fixed point number */ function powu(uint256 x, uint256 y) private pure returns (uint256) { if (y == 0) return 0x80000000000000000000000000000000; else if (x == 0) return 0; else { int256 msb = 0; uint256 xc = x; if (xc >= 0x100000000000000000000000000000000) { xc >>= 128; msb += 128; } if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 xe = msb - 127; if (xe > 0) x >>= uint256(xe); else x <<= uint256(-xe); uint256 result = 0x80000000000000000000000000000000; int256 re = 0; while (y > 0) { if (y & 1 > 0) { result = result * x; y -= 1; re += xe; if ( result >= 0x8000000000000000000000000000000000000000000000000000000000000000 ) { result >>= 128; re += 1; } else result >>= 127; if (re < -127) return 0; // Underflow require(re < 128); // Overflow } else { x = x * x; y >>= 1; xe <<= 1; if ( x >= 0x8000000000000000000000000000000000000000000000000000000000000000 ) { x >>= 128; xe += 1; } else x >>= 127; if (xe < -127) return 0; // Underflow require(xe < 128); // Overflow } } if (re > 0) result <<= uint256(re); else if (re < 0) result >>= uint256(-re); return result; } } /** * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer * number. * * @param x unsigned 256-bit integer number * @return unsigned 128-bit integer number */ function sqrtu(uint256 x) internal pure returns (uint128) { if (x == 0) return 0; else { 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 uint128(r < r1 ? r : r1); } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./ABDKMath64x64.sol"; /** * Library with utility functions for xAssetCLR */ library Utils { using SafeMath for uint256; struct AmountsMinted { uint256 amount0ToMint; uint256 amount1ToMint; uint256 amount0Minted; uint256 amount1Minted; } /** Get asset 1 twap price for the period of [now - secondsAgo, now] */ function getTWAP(int56[] memory prices, uint32 secondsAgo) internal pure returns (int128) { // Formula is // 1.0001 ^ (currentPrice - pastPrice) / secondsAgo require(secondsAgo != 0, "Cannot get twap for 0 seconds"); int256 diff = int256(prices[1]) - int256(prices[0]); uint256 priceDiff = diff < 0 ? uint256(-diff) : uint256(diff); int128 fraction = ABDKMath64x64.divu(priceDiff, uint256(secondsAgo)); int128 twap = ABDKMath64x64.pow( ABDKMath64x64.divu(10001, 10000), uint256(ABDKMath64x64.toUInt(fraction)) ); // This is necessary because we cannot call .pow on unsigned integers // And thus when asset0Price > asset1Price we need to reverse the value twap = diff < 0 ? ABDKMath64x64.inv(twap) : twap; return twap; } /** * Helper function to calculate how much to swap when * staking or withdrawing from Uni V3 Pools * Goal of this function is to calibrate the staking tokens amounts * When we want to stake, for example, 100 token0 and 10 token1 * But pool price demands 100 token0 and 40 token1 * We cannot directly stake 100 t0 and 10 t1, so we swap enough * to be able to stake the value of 100 t0 and 10 t1 */ function calculateSwapAmount( AmountsMinted memory amountsMinted, int128 liquidityRatio, uint256 midPrice ) internal pure returns (uint256 swapAmount) { // formula is more complicated than xU3LP case // it includes the asset prices, and considers the swap impact on the pool // base formula is this: // n - swap amt, x - amount 0 to mint, y - amount 1 to mint, // z - amount 0 minted, t - amount 1 minted, p0 - pool mid price // l - liquidity ratio (current mint liquidity vs total pool liq) // (X - n) / (Y + n * p0) = (Z + l * n) / (T - l * n * p0) -> // n = (X * T - Y * Z) / (p0 * l * X + p0 * Z + l * Y + T) uint256 mul1 = amountsMinted.amount0ToMint.mul(amountsMinted.amount1Minted); uint256 mul2 = amountsMinted.amount1ToMint.mul(amountsMinted.amount0Minted); uint256 sub = subAbs(mul1, mul2); uint256 add1 = ABDKMath64x64.mulu(liquidityRatio, amountsMinted.amount1ToMint); uint256 add2 = midPrice .mul( ABDKMath64x64.mulu(liquidityRatio, amountsMinted.amount0ToMint) ) .div(1e12); uint256 add3 = midPrice.mul(amountsMinted.amount0Minted).div(1e12); uint256 add = add1.add(add2).add(add3).add(amountsMinted.amount1Minted); // Some numbers are too big to fit in ABDK's div 128-bit representation // So calculate the root of the equation and then raise to the 2nd power int128 nRatio = ABDKMath64x64.divu( ABDKMath64x64.sqrtu(sub), ABDKMath64x64.sqrtu(add) ); int64 n = ABDKMath64x64.toInt(nRatio); swapAmount = uint256(n)**2; } // comparator for 32-bit timestamps // @return bool Whether a <= b function lte( uint32 time, uint32 a, uint32 b ) internal pure returns (bool) { if (a <= time && b <= time) return a <= b; uint256 aAdjusted = a > time ? a : a + 2**32; uint256 bAdjusted = b > time ? b : b + 2**32; return aAdjusted <= bAdjusted; } // Subtract two numbers and return absolute value function subAbs(uint256 amount0, uint256 amount1) internal pure returns (uint256) { return amount0 >= amount1 ? amount0.sub(amount1) : amount1.sub(amount0); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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.7.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; /// @title Creates and initializes V3 Pools /// @notice Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that /// require the pool to exist. interface IPoolInitializer { /// @notice Creates a new pool if it does not exist, then initializes if not initialized /// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool /// @param token0 The contract address of token0 of the pool /// @param token1 The contract address of token1 of the pool /// @param fee The fee amount of the v3 pool for the specified token pair /// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value /// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary function createAndInitializePoolIfNecessary( address token0, address token1, uint24 fee, uint160 sqrtPriceX96 ) external payable returns (address pool); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; import '@openzeppelin/contracts/token/ERC721/IERC721.sol'; /// @title ERC721 with permit /// @notice Extension to ERC721 that includes a permit function for signature based approvals interface IERC721Permit is IERC721 { /// @notice The permit typehash used in the permit signature /// @return The typehash for the permit function PERMIT_TYPEHASH() external pure returns (bytes32); /// @notice The domain separator used in the permit signature /// @return The domain seperator used in encoding of permit signature function DOMAIN_SEPARATOR() external view returns (bytes32); /// @notice Approve of a specific token ID for spending by spender via signature /// @param spender The account that is being approved /// @param tokenId The ID of the token that is being approved for spending /// @param deadline The deadline timestamp by which the call must be mined for the approve to work /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s` /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s` /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v` function permit( address spender, uint256 tokenId, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external payable; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Immutable state /// @notice Functions that return immutable state of the router interface IPeripheryImmutableState { /// @return Returns the address of the Uniswap V3 factory function factory() external view returns (address); /// @return Returns the address of WETH9 function WETH9() external view returns (address); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Provides functions for deriving a pool address from the factory, tokens, and the fee library PoolAddress { bytes32 internal constant POOL_INIT_CODE_HASH = 0xc02f72e8ae5e68802e6d893d58ddfb0df89a2f4c9c2f04927db1186a29373660; /// @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: MIT pragma solidity ^0.7.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.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: 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: 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: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface /// @return The contract address function factory() external view returns (address); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice The maximum amount of position liquidity that can use any tick in the range /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool /// @return The max amount of liquidity per tick function maxLiquidityPerTick() external view returns (uint128); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice The amounts of token0 and token1 that are owed to the protocol /// @dev Protocol fees will never exceed uint128 max in either token function protocolFees() external view returns (uint128 token0, uint128 token1); /// @notice The currently in range liquidity available to the pool /// @dev This value has no relationship to the total liquidity across all ticks function liquidity() external view returns (uint128); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information function tickBitmap(int16 wordPosition) external view returns (uint256); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); /// @notice Returns data about a specific observation index /// @param index The element of the observations array to fetch /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time /// ago, rather than at a specific index in the array. /// @return blockTimestamp The timestamp of the observation, /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp, /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp, /// Returns initialized whether the observation has been initialized and the values are safe to use function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed. /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first /// snapshot is taken and the second snapshot is taken. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range /// @return tickCumulativeInside The snapshot of the tick accumulator for the range /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range /// @return secondsInside The snapshot of seconds per liquidity for the range function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Sets the initial price for the pool /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96 function initialize(uint160 sqrtPriceX96) external; /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling /// with 0 amount{0,1} and sending the donation amount(s) from the callback /// @param recipient The address which will receive the token0 and token1 amounts /// @param amount0 The amount of token0 to send /// @param amount1 The amount of token1 to send /// @param data Any data to be passed through to the callback function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; /// @notice Increase the maximum number of price and liquidity observations that this pool will store /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to /// the input observationCardinalityNext. /// @param observationCardinalityNext The desired minimum number of observations for the pool to store function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissioned pool actions /// @notice Contains pool methods that may only be called by the factory owner interface IUniswapV3PoolOwnerActions { /// @notice Set the denominator of the protocol's % share of the fees /// @param feeProtocol0 new protocol fee for token0 of the pool /// @param feeProtocol1 new protocol fee for token1 of the pool function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external; /// @notice Collect the protocol fee accrued to the pool /// @param recipient The address to which collected protocol fees should be sent /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1 /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0 /// @return amount0 The protocol fee collected in token0 /// @return amount1 The protocol fee collected in token1 function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title 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 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, 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); }
* Convert signed 64.64 fixed point number into unsigned 64-bit integer number rounding down. Revert on underflow. @param x signed 64.64-bit fixed point number @return unsigned 64-bit integer number/
function toUInt(int128 x) internal pure returns (uint64) { require(x >= 0); return uint64(x >> 64); }
1,686,917
[ 1, 2723, 6726, 5178, 18, 1105, 5499, 1634, 1300, 1368, 9088, 5178, 17, 3682, 3571, 1300, 13885, 2588, 18, 225, 868, 1097, 603, 3613, 2426, 18, 225, 619, 6726, 5178, 18, 1105, 17, 3682, 5499, 1634, 1300, 327, 9088, 5178, 17, 3682, 3571, 1300, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 358, 14342, 12, 474, 10392, 619, 13, 2713, 16618, 1135, 261, 11890, 1105, 13, 288, 203, 3639, 2583, 12, 92, 1545, 374, 1769, 203, 3639, 327, 2254, 1105, 12, 92, 1671, 5178, 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/4/0xd8e73af836e570a8C344F7234876ED47ADf04544/sources/contracts/token.sol
@notice Alerts when new token was created @notice Creates a new Token
{ TokenERC20 token = new TokenERC20(_name, _symbol, _decimals, _initialSupply); require(address(token) != address(0), "Token was not created"); emit NewTokenCreated(address(token), token.name()); }
12,394,834
[ 1, 37, 29729, 1347, 394, 1147, 1703, 2522, 225, 10210, 279, 394, 3155, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 288, 203, 3639, 3155, 654, 39, 3462, 1147, 273, 394, 3155, 654, 39, 3462, 24899, 529, 16, 389, 7175, 16, 389, 31734, 16, 389, 6769, 3088, 1283, 1769, 203, 3639, 2583, 12, 2867, 12, 2316, 13, 480, 1758, 12, 20, 3631, 315, 1345, 1703, 486, 2522, 8863, 203, 3639, 3626, 1166, 1345, 6119, 12, 2867, 12, 2316, 3631, 1147, 18, 529, 10663, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./ComptrollerInterface.sol"; import "./CTokenInterfaces.sol"; import "./ErrorReporter.sol"; import "./Exponential.sol"; import "./EIP20Interface.sol"; import "./EIP20NonStandardInterface.sol"; import "./InterestRateModel.sol"; /** * @title Compound's CToken Contract * @notice Abstract base for CTokens * @author Compound */ abstract contract CToken is CTokenInterface, Exponential, TokenErrorReporter { /** * @notice Initialize the money market * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ EIP-20 name of this token * @param symbol_ EIP-20 symbol of this token * @param decimals_ EIP-20 decimal precision of this token */ function initialize(ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_) public { require(msg.sender == admin, "only admin may initialize the market"); require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once"); // Set initial exchange rate initialExchangeRateMantissa = initialExchangeRateMantissa_; require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero."); // Set the comptroller uint err = _setComptroller(comptroller_); require(err == uint(Error.NO_ERROR), "setting comptroller failed"); // Initialize block number and borrow index (block number mocks depend on comptroller being set) accrualBlockNumber = getBlockNumber(); borrowIndex = mantissaOne; // Set the interest rate model (depends on block number / borrow index) err = _setInterestRateModelFresh(interestRateModel_); require(err == uint(Error.NO_ERROR), "setting interest rate model failed"); name = name_; symbol = symbol_; decimals = decimals_; // The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund) _notEntered = true; } /** * @notice Transfer `tokens` tokens from `src` to `dst` by `spender` * @dev Called by both `transfer` and `transferFrom` internally * @param spender The address of the account performing the transfer * @param src The address of the source account * @param dst The address of the destination account * @param tokens The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) { /* Fail if transfer not allowed */ uint allowed = comptroller.transferAllowed(address(this), src, dst, tokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed); } /* Do not allow self-transfers */ if (src == dst) { return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED); } /* Get the allowance, infinite for the account owner */ uint startingAllowance = 0; if (spender == src) { startingAllowance = uint(-1); } else { startingAllowance = transferAllowances[src][spender]; } /* Do the calculations, checking for {under,over}flow */ MathError mathErr; uint allowanceNew; uint srcTokensNew; uint dstTokensNew; (mathErr, allowanceNew) = subUInt(startingAllowance, tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED); } (mathErr, srcTokensNew) = subUInt(accountTokens[src], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH); } (mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) accountTokens[src] = srcTokensNew; accountTokens[dst] = dstTokensNew; /* Eat some of the allowance (if necessary) */ if (startingAllowance != uint(-1)) { transferAllowances[src][spender] = allowanceNew; } /* We emit a Transfer event */ emit Transfer(src, dst, tokens); comptroller.transferVerify(address(this), src, dst, tokens); return uint(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external override nonReentrant returns (bool) { return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external override nonReentrant returns (bool) { return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR); } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external override returns (bool) { address src = msg.sender; transferAllowances[src][spender] = amount; emit Approval(src, spender, amount); return true; } /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external override view returns (uint256) { return transferAllowances[owner][spender]; } /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external override view returns (uint256) { return accountTokens[owner]; } /** * @notice Get the underlying balance of the `owner` * @dev This also accrues interest in a transaction * @param owner The address of the account to query * @return The amount of underlying owned by `owner` */ function balanceOfUnderlying(address owner) external override returns (uint) { Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()}); (MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]); require(mErr == MathError.NO_ERROR, "balance could not be calculated"); return balance; } /** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by comptroller to more efficiently perform liquidity checks. * @param account Address of the account to snapshot * @return (possible error, token balance, borrow balance, exchange rate mantissa) */ function getAccountSnapshot(address account) external override view returns (uint, uint, uint, uint) { uint cTokenBalance = accountTokens[account]; uint borrowBalance; uint exchangeRateMantissa; MathError mErr; (mErr, borrowBalance) = borrowBalanceStoredInternal(account); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0, 0, 0); } (mErr, exchangeRateMantissa) = exchangeRateStoredInternal(); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0, 0, 0); } return (uint(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa); } /** * @dev Function to simply retrieve block number * This exists mainly for inheriting test contracts to stub this result. */ function getBlockNumber() internal view returns (uint) { return block.number; } /** * @notice Returns the current per-block borrow interest rate for this cToken * @return The borrow interest rate per block, scaled by 1e18 */ function borrowRatePerBlock() external override view returns (uint) { return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves); } /** * @notice Returns the current per-block supply interest rate for this cToken * @return The supply interest rate per block, scaled by 1e18 */ function supplyRatePerBlock() external override view returns (uint) { return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa); } /** * @notice Returns the current total borrows plus accrued interest * @return The total borrows with interest */ function totalBorrowsCurrent() external override nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return totalBorrows; } /** * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex * @param account The address whose balance should be calculated after updating borrowIndex * @return The calculated balance */ function borrowBalanceCurrent(address account) external override nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return borrowBalanceStored(account); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return The calculated balance */ function borrowBalanceStored(address account) public override view returns (uint) { (MathError err, uint result) = borrowBalanceStoredInternal(account); require(err == MathError.NO_ERROR, "borrowBalanceStored: borrowBalanceStoredInternal failed"); return result; } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return (error code, the calculated balance or 0 if error code is non-zero) */ function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) { /* Note: we do not assert that the market is up to date */ MathError mathErr; uint principalTimesIndex; uint result; /* Get borrowBalance and borrowIndex */ BorrowSnapshot storage borrowSnapshot = accountBorrows[account]; /* If borrowBalance = 0 then borrowIndex is likely also 0. * Rather than failing the calculation with a division by 0, we immediately return 0 in this case. */ if (borrowSnapshot.principal == 0) { return (MathError.NO_ERROR, 0); } /* Calculate new borrow balance using the interest index: * recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex */ (mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } return (MathError.NO_ERROR, result); } /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() public override nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return exchangeRateStored(); } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() public override view returns (uint) { (MathError err, uint result) = exchangeRateStoredInternal(); require(err == MathError.NO_ERROR, "exchangeRateStored: exchangeRateStoredInternal failed"); return result; } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return (error code, calculated exchange rate scaled by 1e18) */ function exchangeRateStoredInternal() internal view returns (MathError, uint) { uint _totalSupply = totalSupply; if (_totalSupply == 0) { /* * If there are no tokens minted: * exchangeRate = initialExchangeRate */ return (MathError.NO_ERROR, initialExchangeRateMantissa); } else { /* * Otherwise: * exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply */ uint totalCash = getCashPrior(); uint cashPlusBorrowsMinusReserves; Exp memory exchangeRate; MathError mathErr; (mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } return (MathError.NO_ERROR, exchangeRate.mantissa); } } /** * @notice Get cash balance of this cToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external override view returns (uint) { return getCashPrior(); } /** * @notice Applies accrued interest to total borrows and reserves * @dev This calculates interest accrued from the last checkpointed block * up to the current block and writes new checkpoint to storage. */ function accrueInterest() override public returns (uint) { /* Remember the initial block number */ uint currentBlockNumber = getBlockNumber(); uint accrualBlockNumberPrior = accrualBlockNumber; /* Short-circuit accumulating 0 interest */ if (accrualBlockNumberPrior == currentBlockNumber) { return uint(Error.NO_ERROR); } /* Read the previous values out of storage */ uint cashPrior = getCashPrior(); uint borrowsPrior = totalBorrows; uint reservesPrior = totalReserves; uint borrowIndexPrior = borrowIndex; /* Calculate the current borrow interest rate */ uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior); require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high"); /* Calculate the number of blocks elapsed since the last accrual */ (MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior); require(mathErr == MathError.NO_ERROR, "could not calculate block delta"); /* * Calculate the interest accumulated into borrows and reserves and the new index: * simpleInterestFactor = borrowRate * blockDelta * interestAccumulated = simpleInterestFactor * totalBorrows * totalBorrowsNew = interestAccumulated + totalBorrows * totalReservesNew = interestAccumulated * reserveFactor + totalReserves * borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex */ Exp memory simpleInterestFactor; uint interestAccumulated; uint totalBorrowsNew; uint totalReservesNew; uint borrowIndexNew; (mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr)); } (mathErr, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr)); } (mathErr, totalBorrowsNew) = addUInt(interestAccumulated, borrowsPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr)); } (mathErr, totalReservesNew) = mulScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr)); } (mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accrualBlockNumber = currentBlockNumber; borrowIndex = borrowIndexNew; totalBorrows = totalBorrowsNew; totalReserves = totalReservesNew; /* We emit an AccrueInterest event */ emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew); return uint(Error.NO_ERROR); } /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0); } // mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to return mintFresh(msg.sender, mintAmount); } struct MintLocalVars { Error err; MathError mathErr; uint exchangeRateMantissa; uint mintTokens; uint totalSupplyNew; uint accountTokensNew; uint actualMintAmount; } /** * @notice User supplies assets into the market and receives cTokens in exchange * @dev Assumes interest has already been accrued up to the current block * @param minter The address of the account which is supplying the assets * @param mintAmount The amount of the underlying asset to supply * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) { /* Fail if mint not allowed */ uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0); } MintLocalVars memory vars; (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call `doTransferIn` for the minter and the mintAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * `doTransferIn` reverts if anything goes wrong, since we can't be sure if * side-effects occurred. The function returns the amount actually transferred, * in case of a fee. On success, the cToken holds an additional `actualMintAmount` * of cash. */ vars.actualMintAmount = doTransferIn(minter, mintAmount); /* * We get the current exchange rate and calculate the number of cTokens to be minted: * mintTokens = actualMintAmount / exchangeRate */ (vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa})); require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED"); /* * We calculate the new total supply of cTokens and minter token balance, checking for overflow: * totalSupplyNew = totalSupply + mintTokens * accountTokensNew = accountTokens[minter] + mintTokens */ (vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens); require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED"); (vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens); require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED"); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[minter] = vars.accountTokensNew; /* We emit a Mint event, and a Transfer event */ emit Mint(minter, vars.actualMintAmount, vars.mintTokens); emit Transfer(address(this), minter, vars.mintTokens); /* We call the defense hook */ comptroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens); return (uint(Error.NO_ERROR), vars.actualMintAmount); } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, redeemTokens, 0); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to receive from redeeming cTokens * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, 0, redeemAmount); } struct RedeemLocalVars { Error err; MathError mathErr; uint exchangeRateMantissa; uint redeemTokens; uint redeemAmount; uint totalSupplyNew; uint accountTokensNew; } /** * @notice User redeems cTokens in exchange for the underlying asset * @dev Assumes interest has already been accrued up to the current block * @param redeemer The address of the account which is redeeming the tokens * @param redeemTokensIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) { require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero"); RedeemLocalVars memory vars; /* exchangeRate = invoke Exchange Rate Stored() */ (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)); } /* If redeemTokensIn > 0: */ if (redeemTokensIn > 0) { /* * We calculate the exchange rate and the amount of underlying to be redeemed: * redeemTokens = redeemTokensIn * redeemAmount = redeemTokensIn x exchangeRateCurrent */ vars.redeemTokens = redeemTokensIn; (vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr)); } } else { /* * We get the current exchange rate and calculate the amount to be redeemed: * redeemTokens = redeemAmountIn / exchangeRate * redeemAmount = redeemAmountIn */ (vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa})); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr)); } vars.redeemAmount = redeemAmountIn; } /* Fail if redeem not allowed */ uint allowed = comptroller.redeemAllowed(address(this), redeemer, vars.redeemTokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REDEEM_COMPTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK); } /* * We calculate the new total supply and redeemer balance, checking for underflow: * totalSupplyNew = totalSupply - redeemTokens * accountTokensNew = accountTokens[redeemer] - redeemTokens */ (vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } /* Fail gracefully if protocol has insufficient cash */ if (getCashPrior() < vars.redeemAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[redeemer] = vars.accountTokensNew; if (totalSupply == 0 && totalBorrows > 0) { totalReserves = totalReserves - totalBorrows; totalBorrows = 0; } /* * We invoke doTransferOut for the redeemer and the redeemAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken has redeemAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(redeemer, vars.redeemAmount); /* We emit a Transfer event, and a Redeem event */ emit Transfer(redeemer, address(this), vars.redeemTokens); emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens); /* We call the defense hook */ comptroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens); return uint(Error.NO_ERROR); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED); } // borrowFresh emits borrow-specific logs on errors, so we don't need to return borrowFresh(msg.sender, borrowAmount); } struct BorrowLocalVars { MathError mathErr; uint accountBorrows; uint accountBorrowsNew; uint totalBorrowsNew; } /** * @notice Users borrow assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) { /* Fail if borrow not allowed */ uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK); } /* Fail gracefully if protocol has insufficient underlying cash */ if (getCashPrior() < borrowAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE); } BorrowLocalVars memory vars; /* * We calculate the new borrower and total borrow balances, failing on overflow: * accountBorrowsNew = accountBorrows + borrowAmount * totalBorrowsNew = totalBorrows + borrowAmount */ (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* * We invoke doTransferOut for the borrower and the borrowAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken borrowAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(borrower, borrowAmount); /* We emit a Borrow event */ emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ comptroller.borrowVerify(address(this), borrower, borrowAmount); return uint(Error.NO_ERROR); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, msg.sender, repayAmount); } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, borrower, repayAmount); } struct RepayBorrowLocalVars { Error err; MathError mathErr; uint repayAmount; uint borrowerIndex; uint accountBorrows; uint accountBorrowsNew; uint totalBorrowsNew; uint actualRepayAmount; } /** * @notice Borrows are repaid by another user (possibly the borrower). * @param payer the account paying off the borrow * @param borrower the account with the debt being payed off * @param repayAmount the amount of undelrying tokens being returned * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) { /* Fail if repayBorrow not allowed */ uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0); } RepayBorrowLocalVars memory vars; /* We remember the original borrowerIndex for verification purposes */ vars.borrowerIndex = accountBorrows[borrower].interestIndex; /* We fetch the amount the borrower owes, with accumulated interest */ (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower); if (vars.mathErr != MathError.NO_ERROR) { return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0); } /* If repayAmount == -1, repayAmount = accountBorrows */ if (repayAmount == uint(-1)) { vars.repayAmount = vars.accountBorrows; } else { vars.repayAmount = repayAmount; } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the payer and the repayAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional repayAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount); /* * We calculate the new borrower and total borrow balances, failing on underflow: * accountBorrowsNew = accountBorrows - actualRepayAmount * totalBorrowsNew = totalBorrows - actualRepayAmount */ (vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount); require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED"); (vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount); require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED"); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a RepayBorrow event */ emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex); return (uint(Error.NO_ERROR), vars.actualRepayAmount); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowInternal(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0); } error = cTokenCollateral.accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0); } // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral); } /** * @notice The liquidator liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param liquidator The address repaying the borrow and seizing collateral * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal returns (uint, uint) { /* Fail if liquidate not allowed */ uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0); } /* Verify cTokenCollateral market's block number equals current block number */ if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0); } /* Fail if repayAmount = 0 */ if (repayAmount == 0) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0); } /* Fail if repayAmount = -1 */ if (repayAmount == uint(-1)) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0); } /* Fail if repayBorrow fails */ (uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount); if (repayBorrowError != uint(Error.NO_ERROR)) { return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We calculate the number of collateral tokens that will be seized */ (uint amountSeizeError, uint seizeTokens) = comptroller.liquidateCalculateSeizeTokens(address(this), address(cTokenCollateral), actualRepayAmount); require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED"); /* Revert if borrower collateral token balance < seizeTokens */ require(cTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH"); // If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call uint seizeError; if (address(cTokenCollateral) == address(this)) { seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens); } else { seizeError = cTokenCollateral.seize(liquidator, borrower, seizeTokens); } /* Revert if seize tokens fails (since we cannot be sure of side effects) */ require(seizeError == uint(Error.NO_ERROR), "token seizure failed"); /* We emit a LiquidateBorrow event */ emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(cTokenCollateral), seizeTokens); /* We call the defense hook */ comptroller.liquidateBorrowVerify(address(this), address(cTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens); return (uint(Error.NO_ERROR), actualRepayAmount); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Will fail unless called by another cToken during the process of liquidation. * Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seize(address liquidator, address borrower, uint seizeTokens) external override nonReentrant returns (uint) { return seizeInternal(msg.sender, liquidator, borrower, seizeTokens); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken. * Its absolutely critical to use msg.sender as the seizer cToken and not a parameter. * @param seizerToken The contract seizing the collateral (i.e. borrowed cToken) * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) { /* Fail if seize not allowed */ uint allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER); } MathError mathErr; uint borrowerTokensNew; uint liquidatorTokensNew; /* * We calculate the new borrower and liquidator token balances, failing on underflow/overflow: * borrowerTokensNew = accountTokens[borrower] - seizeTokens * liquidatorTokensNew = accountTokens[liquidator] + seizeTokens */ (mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr)); } (mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accountTokens[borrower] = borrowerTokensNew; accountTokens[liquidator] = liquidatorTokensNew; /* Emit a Transfer event */ emit Transfer(borrower, liquidator, seizeTokens); /* We call the defense hook */ comptroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens); return uint(Error.NO_ERROR); } /*** Admin Functions ***/ /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address payable newPendingAdmin) external override returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() external override returns (uint) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Sets a new comptroller for the market * @dev Admin function to set a new comptroller * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setComptroller(ComptrollerInterface newComptroller) public override returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK); } ComptrollerInterface oldComptroller = comptroller; // Ensure invoke comptroller.isComptroller() returns true require(newComptroller.isComptroller(), "marker method returned false"); // Set market's comptroller to newComptroller comptroller = newComptroller; // Emit NewComptroller(oldComptroller, newComptroller) emit NewComptroller(oldComptroller, newComptroller); return uint(Error.NO_ERROR); } /** * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh * @dev Admin function to accrue interest and set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactor(uint newReserveFactorMantissa) external override nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed. return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED); } // _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to. return _setReserveFactorFresh(newReserveFactorMantissa); } /** * @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual) * @dev Admin function to set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK); } // Verify market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK); } // Check newReserveFactor ≤ maxReserveFactor if (newReserveFactorMantissa > reserveFactorMaxMantissa) { return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK); } uint oldReserveFactorMantissa = reserveFactorMantissa; reserveFactorMantissa = newReserveFactorMantissa; emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Accrues interest and reduces reserves by transferring from msg.sender * @param addAmount Amount of addition to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED); } // _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to. (error, ) = _addReservesFresh(addAmount); return error; } /** * @notice Add reserves by transferring from caller * @dev Requires fresh interest accrual * @param addAmount Amount of addition to reserves * @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees */ function _addReservesFresh(uint addAmount) internal returns (uint, uint) { // totalReserves + actualAddAmount uint totalReservesNew; uint actualAddAmount; // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the caller and the addAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional addAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ actualAddAmount = doTransferIn(msg.sender, addAmount); totalReservesNew = totalReserves + actualAddAmount; /* Revert on overflow */ require(totalReservesNew >= totalReserves, "add reserves unexpected overflow"); // Store reserves[n+1] = reserves[n] + actualAddAmount totalReserves = totalReservesNew; /* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */ emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew); /* Return (NO_ERROR, actualAddAmount) */ return (uint(Error.NO_ERROR), actualAddAmount); } /** * @notice Accrues interest and reduces reserves by transferring to admin * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReserves(uint reduceAmount) external override nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED); } // _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to. return _reduceReservesFresh(reduceAmount); } /** * @notice Reduces reserves by transferring to admin * @dev Requires fresh interest accrual * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReservesFresh(uint reduceAmount) internal returns (uint) { // totalReserves - reduceAmount uint totalReservesNew; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK); } // Fail gracefully if protocol has insufficient underlying cash if (getCashPrior() < reduceAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE); } // Check reduceAmount ≤ reserves[n] (totalReserves) if (reduceAmount > totalReserves) { return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) totalReservesNew = totalReserves - reduceAmount; // We checked reduceAmount <= totalReserves above, so this should never revert. require(totalReservesNew <= totalReserves, "reduce reserves unexpected underflow"); // Store reserves[n+1] = reserves[n] - reduceAmount totalReserves = totalReservesNew; // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. doTransferOut(admin, reduceAmount); emit ReservesReduced(admin, reduceAmount, totalReservesNew); return uint(Error.NO_ERROR); } /** * @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh * @dev Admin function to accrue interest and update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModel(InterestRateModel newInterestRateModel) public override returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED); } // _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to. return _setInterestRateModelFresh(newInterestRateModel); } /** * @notice updates the interest rate model (*requires fresh interest accrual) * @dev Admin function to update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) { // Used to store old model for use in the event that is emitted on success InterestRateModel oldInterestRateModel; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK); } // Track the market's current interest rate model oldInterestRateModel = interestRateModel; // Ensure invoke newInterestRateModel.isInterestRateModel() returns true require(newInterestRateModel.isInterestRateModel(), "marker method returned false"); // Set the interest rate model to newInterestRateModel interestRateModel = newInterestRateModel; // Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel) emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel); return uint(Error.NO_ERROR); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying owned by this contract */ function getCashPrior() internal view virtual returns (uint); /** * @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee. * This may revert due to insufficient balance or insufficient allowance. */ function doTransferIn(address from, uint amount) internal virtual returns (uint); /** * @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting. * If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract. * If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions. */ function doTransferOut(address payable to, uint amount) internal virtual; /*** Reentrancy Guard ***/ /** * @dev Prevents a contract from calling itself, directly or indirectly. */ modifier nonReentrant() { require(_notEntered, "re-entered"); _notEntered = false; _; _notEntered = true; // get a gas-refund post-Istanbul } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./ComptrollerInterface.sol"; import "./InterestRateModel.sol"; contract CTokenStorage { /** * @dev Guard variable for re-entrancy checks */ bool internal _notEntered; /** * @notice EIP-20 token name for this token */ string public name; /** * @notice EIP-20 token symbol for this token */ string public symbol; /** * @notice EIP-20 token decimals for this token */ uint8 public decimals; /** * @notice Maximum borrow rate that can ever be applied (.0005% / block) */ uint internal constant borrowRateMaxMantissa = 0.0005e16; /** * @notice Maximum fraction of interest that can be set aside for reserves */ uint internal constant reserveFactorMaxMantissa = 1e18; /** * @notice Administrator for this contract */ address payable public admin; /** * @notice Pending administrator for this contract */ address payable public pendingAdmin; /** * @notice Contract which oversees inter-cToken operations */ ComptrollerInterface public comptroller; /** * @notice Model which tells what the current interest rate should be */ InterestRateModel public interestRateModel; /** * @notice Initial exchange rate used when minting the first CTokens (used when totalSupply = 0) */ uint internal initialExchangeRateMantissa; /** * @notice Fraction of interest currently set aside for reserves */ uint public reserveFactorMantissa; /** * @notice Block number that interest was last accrued at */ uint public accrualBlockNumber; /** * @notice Accumulator of the total earned interest rate since the opening of the market */ uint public borrowIndex; /** * @notice Total amount of outstanding borrows of the underlying in this market */ uint public totalBorrows; /** * @notice Total amount of reserves of the underlying held in this market */ uint public totalReserves; /** * @notice Total number of tokens in circulation */ uint public totalSupply; /** * @notice Official record of token balances for each account */ mapping (address => uint) internal accountTokens; /** * @notice Approved token transfer amounts on behalf of others */ mapping (address => mapping (address => uint)) internal transferAllowances; /** * @notice Container for borrow balance information * @member principal Total balance (with accrued interest), after applying the most recent balance-changing action * @member interestIndex Global borrowIndex as of the most recent balance-changing action */ struct BorrowSnapshot { uint principal; uint interestIndex; } /** * @notice Mapping of account addresses to outstanding borrow balances */ mapping(address => BorrowSnapshot) internal accountBorrows; } abstract contract CTokenInterface is CTokenStorage { /** * @notice Indicator that this is a CToken contract (for inspection) */ bool public constant isCToken = true; /*** Market Events ***/ /** * @notice Event emitted when interest is accrued */ event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows); /** * @notice Event emitted when tokens are minted */ event Mint(address minter, uint mintAmount, uint mintTokens); /** * @notice Event emitted when tokens are redeemed */ event Redeem(address redeemer, uint redeemAmount, uint redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address cTokenCollateral, uint seizeTokens); /*** Admin Events ***/ /** * @notice Event emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Event emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /** * @notice Event emitted when comptroller is changed */ event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller); /** * @notice Event emitted when interestRateModel is changed */ event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel); /** * @notice Event emitted when the reserve factor is changed */ event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa); /** * @notice Event emitted when the reserves are added */ event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves); /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint amount); /** * @notice Failure event */ event Failure(uint error, uint info, uint detail); /*** User Interface ***/ function transfer(address dst, uint amount) external virtual returns (bool); function transferFrom(address src, address dst, uint amount) external virtual returns (bool); function approve(address spender, uint amount) external virtual returns (bool); function allowance(address owner, address spender) external view virtual returns (uint); function balanceOf(address owner) external view virtual returns (uint); function balanceOfUnderlying(address owner) external virtual returns (uint); function getAccountSnapshot(address account) external view virtual returns (uint, uint, uint, uint); function borrowRatePerBlock() external view virtual returns (uint); function supplyRatePerBlock() external view virtual returns (uint); function totalBorrowsCurrent() external virtual returns (uint); function borrowBalanceCurrent(address account) external virtual returns (uint); function borrowBalanceStored(address account) public view virtual returns (uint); function exchangeRateCurrent() public virtual returns (uint); function exchangeRateStored() public view virtual returns (uint); function getCash() external view virtual returns (uint); function accrueInterest() public virtual returns (uint); function seize(address liquidator, address borrower, uint seizeTokens) external virtual returns (uint); /*** Admin Functions ***/ function _setPendingAdmin(address payable newPendingAdmin) external virtual returns (uint); function _acceptAdmin() external virtual returns (uint); function _setComptroller(ComptrollerInterface newComptroller) public virtual returns (uint); function _setReserveFactor(uint newReserveFactorMantissa) external virtual returns (uint); function _reduceReserves(uint reduceAmount) external virtual returns (uint); function _setInterestRateModel(InterestRateModel newInterestRateModel) public virtual returns (uint); } contract CErc20Storage { /** * @notice Underlying asset for this CToken */ address public underlying; } abstract contract CErc20Interface is CErc20Storage { /*** User Interface ***/ function mint(uint mintAmount) external virtual returns (uint); function redeem(uint redeemTokens) external virtual returns (uint); function redeemUnderlying(uint redeemAmount) external virtual returns (uint); function borrow(uint borrowAmount) external virtual returns (uint); function repayBorrow(uint repayAmount) external virtual returns (uint); function repayBorrowBehalf(address borrower, uint repayAmount) external virtual returns (uint); function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external virtual returns (uint); /*** Admin Functions ***/ function _addReserves(uint addAmount) external virtual returns (uint); } contract CDelegationStorage { /** * @notice Implementation address for this contract */ address public implementation; } abstract contract CDelegatorInterface is CDelegationStorage { /** * @notice Emitted when implementation is changed */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Called by the admin to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public virtual; } abstract contract CDelegateInterface is CDelegationStorage { /** * @notice Called by the delegator on a delegate to initialize it for duty * @dev Should revert if any issues arise which make it unfit for delegation * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public virtual; /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public virtual; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @title Careful Math * @author Compound * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint a, uint b) internal pure returns (MathError, uint) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint a, uint b) internal pure returns (MathError, uint) { uint c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) { (MathError err0, uint sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./CToken.sol"; import "./ErrorReporter.sol"; import "./Exponential.sol"; import "./PriceOracle.sol"; import "./ComptrollerInterface.sol"; import "./ComptrollerStorage.sol"; import "./Unitroller.sol"; import "./Governance/Dop.sol"; /** * @title Compound's Comptroller Contract * @author Compound */ contract Comptroller is ComptrollerV4Storage, ComptrollerInterface, ComptrollerErrorReporter, Exponential { /// @notice Emitted when an admin supports a market event MarketListed(CToken cToken); /// @notice Emitted when an account enters a market event MarketEntered(CToken cToken, address account); /// @notice Emitted when an account exits a market event MarketExited(CToken cToken, address account); /// @notice Emitted when close factor is changed by admin event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa); /// @notice Emitted when a collateral factor is changed by admin event NewCollateralFactor(CToken cToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa); /// @notice Emitted when liquidation incentive is changed by admin event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa); /// @notice Emitted when maxAssets is changed by admin event NewMaxAssets(uint oldMaxAssets, uint newMaxAssets); /// @notice Emitted when price oracle is changed event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle); /// @notice Emitted when pause guardian is changed event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian); /// @notice Emitted when an action is paused globally event ActionPaused(string action, bool pauseState); /// @notice Emitted when an action is paused on a market event ActionPaused(CToken cToken, string action, bool pauseState); /// @notice Emitted when market comped status is changed event MarketComped(CToken cToken, bool isComped); /// @notice Emitted when COMP rate is changed event NewCompRate(uint oldCompRate, uint newCompRate); /// @notice Emitted when a new COMP speed is calculated for a market event CompSpeedUpdated(CToken indexed cToken, uint newSpeed); /// @notice Emitted when COMP is distributed to a supplier event DistributedSupplierComp(CToken indexed cToken, address indexed supplier, uint compDelta, uint compSupplyIndex); /// @notice Emitted when COMP is distributed to a borrower event DistributedBorrowerComp(CToken indexed cToken, address indexed borrower, uint compDelta, uint compBorrowIndex); /// @notice Emitted when borrow cap for a cToken is changed event NewBorrowCap(CToken indexed cToken, uint newBorrowCap); /// @notice Emitted when borrow cap guardian is changed event NewBorrowCapGuardian(address oldBorrowCapGuardian, address newBorrowCapGuardian); /// @notice The threshold above which the flywheel transfers COMP, in wei uint public constant compClaimThreshold = 0.001e18; /// @notice The initial COMP index for a market uint224 public constant compInitialIndex = 1e36; // closeFactorMantissa must be strictly greater than this value uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05 // closeFactorMantissa must not exceed this value uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9 // No collateralFactorMantissa may exceed this value uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9 // liquidationIncentiveMantissa must be no less than this value uint internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0 // liquidationIncentiveMantissa must be no greater than this value uint internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5 constructor() public { admin = msg.sender; } /*** Assets You Are In ***/ /** * @notice Returns the assets an account has entered * @param account The address of the account to pull assets for * @return A dynamic list with the assets the account has entered */ function getAssetsIn(address account) external view returns (CToken[] memory) { CToken[] memory assetsIn = accountAssets[account]; return assetsIn; } /** * @notice Returns whether the given account is entered in the given asset * @param account The address of the account to check * @param cToken The cToken to check * @return True if the account is in the asset, otherwise false. */ function checkMembership(address account, CToken cToken) external view returns (bool) { return markets[address(cToken)].accountMembership[account]; } /** * @notice Add assets to be included in account liquidity calculation * @param cTokens The list of addresses of the cToken markets to be enabled * @return Success indicator for whether each corresponding market was entered */ function enterMarkets(address[] memory cTokens) public override returns (uint[] memory) { uint len = cTokens.length; uint[] memory results = new uint[](len); for (uint i = 0; i < len; i++) { CToken cToken = CToken(cTokens[i]); results[i] = uint(addToMarketInternal(cToken, msg.sender)); } return results; } /** * @notice Add the market to the borrower's "assets in" for liquidity calculations * @param cToken The market to enter * @param borrower The address of the account to modify * @return Success indicator for whether the market was entered */ function addToMarketInternal(CToken cToken, address borrower) internal returns (Error) { Market storage marketToJoin = markets[address(cToken)]; if (!marketToJoin.isListed) { // market is not listed, cannot join return Error.MARKET_NOT_LISTED; } if (marketToJoin.accountMembership[borrower] == true) { // already joined return Error.NO_ERROR; } if (accountAssets[borrower].length >= maxAssets) { // no space, cannot join return Error.TOO_MANY_ASSETS; } // survived the gauntlet, add to list // NOTE: we store these somewhat redundantly as a significant optimization // this avoids having to iterate through the list for the most common use cases // that is, only when we need to perform liquidity checks // and not whenever we want to check if an account is in a particular market marketToJoin.accountMembership[borrower] = true; accountAssets[borrower].push(cToken); emit MarketEntered(cToken, borrower); return Error.NO_ERROR; } /** * @notice Removes asset from sender's account liquidity calculation * @dev Sender must not have an outstanding borrow balance in the asset, * or be providing necessary collateral for an outstanding borrow. * @param cTokenAddress The address of the asset to be removed * @return Whether or not the account successfully exited the market */ function exitMarket(address cTokenAddress) external override returns (uint) { CToken cToken = CToken(cTokenAddress); /* Get sender tokensHeld and amountOwed underlying from the cToken */ (uint oErr, uint tokensHeld, uint amountOwed, ) = cToken.getAccountSnapshot(msg.sender); require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code /* Fail if the sender has a borrow balance */ if (amountOwed != 0) { return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED); } /* Fail if the sender is not permitted to redeem all of their tokens */ uint allowed = redeemAllowedInternal(cTokenAddress, msg.sender, tokensHeld); if (allowed != 0) { return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed); } Market storage marketToExit = markets[address(cToken)]; /* Return true if the sender is not already ‘in’ the market */ if (!marketToExit.accountMembership[msg.sender]) { return uint(Error.NO_ERROR); } /* Set cToken account membership to false */ delete marketToExit.accountMembership[msg.sender]; /* Delete cToken from the account’s list of assets */ // load into memory for faster iteration CToken[] memory userAssetList = accountAssets[msg.sender]; uint len = userAssetList.length; uint assetIndex = len; for (uint i = 0; i < len; i++) { if (userAssetList[i] == cToken) { assetIndex = i; break; } } // We *must* have found the asset in the list or our redundant data structure is broken assert(assetIndex < len); // copy last item in list to location of item to be removed, reduce length by 1 CToken[] storage storedList = accountAssets[msg.sender]; storedList[assetIndex] = storedList[storedList.length - 1]; storedList.pop(); emit MarketExited(cToken, msg.sender); return uint(Error.NO_ERROR); } /*** Policy Hooks ***/ /** * @notice Checks if the account should be allowed to mint tokens in the given market * @param cToken The market to verify the mint against * @param minter The account which would get the minted tokens * @param mintAmount The amount of underlying being supplied to the market in exchange for tokens * @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function mintAllowed(address cToken, address minter, uint mintAmount) external override returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!mintGuardianPaused[cToken], "mint is paused"); // Shh - currently unused minter; mintAmount; if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // Keep the flywheel moving updateCompSupplyIndex(cToken); distributeSupplierComp(cToken, minter, false); return uint(Error.NO_ERROR); } /** * @notice Validates mint and reverts on rejection. May emit logs. * @param cToken Asset being minted * @param minter The address minting the tokens * @param actualMintAmount The amount of the underlying asset being minted * @param mintTokens The number of tokens being minted */ function mintVerify(address cToken, address minter, uint actualMintAmount, uint mintTokens) external override { // Shh - currently unused cToken; minter; actualMintAmount; mintTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to redeem tokens in the given market * @param cToken The market to verify the redeem against * @param redeemer The account which would redeem the tokens * @param redeemTokens The number of cTokens to exchange for the underlying asset in the market * @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external override returns (uint) { uint allowed = redeemAllowedInternal(cToken, redeemer, redeemTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } // Keep the flywheel moving updateCompSupplyIndex(cToken); distributeSupplierComp(cToken, redeemer, false); return uint(Error.NO_ERROR); } function redeemAllowedInternal(address cToken, address redeemer, uint redeemTokens) internal returns (uint) { if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* If the redeemer is not 'in' the market, then we can bypass the liquidity check */ if (!markets[cToken].accountMembership[redeemer]) { return uint(Error.NO_ERROR); } /* Otherwise, perform a hypothetical liquidity check to guard against shortfall */ (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, CToken(cToken), redeemTokens, 0); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } return uint(Error.NO_ERROR); } /** * @notice Validates redeem and reverts on rejection. May emit logs. * @param cToken Asset being redeemed * @param redeemer The address redeeming the tokens * @param redeemAmount The amount of the underlying asset being redeemed * @param redeemTokens The number of tokens being redeemed */ function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external override { // Shh - currently unused cToken; redeemer; // Require tokens is zero or amount is also zero if (redeemTokens == 0 && redeemAmount > 0) { revert("redeemTokens zero"); } } /** * @notice Checks if the account should be allowed to borrow the underlying asset of the given market * @param cToken The market to verify the borrow against * @param borrower The account which would borrow the asset * @param borrowAmount The amount of underlying the account would borrow * @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function borrowAllowed(address cToken, address borrower, uint borrowAmount) external override returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!borrowGuardianPaused[cToken], "borrow is paused"); if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (!markets[cToken].accountMembership[borrower]) { // only cTokens may call borrowAllowed if borrower not in market require(msg.sender == cToken, "sender must be cToken"); // attempt to add borrower to the market Error err = addToMarketInternal(CToken(msg.sender), borrower); if (err != Error.NO_ERROR) { return uint(err); } // it should be impossible to break the important invariant assert(markets[cToken].accountMembership[borrower]); } if (oracle.getUnderlyingPrice(CToken(cToken)) == 0) { return uint(Error.PRICE_ERROR); } uint borrowCap = borrowCaps[cToken]; // Borrow cap of 0 corresponds to unlimited borrowing if (borrowCap != 0) { uint totalBorrows = CToken(cToken).totalBorrows(); (MathError mathErr, uint nextTotalBorrows) = addUInt(totalBorrows, borrowAmount); require(mathErr == MathError.NO_ERROR, "total borrows overflow"); require(nextTotalBorrows < borrowCap, "market borrow cap reached"); } (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, CToken(cToken), 0, borrowAmount); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } // Keep the flywheel moving Exp memory borrowIndex = Exp({mantissa: CToken(cToken).borrowIndex()}); updateCompBorrowIndex(cToken, borrowIndex); distributeBorrowerComp(cToken, borrower, borrowIndex, false); return uint(Error.NO_ERROR); } /** * @notice Validates borrow and reverts on rejection. May emit logs. * @param cToken Asset whose underlying is being borrowed * @param borrower The address borrowing the underlying * @param borrowAmount The amount of the underlying asset requested to borrow */ function borrowVerify(address cToken, address borrower, uint borrowAmount) external override { // Shh - currently unused cToken; borrower; borrowAmount; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to repay a borrow in the given market * @param cToken The market to verify the repay against * @param payer The account which would repay the asset * @param borrower The account which would borrowed the asset * @param repayAmount The amount of the underlying asset the account would repay * @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function repayBorrowAllowed( address cToken, address payer, address borrower, uint repayAmount) external override returns (uint) { // Shh - currently unused payer; borrower; repayAmount; if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // Keep the flywheel moving Exp memory borrowIndex = Exp({mantissa: CToken(cToken).borrowIndex()}); updateCompBorrowIndex(cToken, borrowIndex); distributeBorrowerComp(cToken, borrower, borrowIndex, false); return uint(Error.NO_ERROR); } /** * @notice Validates repayBorrow and reverts on rejection. May emit logs. * @param cToken Asset being repaid * @param payer The address repaying the borrow * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function repayBorrowVerify( address cToken, address payer, address borrower, uint actualRepayAmount, uint borrowerIndex) external override { // Shh - currently unused cToken; payer; borrower; actualRepayAmount; borrowerIndex; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the liquidation should be allowed to occur * @param cTokenBorrowed Asset which was borrowed by the borrower * @param cTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param repayAmount The amount of underlying being repaid */ function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount) external override returns (uint) { // Shh - currently unused liquidator; if (!markets[cTokenBorrowed].isListed || !markets[cTokenCollateral].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* The borrower must have shortfall in order to be liquidatable */ (Error err, , uint shortfall) = getAccountLiquidityInternal(borrower); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall == 0) { return uint(Error.INSUFFICIENT_SHORTFALL); } /* The liquidator may not repay more than what is allowed by the closeFactor */ uint borrowBalance = CToken(cTokenBorrowed).borrowBalanceStored(borrower); (MathError mathErr, uint maxClose) = mulScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance); if (mathErr != MathError.NO_ERROR) { return uint(Error.MATH_ERROR); } if (repayAmount > maxClose) { return uint(Error.TOO_MUCH_REPAY); } return uint(Error.NO_ERROR); } /** * @notice Validates liquidateBorrow and reverts on rejection. May emit logs. * @param cTokenBorrowed Asset which was borrowed by the borrower * @param cTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint actualRepayAmount, uint seizeTokens) external override { // Shh - currently unused cTokenBorrowed; cTokenCollateral; liquidator; borrower; actualRepayAmount; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the seizing of assets should be allowed to occur * @param cTokenCollateral Asset which was used as collateral and will be seized * @param cTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external override returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!seizeGuardianPaused, "seize is paused"); // Shh - currently unused seizeTokens; if (!markets[cTokenCollateral].isListed || !markets[cTokenBorrowed].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (CToken(cTokenCollateral).comptroller() != CToken(cTokenBorrowed).comptroller()) { return uint(Error.COMPTROLLER_MISMATCH); } // Keep the flywheel moving updateCompSupplyIndex(cTokenCollateral); distributeSupplierComp(cTokenCollateral, borrower, false); distributeSupplierComp(cTokenCollateral, liquidator, false); return uint(Error.NO_ERROR); } /** * @notice Validates seize and reverts on rejection. May emit logs. * @param cTokenCollateral Asset which was used as collateral and will be seized * @param cTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external override { // Shh - currently unused cTokenCollateral; cTokenBorrowed; liquidator; borrower; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to transfer tokens in the given market * @param cToken The market to verify the transfer against * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of cTokens to transfer * @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function transferAllowed(address cToken, address src, address dst, uint transferTokens) external override returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!transferGuardianPaused, "transfer is paused"); // Currently the only consideration is whether or not // the src is allowed to redeem this many tokens uint allowed = redeemAllowedInternal(cToken, src, transferTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } // Keep the flywheel moving updateCompSupplyIndex(cToken); distributeSupplierComp(cToken, src, false); distributeSupplierComp(cToken, dst, false); return uint(Error.NO_ERROR); } /** * @notice Validates transfer and reverts on rejection. May emit logs. * @param cToken Asset being transferred * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of cTokens to transfer */ function transferVerify(address cToken, address src, address dst, uint transferTokens) external override { // Shh - currently unused cToken; src; dst; transferTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /*** Liquidity/Liquidation Calculations ***/ /** * @dev Local vars for avoiding stack-depth limits in calculating account liquidity. * Note that `cTokenBalance` is the number of cTokens the account owns in the market, * whereas `borrowBalance` is the amount of underlying that the account has borrowed. */ struct AccountLiquidityLocalVars { uint sumCollateral; uint sumBorrowPlusEffects; uint cTokenBalance; uint borrowBalance; uint exchangeRateMantissa; uint oraclePriceMantissa; Exp collateralFactor; Exp exchangeRate; Exp oraclePrice; Exp tokensToDenom; } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code (semi-opaque), account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidity(address account) public returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, CToken(0), 0, 0); return (uint(err), liquidity, shortfall); } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code, account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidityInternal(address account) internal returns (Error, uint, uint) { return getHypotheticalAccountLiquidityInternal(account, CToken(0), 0, 0); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param cTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @return (possible error code (semi-opaque), hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidity( address account, address cTokenModify, uint redeemTokens, uint borrowAmount) public returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, CToken(cTokenModify), redeemTokens, borrowAmount); return (uint(err), liquidity, shortfall); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param cTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @dev Note that we calculate the exchangeRateStored for each collateral cToken using stored data, * without calculating accumulated interest. * @return (possible error code, hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidityInternal( address account, CToken cTokenModify, uint redeemTokens, uint borrowAmount) internal returns (Error, uint, uint) { AccountLiquidityLocalVars memory vars; // Holds all our calculation results uint oErr; MathError mErr; // For each asset the account is in CToken[] memory assets = accountAssets[account]; for (uint i = 0; i < assets.length; i++) { CToken asset = assets[i]; // Read the balances and exchange rate from the cToken (oErr, vars.cTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account); if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades return (Error.SNAPSHOT_ERROR, 0, 0); } vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa}); vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa}); // Get the normalized price of the asset vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset); if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa}); // Pre-compute a conversion factor from tokens -> ether (normalized price value) (mErr, vars.tokensToDenom) = mulExp3(vars.collateralFactor, vars.exchangeRate, vars.oraclePrice); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // sumCollateral += tokensToDenom * cTokenBalance (mErr, vars.sumCollateral) = mulScalarTruncateAddUInt(vars.tokensToDenom, vars.cTokenBalance, vars.sumCollateral); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // sumBorrowPlusEffects += oraclePrice * borrowBalance (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // Calculate effects of interacting with cTokenModify if (asset == cTokenModify) { // redeem effect // sumBorrowPlusEffects += tokensToDenom * redeemTokens (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // borrow effect // sumBorrowPlusEffects += oraclePrice * borrowAmount (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } } } // These are safe, as the underflow condition is checked first if (vars.sumCollateral > vars.sumBorrowPlusEffects) { return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0); } else { return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral); } } /** * @notice Calculate number of tokens of collateral asset to seize given an underlying amount * @dev Used in liquidation (called in cToken.liquidateBorrowFresh) * @param cTokenBorrowed The address of the borrowed cToken * @param cTokenCollateral The address of the collateral cToken * @param actualRepayAmount The amount of cTokenBorrowed underlying to convert into cTokenCollateral tokens * @return (errorCode, number of cTokenCollateral tokens to be seized in a liquidation) */ function liquidateCalculateSeizeTokens(address cTokenBorrowed, address cTokenCollateral, uint actualRepayAmount) external override returns (uint, uint) { /* Read oracle prices for borrowed and collateral markets */ uint priceBorrowedMantissa = oracle.getUnderlyingPrice(CToken(cTokenBorrowed)); uint priceCollateralMantissa = oracle.getUnderlyingPrice(CToken(cTokenCollateral)); if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) { return (uint(Error.PRICE_ERROR), 0); } /* * Get the exchange rate and calculate the number of collateral tokens to seize: * seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral * seizeTokens = seizeAmount / exchangeRate * = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate) */ uint exchangeRateMantissa = CToken(cTokenCollateral).exchangeRateStored(); // Note: reverts on error uint seizeTokens; Exp memory numerator; Exp memory denominator; Exp memory ratio; MathError mathErr; (mathErr, numerator) = mulExp(liquidationIncentiveMantissa, priceBorrowedMantissa); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, denominator) = mulExp(priceCollateralMantissa, exchangeRateMantissa); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, ratio) = divExp(numerator, denominator); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, seizeTokens) = mulScalarTruncate(ratio, actualRepayAmount); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } return (uint(Error.NO_ERROR), seizeTokens); } /*** Admin Functions ***/ /** * @notice Sets a new price oracle for the comptroller * @dev Admin function to set a new price oracle * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPriceOracle(PriceOracle newOracle) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK); } // Track the old oracle for the comptroller PriceOracle oldOracle = oracle; // Set comptroller's oracle to newOracle oracle = newOracle; // Emit NewPriceOracle(oldOracle, newOracle) emit NewPriceOracle(oldOracle, newOracle); return uint(Error.NO_ERROR); } /** * @notice Sets the closeFactor used when liquidating borrows * @dev Admin function to set closeFactor * @param newCloseFactorMantissa New close factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_CLOSE_FACTOR_OWNER_CHECK); } Exp memory newCloseFactorExp = Exp({mantissa: newCloseFactorMantissa}); Exp memory lowLimit = Exp({mantissa: closeFactorMinMantissa}); if (lessThanOrEqualExp(newCloseFactorExp, lowLimit)) { return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION); } Exp memory highLimit = Exp({mantissa: closeFactorMaxMantissa}); if (lessThanExp(highLimit, newCloseFactorExp)) { return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION); } uint oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = newCloseFactorMantissa; emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets the collateralFactor for a market * @dev Admin function to set per-market collateralFactor * @param cToken The market to set the factor on * @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCollateralFactor(CToken cToken, uint newCollateralFactorMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK); } // Verify market is listed Market storage market = markets[address(cToken)]; if (!market.isListed) { return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS); } Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa}); // Check collateral factor <= 0.9 Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa}); if (lessThanExp(highLimit, newCollateralFactorExp)) { return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION); } // If collateral factor != 0, fail if price == 0 if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(cToken) == 0) { return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE); } // Set market's collateral factor to new collateral factor, remember old value uint oldCollateralFactorMantissa = market.collateralFactorMantissa; market.collateralFactorMantissa = newCollateralFactorMantissa; // Emit event with asset, old collateral factor, and new collateral factor emit NewCollateralFactor(cToken, oldCollateralFactorMantissa, newCollateralFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets maxAssets which controls how many markets can be entered * @dev Admin function to set maxAssets * @param newMaxAssets New max assets * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setMaxAssets(uint newMaxAssets) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_MAX_ASSETS_OWNER_CHECK); } uint oldMaxAssets = maxAssets; maxAssets = newMaxAssets; emit NewMaxAssets(oldMaxAssets, newMaxAssets); return uint(Error.NO_ERROR); } /** * @notice Sets liquidationIncentive * @dev Admin function to set liquidationIncentive * @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK); } // Check de-scaled min <= newLiquidationIncentive <= max Exp memory newLiquidationIncentive = Exp({mantissa: newLiquidationIncentiveMantissa}); Exp memory minLiquidationIncentive = Exp({mantissa: liquidationIncentiveMinMantissa}); if (lessThanExp(newLiquidationIncentive, minLiquidationIncentive)) { return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION); } Exp memory maxLiquidationIncentive = Exp({mantissa: liquidationIncentiveMaxMantissa}); if (lessThanExp(maxLiquidationIncentive, newLiquidationIncentive)) { return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION); } // Save current value for use in log uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa; // Set liquidation incentive to new incentive liquidationIncentiveMantissa = newLiquidationIncentiveMantissa; // Emit event with old incentive, new incentive emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa); return uint(Error.NO_ERROR); } /** * @notice Add the market to the markets mapping and set it as listed * @dev Admin function to set isListed and add support for the market * @param cToken The address of the market (token) to list * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _supportMarket(CToken cToken) external returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK); } if (markets[address(cToken)].isListed) { return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS); } cToken.isCToken(); // Sanity check to make sure its really a CToken markets[address(cToken)] = Market({isListed: true, isComped: false, collateralFactorMantissa: 0}); _addMarketInternal(address(cToken)); emit MarketListed(cToken); return uint(Error.NO_ERROR); } function _addMarketInternal(address cToken) internal { for (uint i = 0; i < allMarkets.length; i ++) { require(allMarkets[i] != CToken(cToken), "market already added"); } allMarkets.push(CToken(cToken)); } /** * @notice Set the given borrow caps for the given cToken markets. Borrowing that brings total borrows to or above borrow cap will revert. * @dev Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing. * @param cTokens The addresses of the markets (tokens) to change the borrow caps for * @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing. */ function _setMarketBorrowCaps(CToken[] calldata cTokens, uint[] calldata newBorrowCaps) external { require(msg.sender == admin || msg.sender == borrowCapGuardian, "not an admin"); uint numMarkets = cTokens.length; uint numBorrowCaps = newBorrowCaps.length; require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input"); for(uint i = 0; i < numMarkets; i++) { borrowCaps[address(cTokens[i])] = newBorrowCaps[i]; emit NewBorrowCap(cTokens[i], newBorrowCaps[i]); } } /** * @notice Admin function to change the Borrow Cap Guardian * @param newBorrowCapGuardian The address of the new Borrow Cap Guardian */ function _setBorrowCapGuardian(address newBorrowCapGuardian) external { require(msg.sender == admin, "not an admin"); // Save current value for inclusion in log address oldBorrowCapGuardian = borrowCapGuardian; // Store borrowCapGuardian with value newBorrowCapGuardian borrowCapGuardian = newBorrowCapGuardian; // Emit NewBorrowCapGuardian(OldBorrowCapGuardian, NewBorrowCapGuardian) emit NewBorrowCapGuardian(oldBorrowCapGuardian, newBorrowCapGuardian); } /** * @notice Admin function to change the Pause Guardian * @param newPauseGuardian The address of the new Pause Guardian * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _setPauseGuardian(address newPauseGuardian) public returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK); } // Save current value for inclusion in log address oldPauseGuardian = pauseGuardian; // Store pauseGuardian with value newPauseGuardian pauseGuardian = newPauseGuardian; // Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian) emit NewPauseGuardian(oldPauseGuardian, pauseGuardian); return uint(Error.NO_ERROR); } function _setMintPaused(CToken cToken, bool state) public returns (bool) { require(markets[address(cToken)].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "not an admin"); mintGuardianPaused[address(cToken)] = state; emit ActionPaused(cToken, "Mint", state); return state; } function _setBorrowPaused(CToken cToken, bool state) public returns (bool) { require(markets[address(cToken)].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "not an admin"); borrowGuardianPaused[address(cToken)] = state; emit ActionPaused(cToken, "Borrow", state); return state; } function _setTransferPaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "not an admin"); transferGuardianPaused = state; emit ActionPaused("Transfer", state); return state; } function _setSeizePaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "not an admin"); seizeGuardianPaused = state; emit ActionPaused("Seize", state); return state; } function _become(Unitroller unitroller) public { require(msg.sender == unitroller.admin(), "only unitroller admin can change brains"); require(unitroller._acceptImplementation() == 0, "change not authorized"); } /** * @notice Checks caller is admin, or this contract is becoming the new implementation */ function adminOrInitializing() internal view returns (bool) { return msg.sender == admin || msg.sender == comptrollerImplementation; } /*** Comp Distribution ***/ /** * @notice Recalculate and update COMP speeds for all COMP markets */ function refreshCompSpeeds() public { require(msg.sender == tx.origin, "only externally owned accounts may refresh speeds"); refreshCompSpeedsInternal(); } function refreshCompSpeedsInternal() internal { CToken[] memory allMarkets_ = allMarkets; for (uint i = 0; i < allMarkets_.length; i++) { CToken cToken = allMarkets_[i]; Exp memory borrowIndex = Exp({mantissa: cToken.borrowIndex()}); updateCompSupplyIndex(address(cToken)); updateCompBorrowIndex(address(cToken), borrowIndex); } Exp memory totalUtility = Exp({mantissa: 0}); Exp[] memory utilities = new Exp[](allMarkets_.length); for (uint i = 0; i < allMarkets_.length; i++) { CToken cToken = allMarkets_[i]; if (markets[address(cToken)].isComped) { Exp memory assetPrice = Exp({mantissa: oracle.getUnderlyingPrice(cToken)}); Exp memory utility = mul_(assetPrice, cToken.totalBorrows()); utilities[i] = utility; totalUtility = add_(totalUtility, utility); } } for (uint i = 0; i < allMarkets_.length; i++) { CToken cToken = allMarkets[i]; uint newSpeed = totalUtility.mantissa > 0 ? mul_(compRate, div_(utilities[i], totalUtility)) : 0; compSpeeds[address(cToken)] = newSpeed; emit CompSpeedUpdated(cToken, newSpeed); } } /** * @notice Accrue COMP to the market by updating the supply index * @param cToken The market whose supply index to update */ function updateCompSupplyIndex(address cToken) internal { CompMarketState storage supplyState = compSupplyState[cToken]; uint supplySpeed = compSpeeds[cToken]; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, uint(supplyState.block)); if (deltaBlocks > 0 && supplySpeed > 0) { uint supplyTokens = CToken(cToken).totalSupply(); uint compAccrued = mul_(deltaBlocks, supplySpeed); Double memory ratio = supplyTokens > 0 ? fraction(compAccrued, supplyTokens) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: supplyState.index}), ratio); compSupplyState[cToken] = CompMarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(blockNumber, "block number exceeds 32 bits") }); } else if (deltaBlocks > 0) { supplyState.block = safe32(blockNumber, "block number exceeds 32 bits"); } } /** * @notice Accrue COMP to the market by updating the borrow index * @param cToken The market whose borrow index to update */ function updateCompBorrowIndex(address cToken, Exp memory marketBorrowIndex) internal { CompMarketState storage borrowState = compBorrowState[cToken]; uint borrowSpeed = compSpeeds[cToken]; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, uint(borrowState.block)); if (deltaBlocks > 0 && borrowSpeed > 0) { uint borrowAmount = div_(CToken(cToken).totalBorrows(), marketBorrowIndex); uint compAccrued = mul_(deltaBlocks, borrowSpeed); Double memory ratio = borrowAmount > 0 ? fraction(compAccrued, borrowAmount) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: borrowState.index}), ratio); compBorrowState[cToken] = CompMarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(blockNumber, "block number exceeds 32 bits") }); } else if (deltaBlocks > 0) { borrowState.block = safe32(blockNumber, "block number exceeds 32 bits"); } } /** * @notice Calculate COMP accrued by a supplier and possibly transfer it to them * @param cToken The market in which the supplier is interacting * @param supplier The address of the supplier to distribute COMP to */ function distributeSupplierComp(address cToken, address supplier, bool distributeAll) internal { CompMarketState storage supplyState = compSupplyState[cToken]; Double memory supplyIndex = Double({mantissa: supplyState.index}); Double memory supplierIndex = Double({mantissa: compSupplierIndex[cToken][supplier]}); compSupplierIndex[cToken][supplier] = supplyIndex.mantissa; if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) { supplierIndex.mantissa = compInitialIndex; } Double memory deltaIndex = sub_(supplyIndex, supplierIndex); uint supplierTokens = CToken(cToken).balanceOf(supplier); uint supplierDelta = mul_(supplierTokens, deltaIndex); uint supplierAccrued = add_(compAccrued[supplier], supplierDelta); compAccrued[supplier] = transferComp(supplier, supplierAccrued, distributeAll ? 0 : compClaimThreshold); emit DistributedSupplierComp(CToken(cToken), supplier, supplierDelta, supplyIndex.mantissa); } /** * @notice Calculate COMP accrued by a borrower and possibly transfer it to them * @dev Borrowers will not begin to accrue until after the first interaction with the protocol. * @param cToken The market in which the borrower is interacting * @param borrower The address of the borrower to distribute COMP to */ function distributeBorrowerComp(address cToken, address borrower, Exp memory marketBorrowIndex, bool distributeAll) internal { CompMarketState storage borrowState = compBorrowState[cToken]; Double memory borrowIndex = Double({mantissa: borrowState.index}); Double memory borrowerIndex = Double({mantissa: compBorrowerIndex[cToken][borrower]}); compBorrowerIndex[cToken][borrower] = borrowIndex.mantissa; if (borrowerIndex.mantissa > 0) { Double memory deltaIndex = sub_(borrowIndex, borrowerIndex); uint borrowerAmount = div_(CToken(cToken).borrowBalanceStored(borrower), marketBorrowIndex); uint borrowerDelta = mul_(borrowerAmount, deltaIndex); uint borrowerAccrued = add_(compAccrued[borrower], borrowerDelta); compAccrued[borrower] = transferComp(borrower, borrowerAccrued, distributeAll ? 0 : compClaimThreshold); emit DistributedBorrowerComp(CToken(cToken), borrower, borrowerDelta, borrowIndex.mantissa); } } /** * @notice Transfer COMP to the user, if they are above the threshold * @dev Note: If there is not enough COMP, we do not perform the transfer all. * @param user The address of the user to transfer COMP to * @param userAccrued The amount of COMP to (possibly) transfer * @return The amount of COMP which was NOT transferred to the user */ function transferComp(address user, uint userAccrued, uint threshold) internal returns (uint) { if (userAccrued >= threshold && userAccrued > 0) { Dop dop = Dop(getCompAddress()); uint bloRemaining = dop.balanceOf(address(this)); if (userAccrued <= bloRemaining) { dop.transfer(user, userAccrued); return 0; } } return userAccrued; } /** * @notice Claim all the comp accrued by holder in all markets * @param holder The address to claim COMP for */ function claimComp(address holder) public { return claimComp(holder, allMarkets); } /** * @notice Claim all the comp accrued by holder in the specified markets * @param holder The address to claim COMP for * @param cTokens The list of markets to claim COMP in */ function claimComp(address holder, CToken[] memory cTokens) public { address[] memory holders = new address[](1); holders[0] = holder; claimComp(holders, cTokens, true, true); } /** * @notice Claim all comp accrued by the holders * @param holders The addresses to claim COMP for * @param cTokens The list of markets to claim COMP in * @param borrowers Whether or not to claim COMP earned by borrowing * @param suppliers Whether or not to claim COMP earned by supplying */ function claimComp(address[] memory holders, CToken[] memory cTokens, bool borrowers, bool suppliers) public { for (uint i = 0; i < cTokens.length; i++) { CToken cToken = cTokens[i]; require(markets[address(cToken)].isListed, "market must be listed"); if (borrowers == true) { Exp memory borrowIndex = Exp({mantissa: cToken.borrowIndex()}); updateCompBorrowIndex(address(cToken), borrowIndex); for (uint j = 0; j < holders.length; j++) { distributeBorrowerComp(address(cToken), holders[j], borrowIndex, true); } } if (suppliers == true) { updateCompSupplyIndex(address(cToken)); for (uint j = 0; j < holders.length; j++) { distributeSupplierComp(address(cToken), holders[j], true); } } } } /*** Comp Distribution Admin ***/ /** * @notice Set the COMP token address * @param _comp The COMP address */ function _setCompAddress(address _comp) public { require(msg.sender == admin, "not an admin"); comp = _comp; } /** * @notice Set the amount of COMP distributed per block * @param compRate_ The amount of COMP wei per block to distribute */ function _setCompRate(uint compRate_) public { require(adminOrInitializing(), "not an admin"); uint oldRate = compRate; compRate = compRate_; emit NewCompRate(oldRate, compRate_); refreshCompSpeedsInternal(); } /** * @notice Add markets to compMarkets, allowing them to earn COMP in the flywheel * @param cTokens The addresses of the markets to add */ function _addCompMarkets(address[] memory cTokens) public { require(adminOrInitializing(), "not an admin"); for (uint i = 0; i < cTokens.length; i++) { _addCompMarketInternal(cTokens[i]); } refreshCompSpeedsInternal(); } function _addCompMarketInternal(address cToken) internal { Market storage market = markets[cToken]; require(market.isListed == true, "comp market is not listed"); require(market.isComped == false, "comp market already added"); market.isComped = true; emit MarketComped(CToken(cToken), true); if (compSupplyState[cToken].index == 0 && compSupplyState[cToken].block == 0) { compSupplyState[cToken] = CompMarketState({ index: compInitialIndex, block: safe32(getBlockNumber(), "block number exceeds 32 bits") }); } if (compBorrowState[cToken].index == 0 && compBorrowState[cToken].block == 0) { compBorrowState[cToken] = CompMarketState({ index: compInitialIndex, block: safe32(getBlockNumber(), "block number exceeds 32 bits") }); } } /** * @notice Remove a market from compMarkets, preventing it from earning COMP in the flywheel * @param cToken The address of the market to drop */ function _dropCompMarket(address cToken) public { require(msg.sender == admin, "not an admin"); Market storage market = markets[cToken]; require(market.isComped == true, "market is not a comp market"); market.isComped = false; emit MarketComped(CToken(cToken), false); refreshCompSpeedsInternal(); } /** * @notice Return all of the markets * @dev The automatic getter may be used to access an individual market. * @return The list of market addresses */ function getAllMarkets() public view returns (CToken[] memory) { return allMarkets; } function getBlockNumber() public view returns (uint) { return block.number; } /** * @notice Return the address of the COMP token * @return The address of COMP */ function getCompAddress() public view returns (address) { return comp; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; abstract contract ComptrollerInterface { /// @notice Indicator that this is a Comptroller contract (for inspection) bool public constant isComptroller = true; /*** Assets You Are In ***/ function enterMarkets(address[] calldata cTokens) external virtual returns (uint[] memory); function exitMarket(address cToken) external virtual returns (uint); /*** Policy Hooks ***/ function mintAllowed(address cToken, address minter, uint mintAmount) external virtual returns (uint); function mintVerify(address cToken, address minter, uint mintAmount, uint mintTokens) external virtual; function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external virtual returns (uint); function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external virtual; function borrowAllowed(address cToken, address borrower, uint borrowAmount) external virtual returns (uint); function borrowVerify(address cToken, address borrower, uint borrowAmount) external virtual; function repayBorrowAllowed( address cToken, address payer, address borrower, uint repayAmount) external virtual returns (uint); function repayBorrowVerify( address cToken, address payer, address borrower, uint repayAmount, uint borrowerIndex) external virtual; function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount) external virtual returns (uint); function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount, uint seizeTokens) external virtual; function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external virtual returns (uint); function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external virtual; function transferAllowed(address cToken, address src, address dst, uint transferTokens) external virtual returns (uint); function transferVerify(address cToken, address src, address dst, uint transferTokens) external virtual; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint repayAmount) external virtual returns (uint, uint); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./CToken.sol"; import "./PriceOracle.sol"; contract UnitrollerAdminStorage { /** * @notice Administrator for this contract */ address public admin; /** * @notice Pending administrator for this contract */ address public pendingAdmin; /** * @notice Active brains of Unitroller */ address public comptrollerImplementation; /** * @notice Pending brains of Unitroller */ address public pendingComptrollerImplementation; } contract ComptrollerV1Storage is UnitrollerAdminStorage { /** * @notice Oracle which gives the price of any given asset */ PriceOracle public oracle; /** * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint public closeFactorMantissa; /** * @notice Multiplier representing the discount on collateral that a liquidator receives */ uint public liquidationIncentiveMantissa; /** * @notice Max number of assets a single account can participate in (borrow or use as collateral) */ uint public maxAssets; /** * @notice Per-account mapping of "assets you are in", capped by maxAssets */ mapping(address => CToken[]) public accountAssets; } contract ComptrollerV2Storage is ComptrollerV1Storage { struct Market { /// @notice Whether or not this market is listed bool isListed; /** * @notice Multiplier representing the most one can borrow against their collateral in this market. * For instance, 0.9 to allow borrowing 90% of collateral value. * Must be between 0 and 1, and stored as a mantissa. */ uint collateralFactorMantissa; /// @notice Per-market mapping of "accounts in this asset" mapping(address => bool) accountMembership; /// @notice Whether or not this market receives COMP bool isComped; } /** * @notice Official mapping of cTokens -> Market metadata * @dev Used e.g. to determine if a market is supported */ mapping(address => Market) public markets; /** * @notice The Pause Guardian can pause certain actions as a safety mechanism. * Actions which allow users to remove their own assets cannot be paused. * Liquidation / seizing / transfer can only be paused globally, not by market. */ address public pauseGuardian; bool public _mintGuardianPaused; bool public _borrowGuardianPaused; bool public transferGuardianPaused; bool public seizeGuardianPaused; mapping(address => bool) public mintGuardianPaused; mapping(address => bool) public borrowGuardianPaused; } contract ComptrollerV3Storage is ComptrollerV2Storage { struct CompMarketState { /// @notice The market's last updated compBorrowIndex or compSupplyIndex uint224 index; /// @notice The block number the index was last updated at uint32 block; } /// @notice A list of all markets CToken[] public allMarkets; /// @notice The rate at which the flywheel distributes COMP, per block uint public compRate; /// @notice The portion of compRate that each market currently receives mapping(address => uint) public compSpeeds; /// @notice The COMP market supply state for each market mapping(address => CompMarketState) public compSupplyState; /// @notice The COMP market borrow state for each market mapping(address => CompMarketState) public compBorrowState; /// @notice The COMP borrow index for each market for each supplier as of the last time they accrued COMP mapping(address => mapping(address => uint)) public compSupplierIndex; /// @notice The COMP borrow index for each market for each borrower as of the last time they accrued COMP mapping(address => mapping(address => uint)) public compBorrowerIndex; /// @notice The COMP accrued but not yet transferred to each user mapping(address => uint) public compAccrued; } contract ComptrollerV4Storage is ComptrollerV3Storage { // @notice The borrowCapGuardian can set borrowCaps to any number for any market. Lowering the borrow cap could disable borrowing on the given market. address public borrowCapGuardian; // @notice Borrow caps enforced by borrowAllowed for each cToken address. Defaults to zero which corresponds to unlimited borrowing. mapping(address => uint) public borrowCaps; // address of comp token address public comp; } contract ComptrollerV5Storage is ComptrollerV4Storage { /// @notice The portion of COMP that each contributor receives per block mapping(address => uint) public compContributorSpeeds; /// @notice Last block at which a contributor's COMP rewards have been allocated mapping(address => uint) public lastContributorBlock; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @title ERC 20 Token Standard Interface * https://eips.ethereum.org/EIPS/eip-20 */ interface EIP20Interface { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return balance The balance */ function balanceOf(address owner) external view returns (uint256 balance); /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return success Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external returns (bool success); /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return success Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external returns (bool success); /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return success Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return remaining The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @title EIP20NonStandardInterface * @dev Version of ERC20 with no return values for `transfer` and `transferFrom` * See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ interface EIP20NonStandardInterface { /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return balance The balance */ function balanceOf(address owner) external view returns (uint256 balance); /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transfer(address dst, uint256 amount) external; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transferFrom(address src, address dst, uint256 amount) external; /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved * @return success Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return remaining The number of tokens allowed to be spent */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; contract ComptrollerErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, COMPTROLLER_MISMATCH, INSUFFICIENT_SHORTFALL, INSUFFICIENT_LIQUIDITY, INVALID_CLOSE_FACTOR, INVALID_COLLATERAL_FACTOR, INVALID_LIQUIDATION_INCENTIVE, MARKET_NOT_ENTERED, // no longer possible MARKET_NOT_LISTED, MARKET_ALREADY_LISTED, MATH_ERROR, NONZERO_BORROW_BALANCE, PRICE_ERROR, REJECTION, SNAPSHOT_ERROR, TOO_MANY_ASSETS, TOO_MUCH_REPAY } enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK, EXIT_MARKET_BALANCE_OWED, EXIT_MARKET_REJECTION, SET_CLOSE_FACTOR_OWNER_CHECK, SET_CLOSE_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_NO_EXISTS, SET_COLLATERAL_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_WITHOUT_PRICE, SET_IMPLEMENTATION_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_VALIDATION, SET_MAX_ASSETS_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_PENDING_IMPLEMENTATION_OWNER_CHECK, SET_PRICE_ORACLE_OWNER_CHECK, SUPPORT_MARKET_EXISTS, SUPPORT_MARKET_OWNER_CHECK, SET_PAUSE_GUARDIAN_OWNER_CHECK } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } contract TokenErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, BAD_INPUT, COMPTROLLER_REJECTION, COMPTROLLER_CALCULATION_ERROR, INTEREST_RATE_MODEL_ERROR, INVALID_ACCOUNT_PAIR, INVALID_CLOSE_AMOUNT_REQUESTED, INVALID_COLLATERAL_FACTOR, MATH_ERROR, MARKET_NOT_FRESH, MARKET_NOT_LISTED, TOKEN_INSUFFICIENT_ALLOWANCE, TOKEN_INSUFFICIENT_BALANCE, TOKEN_INSUFFICIENT_CASH, TOKEN_TRANSFER_IN_FAILED, TOKEN_TRANSFER_OUT_FAILED } /* * Note: FailureInfo (but not Error) is kept in alphabetical order * This is because FailureInfo grows significantly faster, and * the order of Error has some meaning, while the order of FailureInfo * is entirely arbitrary. */ enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, BORROW_ACCRUE_INTEREST_FAILED, BORROW_CASH_NOT_AVAILABLE, BORROW_FRESHNESS_CHECK, BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, BORROW_MARKET_NOT_LISTED, BORROW_COMPTROLLER_REJECTION, LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED, LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED, LIQUIDATE_COLLATERAL_FRESHNESS_CHECK, LIQUIDATE_COMPTROLLER_REJECTION, LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED, LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX, LIQUIDATE_CLOSE_AMOUNT_IS_ZERO, LIQUIDATE_FRESHNESS_CHECK, LIQUIDATE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_REPAY_BORROW_FRESH_FAILED, LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_SEIZE_TOO_MUCH, MINT_ACCRUE_INTEREST_FAILED, MINT_COMPTROLLER_REJECTION, MINT_EXCHANGE_CALCULATION_FAILED, MINT_EXCHANGE_RATE_READ_FAILED, MINT_FRESHNESS_CHECK, MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, MINT_TRANSFER_IN_FAILED, MINT_TRANSFER_IN_NOT_POSSIBLE, REDEEM_ACCRUE_INTEREST_FAILED, REDEEM_COMPTROLLER_REJECTION, REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, REDEEM_EXCHANGE_RATE_READ_FAILED, REDEEM_FRESHNESS_CHECK, REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, REDEEM_TRANSFER_OUT_NOT_POSSIBLE, REDUCE_RESERVES_ACCRUE_INTEREST_FAILED, REDUCE_RESERVES_ADMIN_CHECK, REDUCE_RESERVES_CASH_NOT_AVAILABLE, REDUCE_RESERVES_FRESH_CHECK, REDUCE_RESERVES_VALIDATION, REPAY_BEHALF_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, REPAY_BORROW_COMPTROLLER_REJECTION, REPAY_BORROW_FRESHNESS_CHECK, REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_VALIDATION, SET_COMPTROLLER_OWNER_CHECK, SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED, SET_INTEREST_RATE_MODEL_FRESH_CHECK, SET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_MAX_ASSETS_OWNER_CHECK, SET_ORACLE_MARKET_NOT_LISTED, SET_PENDING_ADMIN_OWNER_CHECK, SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED, SET_RESERVE_FACTOR_ADMIN_CHECK, SET_RESERVE_FACTOR_FRESH_CHECK, SET_RESERVE_FACTOR_BOUNDS_CHECK, TRANSFER_COMPTROLLER_REJECTION, TRANSFER_NOT_ALLOWED, TRANSFER_NOT_ENOUGH, TRANSFER_TOO_MUCH, ADD_RESERVES_ACCRUE_INTEREST_FAILED, ADD_RESERVES_FRESH_CHECK, ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./CarefulMath.sol"; /** * @title Exponential module for storing fixed-precision decimals * @author Compound * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract Exponential is CarefulMath { uint constant expScale = 1e18; uint constant doubleScale = 1e36; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { uint mantissa; } struct Double { uint mantissa; } /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } function safe224(uint n, string memory errorMessage) pure internal returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint n, string memory errorMessage) pure internal returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint a, uint b) pure internal returns (uint) { return add_(a, b, "addition overflow"); } function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint a, uint b) pure internal returns (uint) { return sub_(a, b, "subtraction underflow"); } function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Exp memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Double memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint a, uint b) pure internal returns (uint) { return mul_(a, b, "multiplication overflow"); } function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { if (a == 0 || b == 0) { return 0; } uint c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Exp memory b) pure internal returns (uint) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Double memory b) pure internal returns (uint) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint a, uint b) pure internal returns (uint) { return div_(a, b, "divide by zero"); } function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b > 0, errorMessage); return a / b; } function fraction(uint a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; contract Dop { /// @notice EIP-20 token name for this token string public constant name = "Drops Ownership Power"; /// @notice EIP-20 token symbol for this token string public constant symbol = "DOP"; /// @notice EIP-20 token decimals for this token uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation uint256 public constant totalSupply = 15000000e18; // 15m /// @notice Allowance amounts on behalf of others mapping(address => mapping(address => uint96)) internal allowances; /// @notice Official record of token balances for each account mapping(address => uint96) internal balances; /// @notice A record of each accounts delegate mapping(address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping(address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256( "EIP712Domain(string name,uint256 chainId,address verifyingContract)" ); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping(address => uint256) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged( address indexed delegator, address indexed fromDelegate, address indexed toDelegate ); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged( address indexed delegate, uint256 previousBalance, uint256 newBalance ); /// @notice The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice The standard EIP-20 approval event event Approval( address indexed owner, address indexed spender, uint256 amount ); /** * @notice Construct a new Comp token * @param account The initial account to grant all the tokens */ constructor(address account) public { balances[account] = uint96(totalSupply); emit Transfer(address(0), account, totalSupply); } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint256) { return allowances[account][spender]; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 rawAmount) external returns (bool) { uint96 amount; if (rawAmount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint256) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "Comp::transfer: amount exceeds 96 bits"); _transferTokens(msg.sender, dst, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address src, address dst, uint256 rawAmount ) external returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits"); if (spender != src && spenderAllowance != uint96(-1)) { uint96 newAllowance = sub96( spenderAllowance, amount, "Comp::transferFrom: transfer amount exceeds spender allowance" ); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry) ); bytes32 digest = keccak256( abi.encodePacked("\x19\x01", domainSeparator, structHash) ); address signatory = ecrecover(digest, v, r, s); require( signatory != address(0), "Comp::delegateBySig: invalid signature" ); require( nonce == nonces[signatory]++, "Comp::delegateBySig: invalid nonce" ); require(now <= expiry, "Comp::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint256 blockNumber) public view returns (uint96) { require( blockNumber < block.number, "Comp::getPriorVotes: not yet determined" ); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = balances[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _transferTokens( address src, address dst, uint96 amount ) internal { require( src != address(0), "Comp::_transferTokens: cannot transfer from the zero address" ); require( dst != address(0), "Comp::_transferTokens: cannot transfer to the zero address" ); balances[src] = sub96( balances[src], amount, "Comp::_transferTokens: transfer amount exceeds balance" ); balances[dst] = add96( balances[dst], amount, "Comp::_transferTokens: transfer amount overflows" ); emit Transfer(src, dst, amount); _moveDelegates(delegates[src], delegates[dst], amount); } function _moveDelegates( address srcRep, address dstRep, uint96 amount ) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96( srcRepOld, amount, "Comp::_moveVotes: vote amount underflows" ); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96( dstRepOld, amount, "Comp::_moveVotes: vote amount overflows" ); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes ) internal { uint32 blockNumber = safe32( block.number, "Comp::_writeCheckpoint: block number exceeds 32 bits" ); if ( nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber ) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint( blockNumber, newVotes ); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @title Compound's InterestRateModel Interface * @author Compound */ abstract contract InterestRateModel { /// @notice Indicator that this is an InterestRateModel contract (for inspection) bool public constant isInterestRateModel = true; /** * @notice Calculates the current borrow interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @return The borrow rate per block (as a percentage, and scaled by 1e18) */ function getBorrowRate(uint cash, uint borrows, uint reserves) external virtual view returns (uint); /** * @notice Calculates the current supply interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external virtual view returns (uint); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./CToken.sol"; abstract contract PriceOracle { /// @notice Indicator that this is a PriceOracle contract (for inspection) bool public constant isPriceOracle = true; /** * @notice Get the underlying price of a cToken asset * @param cToken The cToken to get the underlying price of * @return The underlying asset price mantissa (scaled by 1e18). * Zero means the price is unavailable. */ function getUnderlyingPrice(CToken cToken) external virtual returns (uint); function getUnderlyingPriceView(CToken cToken) public view virtual returns (uint); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./ErrorReporter.sol"; import "./ComptrollerStorage.sol"; /** * @title ComptrollerCore * @dev Storage for the comptroller is at this address, while execution is delegated to the `comptrollerImplementation`. * CTokens should reference this contract as their comptroller. */ contract Unitroller is UnitrollerAdminStorage, ComptrollerErrorReporter { /** * @notice Emitted when pendingComptrollerImplementation is changed */ event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation); /** * @notice Emitted when pendingComptrollerImplementation is accepted, which means comptroller implementation is updated */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); constructor() public { // Set admin to caller admin = msg.sender; } /*** Admin Functions ***/ function _setPendingImplementation(address newPendingImplementation) public returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_IMPLEMENTATION_OWNER_CHECK); } address oldPendingImplementation = pendingComptrollerImplementation; pendingComptrollerImplementation = newPendingImplementation; emit NewPendingImplementation(oldPendingImplementation, pendingComptrollerImplementation); return uint(Error.NO_ERROR); } /** * @notice Accepts new implementation of comptroller. msg.sender must be pendingImplementation * @dev Admin function for new implementation to accept it's role as implementation * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptImplementation() public returns (uint) { // Check caller is pendingImplementation and pendingImplementation ≠ address(0) if (msg.sender != pendingComptrollerImplementation || pendingComptrollerImplementation == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK); } // Save current values for inclusion in log address oldImplementation = comptrollerImplementation; address oldPendingImplementation = pendingComptrollerImplementation; comptrollerImplementation = pendingComptrollerImplementation; pendingComptrollerImplementation = address(0); emit NewImplementation(oldImplementation, comptrollerImplementation); emit NewPendingImplementation(oldPendingImplementation, pendingComptrollerImplementation); return uint(Error.NO_ERROR); } /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address newPendingAdmin) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() public returns (uint) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint(Error.NO_ERROR); } /** * @dev Delegates execution to an implementation contract. * It returns to the external caller whatever the implementation returns * or forwards reverts. */ fallback () payable external { // delegate all other functions to current implementation (bool success, ) = comptrollerImplementation.delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize()) switch success case 0 { revert(free_mem_ptr, returndatasize()) } default { return(free_mem_ptr, returndatasize()) } } } }
Keep the flywheel moving
updateCompSupplyIndex(cTokenCollateral);
564,595
[ 1, 11523, 326, 21434, 21344, 12499, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 1089, 2945, 3088, 1283, 1016, 12, 71, 1345, 13535, 2045, 287, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /** * @title L1BuildParam * @dev L1BuildParam has parameters and contract code for Verse-Layer builds. */ contract L1BuildParam { /********************** * Contract Variables * **********************/ uint256 public maxTransactionGasLimit; uint256 public l2GasDiscountDivisor; uint256 public enqueueGasCost; uint256 public fraudProofWindow; uint256 public sequencerPublishWindow; bytes public l1StandardBridgeCode; bytes public l1ERC721BridgeCode; /*************** * Constructor * ***************/ /** * @param _maxTransactionGasLimit Max transaction gas limit. * @param _l2GasDiscountDivisor L2(Vserse-Layer) gas discount divisor. * @param _enqueueGasCost Enqueue gas cost. * @param _fraudProofWindow Fraud proof window. * @param _sequencerPublishWindow Sequencer publish window. */ constructor( uint256 _maxTransactionGasLimit, uint256 _l2GasDiscountDivisor, uint256 _enqueueGasCost, uint256 _fraudProofWindow, uint256 _sequencerPublishWindow ) { maxTransactionGasLimit = _maxTransactionGasLimit; l2GasDiscountDivisor = _l2GasDiscountDivisor; enqueueGasCost = _enqueueGasCost; fraudProofWindow = _fraudProofWindow; sequencerPublishWindow = _sequencerPublishWindow; } /******************** * Public Functions * ********************/ /** * Sets the code of the L1StandardBridge code. * @param _code Code of the L1StandardBridge code. */ function setL1StandardBridgeCode(bytes memory _code) external { require(l1StandardBridgeCode.length == 0, "the code has already been set"); l1StandardBridgeCode = _code; } /** * Sets the code of the L1ERC721Bridge code. * @param _code Code of the L1ERC721Bridge code. */ function setL1ERC721BridgeCode(bytes memory _code) external { require(l1ERC721BridgeCode.length == 0, "the code has already been set"); l1ERC721BridgeCode = _code; } /** * Returns the code hash of the L1StandardBridge code. */ function l1StandardBridgeCodeHash() external view returns (bytes32) { return keccak256(l1StandardBridgeCode); } /** * Returns the code hash of the L1ERC721Bridge code. */ function l1ERC721BridgeCodeHash() external view returns (bytes32) { return keccak256(l1ERC721BridgeCode); } }
********************* Contract Variables /************** Constructor /* @param _maxTransactionGasLimit Max transaction gas limit. @param _l2GasDiscountDivisor L2(Vserse-Layer) gas discount divisor. @param _enqueueGasCost Enqueue gas cost. @param _fraudProofWindow Fraud proof window. @param _sequencerPublishWindow Sequencer publish window./
) { maxTransactionGasLimit = _maxTransactionGasLimit; l2GasDiscountDivisor = _l2GasDiscountDivisor; enqueueGasCost = _enqueueGasCost; fraudProofWindow = _fraudProofWindow; sequencerPublishWindow = _sequencerPublishWindow; }
2,529,338
[ 1, 8924, 23536, 342, 11417, 342, 225, 389, 1896, 3342, 27998, 3039, 4238, 2492, 16189, 1800, 18, 225, 389, 80, 22, 27998, 9866, 7244, 12385, 511, 22, 12, 58, 550, 307, 17, 4576, 13, 16189, 12137, 15013, 18, 225, 389, 21798, 27998, 8018, 1374, 4000, 16189, 6991, 18, 225, 389, 74, 354, 1100, 20439, 3829, 478, 354, 1100, 14601, 2742, 18, 225, 389, 307, 372, 23568, 6024, 3829, 3265, 372, 23568, 3808, 2742, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 262, 288, 203, 3639, 943, 3342, 27998, 3039, 273, 389, 1896, 3342, 27998, 3039, 31, 203, 3639, 328, 22, 27998, 9866, 7244, 12385, 273, 389, 80, 22, 27998, 9866, 7244, 12385, 31, 203, 3639, 12850, 27998, 8018, 273, 389, 21798, 27998, 8018, 31, 203, 3639, 284, 354, 1100, 20439, 3829, 273, 389, 74, 354, 1100, 20439, 3829, 31, 203, 3639, 26401, 23568, 6024, 3829, 273, 389, 307, 372, 23568, 6024, 3829, 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 ]
pragma solidity ^0.4.21; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Burn(address indexed from, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ 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't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); 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 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)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function () public payable { revert(); } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ /** * @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 { event Mint(address indexed to, uint256 amount); function mint(address _to, uint256 _amount) internal returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); return true; } function burn(uint256 _value) public returns (bool) { require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. totalSupply = totalSupply.sub(_value); balances[msg.sender] = balances[msg.sender].sub(_value); balances[address(0)] = balances[address(0)].add(_value); emit Burn(msg.sender, _value); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ } contract HondaCivic is MintableToken{ string public constant name = "Honda Civic"; string public constant symbol = "HCV"; uint32 public constant decimals = 18; IERC20 token = IERC20(address(0x6b175474e89094c44da98b954eedeac495271d0f)); function create(uint256 daiAmount) public returns (bool) { mint(msg.sender, daiAmount/21000); require(token.transferFrom(msg.sender, address(this), daiAmount)); return true; } function sell(uint256 civics) public returns (bool) { token.transfer(msg.sender, civics*21000); require(burn(civics)); return true; } } 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); }
* approve should be called when allowed[_spender] == 0. To increment allowed value is better to use this function to avoid 2 calls (and wait until the first transaction is mined) From MonolithDAO Token.sol/
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; }
1,321,380
[ 1, 12908, 537, 1410, 506, 2566, 1347, 2935, 63, 67, 87, 1302, 264, 65, 422, 374, 18, 2974, 5504, 2935, 460, 353, 7844, 358, 999, 333, 445, 358, 4543, 576, 4097, 261, 464, 2529, 3180, 326, 1122, 2492, 353, 1131, 329, 13, 225, 6338, 9041, 355, 483, 18485, 3155, 18, 18281, 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, 225, 445, 10929, 23461, 261, 2867, 389, 87, 1302, 264, 16, 2254, 389, 9665, 620, 13, 1071, 1135, 261, 6430, 2216, 13, 288, 203, 565, 2935, 63, 3576, 18, 15330, 6362, 67, 87, 1302, 264, 65, 273, 2935, 63, 3576, 18, 15330, 6362, 67, 87, 1302, 264, 8009, 1289, 24899, 9665, 620, 1769, 203, 565, 3626, 1716, 685, 1125, 12, 3576, 18, 15330, 16, 389, 87, 1302, 264, 16, 2935, 63, 3576, 18, 15330, 6362, 67, 87, 1302, 264, 19226, 7010, 565, 327, 638, 31, 7010, 225, 289, 203, 7010, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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: SEE LICENSE IN LICENSE pragma solidity 0.6.12; import "../utility/ContractRegistryClient.sol"; import "./interfaces/IConverterRegistryData.sol"; /** * @dev The ConverterRegistryData contract is an integral part of the converter registry * as it serves as the database contract that holds all registry data. * * The registry is separated into two different contracts for upgradability - the data contract * is harder to upgrade as it requires migrating all registry data into a new contract, while * the registry contract itself can be easily upgraded. * * For that same reason, the data contract is simple and contains no logic beyond the basic data * access utilities that it exposes. */ contract ConverterRegistryData is IConverterRegistryData, ContractRegistryClient { struct Item { bool valid; uint256 index; } struct Items { address[] array; mapping(address => Item) table; } struct List { uint256 index; Items items; } struct Lists { address[] array; mapping(address => List) table; } Items private smartTokens; Items private liquidityPools; Lists private convertibleTokens; /** * @dev initializes a new ConverterRegistryData instance * * @param _registry address of a contract registry contract */ constructor(IContractRegistry _registry) ContractRegistryClient(_registry) public { } /** * @dev adds a smart token * * @param _anchor smart token */ function addSmartToken(IConverterAnchor _anchor) external override only(CONVERTER_REGISTRY) { addItem(smartTokens, address(_anchor)); } /** * @dev removes a smart token * * @param _anchor smart token */ function removeSmartToken(IConverterAnchor _anchor) external override only(CONVERTER_REGISTRY) { removeItem(smartTokens, address(_anchor)); } /** * @dev adds a liquidity pool * * @param _liquidityPoolAnchor liquidity pool */ function addLiquidityPool(IConverterAnchor _liquidityPoolAnchor) external override only(CONVERTER_REGISTRY) { addItem(liquidityPools, address(_liquidityPoolAnchor)); } /** * @dev removes a liquidity pool * * @param _liquidityPoolAnchor liquidity pool */ function removeLiquidityPool(IConverterAnchor _liquidityPoolAnchor) external override only(CONVERTER_REGISTRY) { removeItem(liquidityPools, address(_liquidityPoolAnchor)); } /** * @dev adds a convertible token * * @param _convertibleToken convertible token * @param _anchor associated smart token */ function addConvertibleToken(IERC20Token _convertibleToken, IConverterAnchor _anchor) external override only(CONVERTER_REGISTRY) { List storage list = convertibleTokens.table[address(_convertibleToken)]; if (list.items.array.length == 0) { list.index = convertibleTokens.array.length; convertibleTokens.array.push(address(_convertibleToken)); } addItem(list.items, address(_anchor)); } /** * @dev removes a convertible token * * @param _convertibleToken convertible token * @param _anchor associated smart token */ function removeConvertibleToken(IERC20Token _convertibleToken, IConverterAnchor _anchor) external override only(CONVERTER_REGISTRY) { List storage list = convertibleTokens.table[address(_convertibleToken)]; removeItem(list.items, address(_anchor)); if (list.items.array.length == 0) { address lastConvertibleToken = convertibleTokens.array[convertibleTokens.array.length - 1]; convertibleTokens.table[lastConvertibleToken].index = list.index; convertibleTokens.array[list.index] = lastConvertibleToken; convertibleTokens.array.pop(); delete convertibleTokens.table[address(_convertibleToken)]; } } /** * @dev returns the number of smart tokens * * @return number of smart tokens */ function getSmartTokenCount() external view override returns (uint256) { return smartTokens.array.length; } /** * @dev returns the list of smart tokens * * @return list of smart tokens */ function getSmartTokens() external view override returns (address[] memory) { return smartTokens.array; } /** * @dev returns the smart token at a given index * * @param _index index * @return smart token at the given index */ function getSmartToken(uint256 _index) external view override returns (IConverterAnchor) { return IConverterAnchor(smartTokens.array[_index]); } /** * @dev checks whether or not a given value is a smart token * * @param _value value * @return true if the given value is a smart token, false if not */ function isSmartToken(address _value) external view override returns (bool) { return smartTokens.table[_value].valid; } /** * @dev returns the number of liquidity pools * * @return number of liquidity pools */ function getLiquidityPoolCount() external view override returns (uint256) { return liquidityPools.array.length; } /** * @dev returns the list of liquidity pools * * @return list of liquidity pools */ function getLiquidityPools() external view override returns (address[] memory) { return liquidityPools.array; } /** * @dev returns the liquidity pool at a given index * * @param _index index * @return liquidity pool at the given index */ function getLiquidityPool(uint256 _index) external view override returns (IConverterAnchor) { return IConverterAnchor(liquidityPools.array[_index]); } /** * @dev checks whether or not a given value is a liquidity pool * * @param _value value * @return true if the given value is a liquidity pool, false if not */ function isLiquidityPool(address _value) external view override returns (bool) { return liquidityPools.table[_value].valid; } /** * @dev returns the number of convertible tokens * * @return number of convertible tokens */ function getConvertibleTokenCount() external view override returns (uint256) { return convertibleTokens.array.length; } /** * @dev returns the list of convertible tokens * * @return list of convertible tokens */ function getConvertibleTokens() external view override returns (address[] memory) { return convertibleTokens.array; } /** * @dev returns the convertible token at a given index * * @param _index index * @return convertible token at the given index */ function getConvertibleToken(uint256 _index) external view override returns (IERC20Token) { return IERC20Token(convertibleTokens.array[_index]); } /** * @dev checks whether or not a given value is a convertible token * * @param _value value * @return true if the given value is a convertible token, false if not */ function isConvertibleToken(address _value) external view override returns (bool) { return convertibleTokens.table[_value].items.array.length > 0; } /** * @dev returns the number of smart tokens associated with a given convertible token * * @param _convertibleToken convertible token * @return number of smart tokens associated with the given convertible token */ function getConvertibleTokenSmartTokenCount(IERC20Token _convertibleToken) external view override returns (uint256) { return convertibleTokens.table[address(_convertibleToken)].items.array.length; } /** * @dev returns the list of smart tokens associated with a given convertible token * * @param _convertibleToken convertible token * @return list of smart tokens associated with the given convertible token */ function getConvertibleTokenSmartTokens(IERC20Token _convertibleToken) external view override returns (address[] memory) { return convertibleTokens.table[address(_convertibleToken)].items.array; } /** * @dev returns the smart token associated with a given convertible token at a given index * * @param _index index * @return smart token associated with the given convertible token at the given index */ function getConvertibleTokenSmartToken(IERC20Token _convertibleToken, uint256 _index) external view override returns (IConverterAnchor) { return IConverterAnchor(convertibleTokens.table[address(_convertibleToken)].items.array[_index]); } /** * @dev checks whether or not a given value is a smart token of a given convertible token * * @param _convertibleToken convertible token * @param _value value * @return true if the given value is a smart token of the given convertible token, false it not */ function isConvertibleTokenSmartToken(IERC20Token _convertibleToken, address _value) external view override returns (bool) { return convertibleTokens.table[address(_convertibleToken)].items.table[_value].valid; } /** * @dev adds an item to a list of items * * @param _items list of items * @param _value item's value */ function addItem(Items storage _items, address _value) internal validAddress(_value) { Item storage item = _items.table[_value]; require(!item.valid, "ERR_INVALID_ITEM"); item.index = _items.array.length; _items.array.push(_value); item.valid = true; } /** * @dev removes an item from a list of items * * @param _items list of items * @param _value item's value */ function removeItem(Items storage _items, address _value) internal validAddress(_value) { Item storage item = _items.table[_value]; require(item.valid, "ERR_INVALID_ITEM"); address lastValue = _items.array[_items.array.length - 1]; _items.table[lastValue].index = item.index; _items.array[item.index] = lastValue; _items.array.pop(); delete _items.table[_value]; } }
* @dev returns the list of smart tokens @return list of smart tokens/
function getSmartTokens() external view override returns (address[] memory) { return smartTokens.array; }
2,531,832
[ 1, 6154, 326, 666, 434, 13706, 2430, 327, 666, 434, 13706, 2430, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1322, 81, 485, 5157, 1435, 3903, 1476, 3849, 1135, 261, 2867, 8526, 3778, 13, 288, 203, 3639, 327, 13706, 5157, 18, 1126, 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 ]
./full_match/3/0xF1c53b805CDE10d08edAAD712f7b3ECF159af4FC/sources/browser/BRXCrowdsale.sol
* @title RefundEscrow @dev Escrow that holds funds for a beneficiary, deposited from multiple parties. @dev Intended usage: See {Escrow}. Same usage guidelines apply here. @dev The primary account (that is, the contract that instantiates this contract) may deposit, close the deposit period, and allow for either withdrawal by the beneficiary, or refunds to the depositors. All interactions with `RefundEscrow` will be made through the primary contract. See the `RefundableCrowdsale` contract for an example of `RefundEscrow`’s use./
contract RefundEscrow is ConditionalEscrow { event RefundsClosed(); event RefundsEnabled(); State private _state; address payable private _beneficiary; enum State { Active, Refunding, Closed } constructor (address payable beneficiary) public { require(beneficiary != address(0), "RefundEscrow: beneficiary is the zero address"); _beneficiary = beneficiary; _state = State.Active; } function state() public view returns (State) { return _state; } function beneficiary() public view returns (address) { return _beneficiary; } function deposit(address refundee) public payable { require(_state == State.Active, "RefundEscrow: can only deposit while active"); super.deposit(refundee); } function close() public onlyPrimary { require(_state == State.Active, "RefundEscrow: can only close while active"); _state = State.Closed; emit RefundsClosed(); } function enableRefunds() public onlyPrimary { require(_state == State.Active, "RefundEscrow: can only enable refunds while active"); _state = State.Refunding; emit RefundsEnabled(); } function beneficiaryWithdraw() public { require(_state == State.Closed, "RefundEscrow: beneficiary can only withdraw while closed"); _beneficiary.transfer(address(this).balance); } function withdrawalAllowed(address) public view returns (bool) { return _state == State.Refunding; } }
8,168,917
[ 1, 21537, 6412, 492, 225, 512, 1017, 492, 716, 14798, 284, 19156, 364, 279, 27641, 74, 14463, 814, 16, 443, 1724, 329, 628, 3229, 1087, 606, 18, 225, 657, 8140, 4084, 30, 2164, 288, 6412, 492, 5496, 17795, 4084, 9875, 14567, 2230, 2674, 18, 225, 1021, 3354, 2236, 261, 19056, 353, 16, 326, 6835, 716, 5934, 16020, 333, 6835, 13, 2026, 443, 1724, 16, 1746, 326, 443, 1724, 3879, 16, 471, 1699, 364, 3344, 598, 9446, 287, 635, 326, 27641, 74, 14463, 814, 16, 578, 16255, 87, 358, 326, 443, 1724, 1383, 18, 4826, 23877, 598, 1375, 21537, 6412, 492, 68, 903, 506, 7165, 3059, 326, 3354, 6835, 18, 2164, 326, 1375, 21537, 429, 39, 492, 2377, 5349, 68, 6835, 364, 392, 3454, 434, 1375, 21537, 6412, 492, 68, 163, 227, 252, 87, 999, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 3941, 1074, 6412, 492, 353, 22466, 6412, 492, 288, 203, 203, 565, 871, 3941, 19156, 7395, 5621, 203, 565, 871, 3941, 19156, 1526, 5621, 203, 203, 565, 3287, 3238, 389, 2019, 31, 203, 565, 1758, 8843, 429, 3238, 389, 70, 4009, 74, 14463, 814, 31, 203, 203, 565, 2792, 3287, 288, 8857, 16, 3941, 14351, 16, 25582, 289, 203, 565, 3885, 261, 2867, 8843, 429, 27641, 74, 14463, 814, 13, 1071, 288, 203, 3639, 2583, 12, 70, 4009, 74, 14463, 814, 480, 1758, 12, 20, 3631, 315, 21537, 6412, 492, 30, 27641, 74, 14463, 814, 353, 326, 3634, 1758, 8863, 203, 3639, 389, 70, 4009, 74, 14463, 814, 273, 27641, 74, 14463, 814, 31, 203, 3639, 389, 2019, 273, 3287, 18, 3896, 31, 203, 565, 289, 203, 203, 565, 445, 919, 1435, 1071, 1476, 1135, 261, 1119, 13, 288, 203, 3639, 327, 389, 2019, 31, 203, 565, 289, 203, 203, 565, 445, 27641, 74, 14463, 814, 1435, 1071, 1476, 1135, 261, 2867, 13, 288, 203, 3639, 327, 389, 70, 4009, 74, 14463, 814, 31, 203, 565, 289, 203, 203, 565, 445, 443, 1724, 12, 2867, 1278, 318, 20953, 13, 1071, 8843, 429, 288, 203, 3639, 2583, 24899, 2019, 422, 3287, 18, 3896, 16, 315, 21537, 6412, 492, 30, 848, 1338, 443, 1724, 1323, 2695, 8863, 203, 3639, 2240, 18, 323, 1724, 12, 1734, 318, 20953, 1769, 203, 565, 289, 203, 203, 565, 445, 1746, 1435, 1071, 1338, 6793, 288, 203, 3639, 2583, 24899, 2019, 422, 3287, 18, 3896, 16, 315, 21537, 6412, 492, 2 ]
./partial_match/1/0xDB8367c2cB51532951C570857832AebD4D72Ece7/sources/contracts/wtf20230607.sol
this is the mint function for managers onlyset nftStat[newItemId]. struct items
function mint(string memory tokenURI) public { address wtfManAddr1=ownerOf(wtfManager1); address wtfManAddr2=ownerOf(wtfManager2); _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); _safeMint(msg.sender, newItemId); _setTokenURI(newItemId, tokenURI); }
15,636,789
[ 1, 2211, 353, 326, 312, 474, 445, 364, 21103, 1338, 542, 290, 1222, 5000, 63, 2704, 17673, 8009, 1958, 1516, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 312, 474, 12, 1080, 3778, 1147, 3098, 13, 1071, 288, 203, 3639, 1758, 341, 6632, 5669, 3178, 21, 33, 8443, 951, 12, 6046, 74, 1318, 21, 1769, 203, 3639, 1758, 341, 6632, 5669, 3178, 22, 33, 8443, 951, 12, 6046, 74, 1318, 22, 1769, 203, 3639, 389, 2316, 2673, 18, 15016, 5621, 203, 203, 3639, 2254, 5034, 394, 17673, 273, 389, 2316, 2673, 18, 2972, 5621, 203, 203, 3639, 389, 4626, 49, 474, 12, 3576, 18, 15330, 16, 394, 17673, 1769, 203, 3639, 389, 542, 1345, 3098, 12, 2704, 17673, 16, 1147, 3098, 1769, 203, 203, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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-03-21 */ /* Website https://www.shibakiba.com/ */ // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } 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 () public { 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; } } 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; } } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { 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; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 9; } /** * @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: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @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 Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } contract SHIBAKIBA is ERC20, Ownable { using SafeMath for uint256; address public constant DEAD_ADDRESS = address(0xdead); IUniswapV2Router02 public constant uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uint256 public buyLiquidityFee = 3; uint256 public sellLiquidityFee = 3; uint256 public buyTxFee = 9; uint256 public sellTxFee = 9; uint256 public tokensForLiquidity; uint256 public tokensForTax; uint256 public _tTotal = 10**9 * 10**9; // 1 billion uint256 public swapAtAmount = _tTotal.mul(10).div(10000); // 0.10% of total supply uint256 public maxTxLimit = _tTotal.mul(75).div(10000); // 0.75% of total supply uint256 public maxWalletLimit = _tTotal.mul(150).div(10000); // 1.50% of total supply address public dev; address public immutable deployer; address public uniswapV2Pair; uint256 private launchBlock; bool private swapping; bool public isLaunched; // exclude from fees mapping (address => bool) public isExcludedFromFees; // exclude from max transaction amount mapping (address => bool) public isExcludedFromTxLimit; // exclude from max wallet limit mapping (address => bool) public isExcludedFromWalletLimit; // if the account is blacklisted from transacting mapping (address => bool) public isBlacklisted; constructor(address _dev) public ERC20("ShibaKiba", "SHIBAKIBA") { uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory()).createPair(address(this), uniswapV2Router.WETH()); _approve(address(this), address(uniswapV2Router), type(uint256).max); // exclude from fees, wallet limit and transaction limit excludeFromAllLimits(owner(), true); excludeFromAllLimits(address(this), true); excludeFromWalletLimit(uniswapV2Pair, true); dev = _dev; deployer = _msgSender(); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(owner(), _tTotal); } function excludeFromFees(address account, bool value) public onlyOwner() { require(isExcludedFromFees[account] != value, "Fees: Already set to this value"); isExcludedFromFees[account] = value; } function excludeFromTxLimit(address account, bool value) public onlyOwner() { require(isExcludedFromTxLimit[account] != value, "TxLimit: Already set to this value"); isExcludedFromTxLimit[account] = value; } function excludeFromWalletLimit(address account, bool value) public onlyOwner() { require(isExcludedFromWalletLimit[account] != value, "WalletLimit: Already set to this value"); isExcludedFromWalletLimit[account] = value; } function excludeFromAllLimits(address account, bool value) public onlyOwner() { excludeFromFees(account, value); excludeFromTxLimit(account, value); excludeFromWalletLimit(account, value); } function setBuyFee(uint256 liquidityFee, uint256 txFee) external onlyOwner() { buyLiquidityFee = liquidityFee; buyTxFee = txFee; } function setSellFee(uint256 liquidityFee, uint256 txFee) external onlyOwner() { sellLiquidityFee = liquidityFee; sellTxFee = txFee; } function setMaxTxLimit(uint256 newLimit) external onlyOwner() { maxTxLimit = newLimit * (10**9); } function setMaxWalletLimit(uint256 newLimit) external onlyOwner() { maxWalletLimit = newLimit * (10**9); } function setSwapAtAmount(uint256 amountToSwap) external onlyOwner() { swapAtAmount = amountToSwap * (10**9); } function updateDevWallet(address newWallet) external onlyOwner() { dev = newWallet; } function addBlacklist(address account) external onlyOwner() { require(!isBlacklisted[account], "Blacklist: Already blacklisted"); require(account != uniswapV2Pair, "Cannot blacklist pair"); _setBlacklist(account, true); } function removeBlacklist(address account) external onlyOwner() { require(isBlacklisted[account], "Blacklist: Not blacklisted"); _setBlacklist(account, false); } function launchNow() external onlyOwner() { require(!isLaunched, "Contract is already launched"); isLaunched = true; launchBlock = block.number; } function _transfer(address from, address to, uint256 amount) internal override { require(from != address(0), "transfer from the zero address"); require(to != address(0), "transfer to the zero address"); require(amount <= maxTxLimit || isExcludedFromTxLimit[from] || isExcludedFromTxLimit[to], "Tx Amount too large"); require(balanceOf(to).add(amount) <= maxWalletLimit || isExcludedFromWalletLimit[to], "Transfer will exceed wallet limit"); require(isLaunched || isExcludedFromFees[from] || isExcludedFromFees[to], "Waiting to go live"); require(!isBlacklisted[from], "Sender is blacklisted"); if(amount == 0) { super._transfer(from, to, 0); return; } uint256 totalTokensForFee = tokensForLiquidity + tokensForTax; bool canSwap = totalTokensForFee >= swapAtAmount; if( from != uniswapV2Pair && canSwap && !swapping ) { swapping = true; swapBack(totalTokensForFee); swapping = false; } else if( from == uniswapV2Pair && to != uniswapV2Pair && block.number < launchBlock + 2 && !isExcludedFromFees[to] ) { _setBlacklist(to, true); } bool takeFee = !swapping; if(isExcludedFromFees[from] || isExcludedFromFees[to]) { takeFee = false; } if(takeFee) { uint256 fees; // on sell if (to == uniswapV2Pair) { uint256 sellTotalFees = sellLiquidityFee.add(sellTxFee); fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity = tokensForLiquidity.add(fees.mul(sellLiquidityFee).div(sellTotalFees)); tokensForTax = tokensForTax.add(fees.mul(sellTxFee).div(sellTotalFees)); } // on buy & wallet transfers else { uint256 buyTotalFees = buyLiquidityFee.add(buyTxFee); fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity = tokensForLiquidity.add(fees.mul(buyLiquidityFee).div(buyTotalFees)); tokensForTax = tokensForTax.add(fees.mul(buyTxFee).div(buyTotalFees)); } if(fees > 0){ super._transfer(from, address(this), fees); amount = amount.sub(fees); } } super._transfer(from, to, amount); } function swapBack(uint256 totalTokensForFee) private { uint256 toSwap = swapAtAmount; // Halve the amount of liquidity tokens uint256 liquidityTokens = toSwap.mul(tokensForLiquidity).div(totalTokensForFee).div(2); uint256 taxTokens = toSwap.sub(liquidityTokens).sub(liquidityTokens); uint256 amountToSwapForETH = toSwap.sub(liquidityTokens); _swapTokensForETH(amountToSwapForETH); uint256 ethBalance = address(this).balance; uint256 ethForTax = ethBalance.mul(taxTokens).div(amountToSwapForETH); uint256 ethForLiquidity = ethBalance.sub(ethForTax); tokensForLiquidity = tokensForLiquidity.sub(liquidityTokens.mul(2)); tokensForTax = tokensForTax.sub(toSwap.sub(liquidityTokens.mul(2))); payable(address(dev)).transfer(ethForTax); _addLiquidity(liquidityTokens, ethForLiquidity); } function _addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, 0, deployer, block.timestamp ); } function _swapTokensForETH(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function _setBlacklist(address account, bool value) internal { isBlacklisted[account] = value; } receive() external payable {} }
exclude from fees, wallet limit and transaction limit
function _beforeTokenTransfer( address from, address to, uint256 amount } constructor(address _dev) public ERC20("ShibaKiba", "SHIBAKIBA") { uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory()).createPair(address(this), uniswapV2Router.WETH()); _approve(address(this), address(uniswapV2Router), type(uint256).max); excludeFromAllLimits(owner(), true); excludeFromAllLimits(address(this), true); excludeFromWalletLimit(uniswapV2Pair, true); dev = _dev; deployer = _msgSender(); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(owner(), _tTotal);
10,878,543
[ 1, 10157, 628, 1656, 281, 16, 9230, 1800, 471, 2492, 1800, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 97, 203, 203, 565, 3885, 12, 2867, 389, 5206, 13, 1071, 4232, 39, 3462, 2932, 1555, 495, 69, 47, 495, 69, 3113, 315, 2664, 45, 12536, 47, 45, 12536, 7923, 288, 203, 203, 3639, 640, 291, 91, 438, 58, 22, 4154, 273, 467, 984, 291, 91, 438, 58, 22, 1733, 12, 318, 291, 91, 438, 58, 22, 8259, 18, 6848, 1435, 2934, 2640, 4154, 12, 2867, 12, 2211, 3631, 640, 291, 91, 438, 58, 22, 8259, 18, 59, 1584, 44, 10663, 203, 3639, 389, 12908, 537, 12, 2867, 12, 2211, 3631, 1758, 12, 318, 291, 91, 438, 58, 22, 8259, 3631, 618, 12, 11890, 5034, 2934, 1896, 1769, 203, 203, 203, 3639, 4433, 1265, 1595, 12768, 12, 8443, 9334, 638, 1769, 203, 3639, 4433, 1265, 1595, 12768, 12, 2867, 12, 2211, 3631, 638, 1769, 203, 3639, 4433, 1265, 16936, 3039, 12, 318, 291, 91, 438, 58, 22, 4154, 16, 638, 1769, 203, 203, 3639, 4461, 273, 389, 5206, 31, 203, 3639, 7286, 264, 273, 389, 3576, 12021, 5621, 203, 203, 5411, 389, 81, 474, 353, 392, 2713, 445, 316, 4232, 39, 3462, 18, 18281, 716, 353, 1338, 2566, 2674, 16, 203, 5411, 471, 385, 16791, 506, 2566, 14103, 3382, 203, 3639, 389, 81, 474, 12, 8443, 9334, 389, 88, 5269, 1769, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x869F685E5659798F874c736FDd1ce80f70675f9C/sources/DGMContract.sol
* @title ERC20Basic @dev Simpler version of ERC20 interface/
contract IERC20 { function totalSupply() public view returns (uint); 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); 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); }
15,720,857
[ 1, 654, 39, 3462, 8252, 225, 9587, 20728, 1177, 434, 4232, 39, 3462, 1560, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 16351, 467, 654, 39, 3462, 288, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 1476, 1135, 261, 11890, 1769, 203, 565, 445, 11013, 951, 12, 2867, 10354, 13, 1071, 1476, 1135, 261, 11890, 5034, 1769, 203, 565, 445, 7412, 12, 2867, 358, 16, 2254, 5034, 460, 13, 1071, 1135, 261, 6430, 1769, 203, 565, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 460, 1769, 203, 7010, 565, 445, 1699, 1359, 12, 2867, 3410, 16, 1758, 17571, 264, 13, 1071, 1476, 1135, 261, 11890, 5034, 1769, 203, 565, 445, 7412, 1265, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 460, 13, 1071, 1135, 261, 6430, 1769, 203, 565, 445, 6617, 537, 12, 2867, 17571, 264, 16, 2254, 5034, 460, 13, 1071, 1135, 261, 6430, 1769, 203, 565, 871, 1716, 685, 1125, 12, 2867, 8808, 3410, 16, 1758, 8808, 17571, 264, 16, 2254, 5034, 460, 1769, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.11; contract CrowdFunding { // Defines a new type with two fields. struct Funder { address addr; uint amount; } struct Campaign { address beneficiary; uint fundingGoal; uint numFunders; uint amount; mapping (uint => Funder) funders; } uint public numCampaigns; mapping (uint => Campaign) public campaigns; function newCampaign(address beneficiary, uint goal) public returns (uint campaignID) { campaignID = numCampaigns++; // campaignID is return variable // Creates new struct and saves in storage. We leave out the mapping type. campaigns[campaignID] = Campaign(beneficiary, goal, 0, 0); } function contribute(uint campaignID) public payable { Campaign storage c = campaigns[campaignID]; // Creates a new temporary memory struct, initialised with the given values // and copies it over to storage. // Note that you can also use Funder(msg.sender, msg.value) to initialise. c.funders[c.numFunders++] = Funder({addr: msg.sender, amount: msg.value}); c.amount += msg.value; } function checkGoalReached(uint campaignID) public returns (bool reached) { Campaign storage c = campaigns[campaignID]; if (c.amount < c.fundingGoal) return false; uint amount = c.amount; c.amount = 0; c.beneficiary.transfer(amount); return true; } }
Defines a new type with two fields.
contract CrowdFunding { struct Funder { address addr; uint amount; } struct Campaign { address beneficiary; uint fundingGoal; uint numFunders; uint amount; mapping (uint => Funder) funders; } uint public numCampaigns; mapping (uint => Campaign) public campaigns; function newCampaign(address beneficiary, uint goal) public returns (uint campaignID) { campaigns[campaignID] = Campaign(beneficiary, goal, 0, 0); } function contribute(uint campaignID) public payable { Campaign storage c = campaigns[campaignID]; c.amount += msg.value; } c.funders[c.numFunders++] = Funder({addr: msg.sender, amount: msg.value}); function checkGoalReached(uint campaignID) public returns (bool reached) { Campaign storage c = campaigns[campaignID]; if (c.amount < c.fundingGoal) return false; uint amount = c.amount; c.amount = 0; c.beneficiary.transfer(amount); return true; } }
15,784,087
[ 1, 15109, 279, 394, 618, 598, 2795, 1466, 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, 385, 492, 72, 42, 14351, 288, 203, 565, 1958, 478, 9341, 288, 203, 3639, 1758, 3091, 31, 203, 3639, 2254, 3844, 31, 203, 565, 289, 203, 203, 565, 1958, 17820, 288, 203, 3639, 1758, 27641, 74, 14463, 814, 31, 203, 3639, 2254, 22058, 27716, 31, 203, 3639, 2254, 818, 42, 26843, 31, 203, 3639, 2254, 3844, 31, 203, 3639, 2874, 261, 11890, 516, 478, 9341, 13, 284, 26843, 31, 203, 565, 289, 203, 203, 565, 2254, 1071, 818, 13432, 87, 31, 203, 565, 2874, 261, 11890, 516, 17820, 13, 1071, 8965, 87, 31, 203, 203, 565, 445, 394, 13432, 12, 2867, 27641, 74, 14463, 814, 16, 2254, 17683, 13, 1071, 1135, 261, 11890, 8965, 734, 13, 288, 203, 3639, 8965, 87, 63, 14608, 734, 65, 273, 17820, 12, 70, 4009, 74, 14463, 814, 16, 17683, 16, 374, 16, 374, 1769, 203, 565, 289, 203, 203, 565, 445, 356, 887, 12, 11890, 8965, 734, 13, 1071, 8843, 429, 288, 203, 3639, 17820, 2502, 276, 273, 8965, 87, 63, 14608, 734, 15533, 203, 3639, 276, 18, 8949, 1011, 1234, 18, 1132, 31, 203, 565, 289, 203, 203, 3639, 276, 18, 74, 26843, 63, 71, 18, 2107, 42, 26843, 9904, 65, 273, 478, 9341, 12590, 4793, 30, 1234, 18, 15330, 16, 3844, 30, 1234, 18, 1132, 22938, 203, 565, 445, 866, 27716, 23646, 12, 11890, 8965, 734, 13, 1071, 1135, 261, 6430, 8675, 13, 288, 203, 3639, 17820, 2502, 276, 273, 8965, 87, 63, 14608, 734, 15533, 203, 3639, 309, 261, 71, 18, 8949, 411, 276, 2 ]
./partial_match/4/0x1F75b29F849185e8B57E24Fe6fAb09c176583942/sources/ChickenChef.sol
CHIFI tokens created per block.
uint256 public initChickenPerBlock;
8,562,328
[ 1, 1792, 5794, 2430, 2522, 1534, 1203, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2254, 5034, 1071, 1208, 782, 1200, 275, 2173, 1768, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x1a6aa939A1682Cdffa08a35c22795d933AF9A116/sources/EthernaalFlaNft.sol
* This is a getter function to get the current price of an NFT./
function getSalePrice(uint256 tokenId) public view returns (uint256) { return salePrice[tokenId]; }
5,000,953
[ 1, 2503, 353, 279, 7060, 445, 358, 336, 326, 783, 6205, 434, 392, 423, 4464, 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 ]
[ 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, 1322, 5349, 5147, 12, 11890, 5034, 1147, 548, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 272, 5349, 5147, 63, 2316, 548, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/42161/0x2679753c8037b6c1404b33EB7690331C902F0075/sources/src/JoeDexLens.sol
* @notice Returns the prices of each token in Native, scaled with wnative's decimals @param tokens The list of address of the tokens @return prices The prices of each token in Native, with wnative's decimals/
function getTokensPricesNative(address[] calldata tokens) external view override returns (uint256[] memory prices) { return _getTokenWeightedAverageNativePrices(tokens); }
16,298,078
[ 1, 1356, 326, 19827, 434, 1517, 1147, 316, 16717, 16, 12304, 598, 341, 13635, 1807, 15105, 225, 2430, 1021, 666, 434, 1758, 434, 326, 2430, 327, 19827, 1021, 19827, 434, 1517, 1147, 316, 16717, 16, 598, 341, 13635, 1807, 15105, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 18349, 31862, 9220, 12, 2867, 8526, 745, 892, 2430, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 3849, 203, 3639, 1135, 261, 11890, 5034, 8526, 3778, 19827, 13, 203, 565, 288, 203, 3639, 327, 389, 588, 1345, 6544, 329, 17115, 9220, 31862, 12, 7860, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-04-28 */ /** */ pragma solidity ^0.4.11; contract Owned { address public owner; function Owned() { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function setOwner(address _newOwner) onlyOwner { 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'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; } function toUINT112(uint256 a) internal constant returns(uint112) { assert(uint112(a) == a); return uint112(a); } function toUINT120(uint256 a) internal constant returns(uint120) { assert(uint120(a) == a); return uint120(a); } function toUINT128(uint256 a) internal constant returns(uint128) { assert(uint128(a) == a); return uint128(a); } } // Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/issues/20 contract Token { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens //uint256 public totalSupply; function totalSupply() constant returns (uint256 supply); /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant 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); } /// Nereon token, ERC20 compliant contract Nereon is Token, Owned { using SafeMath for uint256; string public constant name = "Nereon Token"; //The Token's name uint8 public constant decimals = 18; //Number of decimals of the smallest unit string public constant symbol = "Nereon"; //An identifier // packed to 256bit to save gas usage. struct Supplies { // uint128's max value is about 3e38. // it's enough to present amount of tokens uint128 total; uint128 rawTokens; } Supplies supplies; // Packed to 256bit to save gas usage. struct Account { // uint112's max value is about 5e33. // it's enough to present amount of tokens uint112 balance; // raw token can be transformed into balance with bonus uint112 rawTokens; // safe to store timestamp uint32 lastMintedTimestamp; } // Balances for each account mapping(address => Account) accounts; // Owner of account approves the transfer of an amount to another account mapping(address => mapping(address => uint256)) allowed; // bonus that can be shared by raw tokens uint256 bonusOffered; // Constructor function Nereon() { } function totalSupply() constant returns (uint256 supply){ return supplies.total; } // Send back ether sent to me function () { revert(); } // If sealed, transfer is enabled and mint is disabled function isSealed() constant returns (bool) { return owner == 0; } function lastMintedTimestamp(address _owner) constant returns(uint32) { return accounts[_owner].lastMintedTimestamp; } // Claim bonus by raw tokens function claimBonus(address _owner) internal{ require(isSealed()); if (accounts[_owner].rawTokens != 0) { uint256 realBalance = balanceOf(_owner); uint256 bonus = realBalance .sub(accounts[_owner].balance) .sub(accounts[_owner].rawTokens); accounts[_owner].balance = realBalance.toUINT112(); accounts[_owner].rawTokens = 0; if(bonus > 0){ Transfer(this, _owner, bonus); } } } // What is the balance of a particular account? function balanceOf(address _owner) constant returns (uint256 balance) { if (accounts[_owner].rawTokens == 0) return accounts[_owner].balance; if (bonusOffered > 0) { uint256 bonus = bonusOffered .mul(accounts[_owner].rawTokens) .div(supplies.rawTokens); return bonus.add(accounts[_owner].balance) .add(accounts[_owner].rawTokens); } return uint256(accounts[_owner].balance) .add(accounts[_owner].rawTokens); } // Transfer the balance from owner's account to another account function transfer(address _to, uint256 _amount) returns (bool success) { require(isSealed()); // implicitly claim bonus for both sender and receiver claimBonus(msg.sender); claimBonus(_to); // according to VEN's total supply, never overflow here if (accounts[msg.sender].balance >= _amount && _amount > 0) { accounts[msg.sender].balance -= uint112(_amount); accounts[_to].balance = _amount.add(accounts[_to].balance).toUINT112(); 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 ) returns (bool success) { require(isSealed()); // implicitly claim bonus for both sender and receiver claimBonus(_from); claimBonus(_to); // according to VEN's total supply, never overflow here if (accounts[_from].balance >= _amount && allowed[_from][msg.sender] >= _amount && _amount > 0) { accounts[_from].balance -= uint112(_amount); allowed[_from][msg.sender] -= _amount; accounts[_to].balance = _amount.add(accounts[_to].balance).toUINT112(); 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) returns (bool success) { allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. //if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { revert(); } ApprovalReceiver(_spender).receiveApproval(msg.sender, _value, this, _extraData); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } // Mint tokens and assign to some one function mint(address _owner, uint256 _amount, bool _isRaw, uint32 timestamp) onlyOwner{ if (_isRaw) { accounts[_owner].rawTokens = _amount.add(accounts[_owner].rawTokens).toUINT112(); supplies.rawTokens = _amount.add(supplies.rawTokens).toUINT128(); } else { accounts[_owner].balance = _amount.add(accounts[_owner].balance).toUINT112(); } accounts[_owner].lastMintedTimestamp = timestamp; supplies.total = _amount.add(supplies.total).toUINT128(); Transfer(0, _owner, _amount); } // Offer bonus to raw tokens holder function offerBonus(uint256 _bonus) onlyOwner { bonusOffered = bonusOffered.add(_bonus); supplies.total = _bonus.add(supplies.total).toUINT128(); Transfer(0, this, _bonus); } // Set owner to zero address, to disable mint, and enable token transfer function seal() onlyOwner { setOwner(0); } } contract ApprovalReceiver { function receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData); } // Contract to sell and distribute Nereon tokens contract nereonSale is Owned{ /// chart of stage transition /// /// deploy initialize startTime endTime finalize /// | <-earlyStageLasts-> | | <- closedStageLasts -> | /// O-----------O---------------O---------------------O-------------O------------------------O------------> /// Created Initialized Early Normal Closed Finalized enum Stage { NotCreated, Created, Initialized, Early, Normal, Closed, Finalized } using SafeMath for uint256; uint256 public constant totalSupply = (10 ** 9) * (10 ** 18); // 1 billion VEN, decimals set to 18 uint256 constant privateSupply = totalSupply * 9 / 100; // 9% for private ICO uint256 constant commercialPlan = totalSupply * 23 / 100; // 23% for commercial plan uint256 constant reservedForTeam = totalSupply * 5 / 100; // 5% for team uint256 constant reservedForOperations = totalSupply * 22 / 100; // 22 for operations // 59% uint256 public constant nonPublicSupply = privateSupply + commercialPlan + reservedForTeam + reservedForOperations; // 41% uint256 public constant publicSupply = totalSupply - nonPublicSupply; uint256 public constant officialLimit = 64371825 * (10 ** 18); uint256 public constant channelsLimit = publicSupply - officialLimit; // packed to 256bit struct SoldOut { uint16 placeholder; // placeholder to make struct pre-alloced // amount of tokens officially sold out. // max value of 120bit is about 1e36, it's enough for token amount uint120 official; uint120 channels; // amount of tokens sold out via channels } SoldOut soldOut; uint256 constant nereonPerEth = 3500; // normal exchange rate uint256 constant nereonPerEthEarlyStage = nereonPerEth + nereonPerEth * 15 / 100; // early stage has 15% reward uint constant minBuyInterval = 30 minutes; // each account can buy once in 30 minutes uint constant maxBuyEthAmount = 30 ether; Nereon nereon; // Nereon token contract follows ERC20 standard address ethVault; // the account to keep received ether address nereonVault; // the account to keep non-public offered Nereon tokens uint public constant startTime = 1503057600; // time to start sale uint public constant endTime = 1504180800; // tiem to close sale uint public constant earlyStageLasts = 3 days; // early bird stage lasts in seconds bool initialized; bool finalized; function NereonSale() { soldOut.placeholder = 1; } /// @notice calculte exchange rate according to current stage /// @return exchange rate. zero if not in sale. function exchangeRate() constant returns (uint256){ if (stage() == Stage.Early) { return nereonPerEthEarlyStage; } if (stage() == Stage.Normal) { return nereonPerEth; } return 0; } /// @notice for test purpose function blockTime() constant returns (uint32) { return uint32(block.timestamp); } /// @notice estimate stage /// @return current stage function stage() constant returns (Stage) { if (finalized) { return Stage.Finalized; } if (!initialized) { // deployed but not initialized return Stage.Created; } if (blockTime() < startTime) { // not started yet return Stage.Initialized; } if (uint256(soldOut.official).add(soldOut.channels) >= publicSupply) { // all sold out return Stage.Closed; } if (blockTime() < endTime) { // in sale if (blockTime() < startTime.add(earlyStageLasts)) { // early bird stage return Stage.Early; } // normal stage return Stage.Normal; } // closed return Stage.Closed; } function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size > 0; } /// @notice entry to buy tokens function () payable { buy(); } /// @notice entry to buy tokens function buy() payable { // reject contract buyer to avoid breaking interval limit require(!isContract(msg.sender)); require(msg.value >= 0.01 ether); uint256 rate = exchangeRate(); // here don't need to check stage. rate is only valid when in sale require(rate > 0); // each account is allowed once in minBuyInterval require(blockTime() >= nereon.lastMintedTimestamp(msg.sender) + minBuyInterval); uint256 requested; // and limited to maxBuyEthAmount if (msg.value > maxBuyEthAmount) { requested = maxBuyEthAmount.mul(rate); } else { requested = msg.value.mul(rate); } uint256 remained = officialLimit.sub(soldOut.official); if (requested > remained) { //exceed remained requested = remained; } uint256 ethCost = requested.div(rate); if (requested > 0) { nereon.mint(msg.sender, requested, true, blockTime()); // transfer ETH to vault ethVault.transfer(ethCost); soldOut.official = requested.add(soldOut.official).toUINT120(); onSold(msg.sender, requested, ethCost); } uint256 toReturn = msg.value.sub(ethCost); if(toReturn > 0) { // return over payed ETH msg.sender.transfer(toReturn); } } /// @notice returns tokens sold officially function officialSold() constant returns (uint256) { return soldOut.official; } /// @notice returns tokens sold via channels function channelsSold() constant returns (uint256) { return soldOut.channels; } /// @notice manually offer tokens to channel function offerToChannel(address _channelAccount, uint256 _nereonAmount) onlyOwner { Stage stg = stage(); // since the settlement may be delayed, so it's allowed in closed stage require(stg == Stage.Early || stg == Stage.Normal || stg == Stage.Closed); soldOut.channels = _nereonAmount.add(soldOut.channels).toUINT120(); //should not exceed limit require(soldOut.channels <= channelsLimit); nereon.mint( _channelAccount, _nereonAmount, true, // unsold tokens can be claimed by channels portion blockTime() ); onSold(_channelAccount, _nereonAmount, 0); } /// @notice initialize to prepare for sale /// @param _nereon The address Nereon token contract following ERC20 standard /// @param _ethVault The place to store received ETH /// @param _nereonVault The place to store non-publicly supplied Nereon tokens function initialize( Nereon _nereon, address _ethVault, address _nereonVault) onlyOwner { require(stage() == Stage.Created); // ownership of token contract should already be this require(_nereon.owner() == address(this)); require(address(_ethVault) != 0); require(address(_nereonVault) != 0); nereon = _nereon; ethVault = _ethVault; nereonVault = _nereonVault; nereon.mint( nereonVault, reservedForTeam.add(reservedForOperations), false, // team and operations reserved portion can't share unsold tokens blockTime() ); nereon.mint( nereonVault, privateSupply.add(commercialPlan), true, // private ICO and commercial plan can share unsold tokens blockTime() ); initialized = true; onInitialized(); } /// @notice finalize function finalize() onlyOwner { // only after closed stage require(stage() == Stage.Closed); uint256 unsold = publicSupply.sub(soldOut.official).sub(soldOut.channels); if (unsold > 0) { // unsold Nereon as bonus nereon.offerBonus(unsold); } nereon.seal(); finalized = true; onFinalized(); } event onInitialized(); event onFinalized(); event onSold(address indexed buyer, uint256 nereonAmount, uint256 ethCost); }
@notice for test purpose
function blockTime() constant returns (uint32) { return uint32(block.timestamp); }
2,089,929
[ 1, 1884, 1842, 13115, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1203, 950, 1435, 5381, 1135, 261, 11890, 1578, 13, 288, 203, 3639, 327, 2254, 1578, 12, 2629, 18, 5508, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// // EntitiesDAO token // $NTTZ v2 // https://entities.wtf // // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; interface MGEX0 { function balanceOG(address _user) external view returns(uint256); } interface NTTZV1 { function getTotalClaimable(address _user) external view returns(uint256); } contract NTTZToken is ERC20("EntitiesDAO Token", "NTTZ"), Ownable { using SafeMath for uint256; bool public hasClaimingStarted = false; bool public hasBurningStarted = false; bool public oldBurnAllowed = false; uint256 constant public BASE_RATE = 10 ether; uint256 constant public INITIAL_ISSUANCE = 1800 ether; uint256 constant public END = 1951230000; //Friday, October 31, 2031 4:20:00 PM (GMT) mapping(address => uint256) public rewards; mapping(address => uint256) public lastUpdate; mapping(address => uint256) public rates; // Contributor wallet daily rate mapping(address => uint256) public ends; // Contributor wallet vesting end MGEX0 public metaGeckosContract; NTTZV1 public nttzV1Contract; event RewardPaid(address indexed user, uint256 reward); event RewardBal(address indexed user, uint256 reward); event RewardCreated(uint256 rewards); function nttz_V1SetAddress(address _nttz) external onlyOwner { nttzV1Contract = NTTZV1(_nttz); } function createInitialReward(address _user, uint256 _initial) public onlyOwner { _initial = _initial * 10**uint(decimals()); setInitialReward(_user, _initial); } function setInitialReward(address _user, uint256 _amount) internal { // Update the value at this address rewards[_user] = rewards[_user] + _amount; emit RewardCreated(rewards[_user]); } function createDailyReward(address _user, uint256 _rates, uint256 _ends) public onlyOwner { _rates = _rates * 10**uint(decimals()); setDailyReward(_user, _rates, _ends); } function setDailyReward(address _user, uint256 _amount, uint256 _ends) internal { // Update the value at this address ends[_user] = _ends; rates[_user] = _amount; emit RewardCreated(rewards[_user]); } function resetDailyContribReward(address _user)public onlyOwner{ ends[_user] = 0; rates[_user] = 0; } function resetAllContribReward(address _user)public onlyOwner{ ends[_user] = 0; rates[_user] = 0; rewards[_user] = 0; } //NTTZ Claiming controller START function startClaiming() public onlyOwner { hasClaimingStarted = true; } //NTTZ Claiming controller PAUSE function pauseClaiming() public onlyOwner { hasClaimingStarted = false; } //NTTZ Burning controller START function startBurning() public onlyOwner { hasBurningStarted = true; } //NTTZ Burning controller PAUSE function pauseBurning() public onlyOwner { hasBurningStarted = false; } constructor(address _mgex0) { metaGeckosContract = MGEX0(_mgex0); } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function updateV1MintRewards(address _user) public onlyOwner { uint256 _prevBal = nttzV1Contract.getTotalClaimable(_user); uint256 time = min(block.timestamp, END); rewards[_user] = _prevBal; lastUpdate[_user] = time; } // Called when minting genesis metageckos // 10 $NTTZ per genesis metagecko per day for 10 years // + 1800 $NTTZ initial reward per genesis metagecko minted function updateRewardOnMint(address _user, uint256 _amount) external { require(msg.sender == address(metaGeckosContract), "Can't call this"); uint256 time = min(block.timestamp, END); uint256 timerUser = lastUpdate[_user]; if (timerUser > 0) rewards[_user] = rewards[_user].add(metaGeckosContract.balanceOG(_user).mul(BASE_RATE.mul((time.sub(timerUser)))).div(86400) .add(_amount.mul(INITIAL_ISSUANCE))); else rewards[_user] = rewards[_user].add(_amount.mul(INITIAL_ISSUANCE)); lastUpdate[_user] = time; } // called on transfers function updateReward(address _from, address _to, uint256 _tokenId) external { require(msg.sender == address(metaGeckosContract)); if (_tokenId < 4000) { uint256 time = min(block.timestamp, END); uint256 timerFrom = lastUpdate[_from]; if (timerFrom > 0) rewards[_from] += metaGeckosContract.balanceOG(_from).mul(BASE_RATE.mul((time.sub(timerFrom)))).div(86400); if (timerFrom != END) lastUpdate[_from] = time; if (_to != address(0)) { uint256 timerTo = lastUpdate[_to]; if (timerTo > 0) rewards[_to] += metaGeckosContract.balanceOG(_to).mul(BASE_RATE.mul((time.sub(timerTo)))).div(86400); if (timerTo != END) lastUpdate[_to] = time; } } } // contributor reward update function updateContribReward(address _from) external { uint256 time = min(block.timestamp, ends[_from]); uint256 timerFrom = lastUpdate[_from]; if (timerFrom > 0) rewards[_from] += rates[_from].mul((time.sub(timerFrom))).div(86400); if (timerFrom != ends[_from]) lastUpdate[_from] = time; } function getReward(address _to) external { require(msg.sender == address(metaGeckosContract)); require(hasClaimingStarted == true, "NTTZ claiming is paused"); uint256 reward = rewards[_to]; if (reward > 0) { rewards[_to] = 0; _mint(_to, reward); emit RewardPaid(_to, reward); } } function burnNTTZ(uint256 _amount) public { require(hasBurningStarted == true, "NTTZ burning is paused"); address _from = msg.sender; _burn(_from, _amount); } //old broken function disabled function burn(address _from, uint256 _amount) external { require(msg.sender == address(metaGeckosContract)); require(oldBurnAllowed == true, "This function is locked"); _burn(_from, _amount); } function getTotalClaimable(address _user) external view returns(uint256) { uint256 time = min(block.timestamp, END); uint256 pending = metaGeckosContract.balanceOG(_user).mul(BASE_RATE.mul((time.sub(lastUpdate[_user])))).div(86400); return rewards[_user] + pending; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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 "../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); }
Friday, October 31, 2031 4:20:00 PM (GMT)
uint256 constant public END = 1951230000;
11,820
[ 1, 42, 1691, 528, 16, 29482, 83, 744, 8231, 16, 4200, 6938, 1059, 30, 3462, 30, 713, 23544, 261, 25315, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 11890, 5034, 5381, 1071, 7273, 273, 24262, 12936, 2787, 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 ]
pragma solidity 0.4.24; pragma experimental "v0.5.0"; pragma experimental ABIEncoderV2; import { EVMConstants } from "solevm-truffle/EVMConstants.sol"; import { EVMAccounts } from "solevm-truffle/EVMAccounts.slb"; import { EVMStorage } from "solevm-truffle/EVMStorage.slb"; import { EVMMemory } from "solevm-truffle/EVMMemory.slb"; import { EVMStack } from "solevm-truffle/EVMStack.slb"; import { EVMLogs } from "solevm-truffle/EVMLogs.slb"; import { EVMUtils } from "solevm-truffle/EVMUtils.slb"; contract EthereumRuntime is EVMConstants { enum CallType { Call, StaticCall, DelegateCall, CallCode } using EVMAccounts for EVMAccounts.Accounts; using EVMAccounts for EVMAccounts.Account; using EVMStorage for EVMStorage.Storage; using EVMMemory for EVMMemory.Memory; using EVMStack for EVMStack.Stack; using EVMLogs for EVMLogs.Logs; // ************* Used as input/output ************* struct TxInput { bool staticExec; // true if STATICCALL (not modifying any state) address from; // tx.from (msg.sender) address to; // tx.to bytes code; // code that will be executed uint value; // tx.value (msg.value) bytes data; // tx.data (calldata) } struct TxInfo { address origin; uint gasPrice; uint gasLimit; uint coinBase; uint blockNumber; uint time; uint difficulty; } struct ExecutionContext { uint[] accounts; // accounts (nonce, balances) bytes accountsCode; // codes, storages uint gasRemaining; uint[] stack; bytes mem; uint pc; } struct Result { uint errno; bytes returnData; } // ************* Only used internally ************* struct Instruction { function(EVM memory) internal pure returns (uint) handler; uint stackIn; uint stackOut; uint gas; } struct EVMInput { uint gas; uint value; bytes data; address caller; address target; TxInfo context; EVMAccounts.Accounts accounts; EVMLogs.Logs logs; Handlers handlers; bool staticExec; EVMMemory.Memory mem; EVMStack.Stack stack; uint pcStart; uint pcEnd; } struct EVMCreateInput { uint gas; uint value; bytes code; address caller; address target; TxInfo context; EVMAccounts.Accounts accounts; EVMLogs.Logs logs; Handlers handlers; } struct Handlers { Instruction[256] ins; function(bytes memory input) internal pure returns (bytes memory ret, uint errno)[9] p; } struct EVM { uint gas; uint value; bytes code; bytes data; bytes lastRet; bytes returnData; uint errno; EVMAccounts.Accounts accounts; EVMLogs.Logs logs; TxInfo context; EVMMemory.Memory mem; EVMStack.Stack stack; uint depth; EVMAccounts.Account caller; EVMAccounts.Account target; uint n; uint pc; bool staticExec; Handlers handlers; } function executeLastStep( bytes memory code, TxInput memory input, TxInfo memory info, ExecutionContext memory context ) public pure returns (bytes32 memory postStateRoot) { EVMInput memory evmInput; evmInput.context = info; evmInput.handlers = _newHandlers(); evmInput.caller = input.from; evmInput.target = input.to; evmInput.value = input.value; evmInput.data = input.data; evmInput.staticExec = input.staticExec; evmInput.pcStart = context.pc; evmInput.pcEnd = context.pc + 1; evmInput.gas = context.gasRemaining; evmInput.mem = EVMMemory.fromArray(context.mem); evmInput.stack = EVMStack.fromArray(context.stack); evmInput.accounts = _accsFromArray(context.accounts, context.accountsCode); // set account code // TODO: fake pc EVMAccounts.Account memory target = evmInput.accounts.get(input.target); target.code = code; EVM memory evm = super._call(evmInput, input.staticExec ? CallType.StaticCall : CallType.Call); postStateRoot = calculateStateRoot(evm); } function calculateStateRoot(EVM memory evm) internal pure returns (bytes32) { uint[] memory accounts; bytes memory accountsCode; (accounts, accountsCode) = evm.accounts.toArray(); uint[] memory stack = evm.stack.toArray(); bytes memory mem = evm.mem.toArray(); return keccak256(abi.encodePacked(accounts, accountsCode, stack, evm)); } function _accsFromArray(uint[] accountsIn, bytes memory accountsCode) internal pure returns (EVMAccounts.Accounts memory accountsOut) { if (accountsIn.length == 0) { return; } uint offset = 0; while (offset < accountsIn.length) { address addr = address(accountsIn[offset]); EVMAccounts.Account memory acc = accountsOut.get(addr); acc.balance = accountsIn[offset + 1]; acc.nonce = uint8(accountsIn[offset + 2]); acc.destroyed = accountsIn[offset + 3] == 1; uint codeSize = accountsIn[offset + 5]; acc.code = new bytes(codeSize); EVMUtils.copy(accountsCode, acc.code, accountsIn[offset + 4], 0, codeSize); // accountsIn[offset + 4] - code offset uint storageSize = accountsIn[offset + 6]; for (uint i = 0; i < storageSize; i++) { acc.stge.store(accountsIn[offset + 7 + 2*i], accountsIn[offset + 8 + 2*i]); } offset += 7 + 2 * storageSize; } } function _call(EVMInput memory evmInput, CallType callType) internal pure returns (EVM memory evm) { evm.context = evmInput.context; evm.handlers = evmInput.handlers; if (evmInput.staticExec) { evm.accounts = evmInput.accounts; evm.logs = evmInput.logs; } else { evm.accounts = evmInput.accounts.copy(); evm.logs = evmInput.logs.copy(); } evm.value = evmInput.value; evm.gas = evmInput.gas; evm.data = evmInput.data; evm.caller = evm.accounts.get(evmInput.caller); // TODO touching accounts. evm.target = evm.accounts.get(evmInput.target); evm.staticExec = evmInput.staticExec; // Transfer value. TODO if callcode is added if (callType != CallType.DelegateCall && evm.value > 0) { if (evm.staticExec) { evm.errno = ERROR_ILLEGAL_WRITE_OPERATION; return; } if (evm.caller.balance < evm.value) { evm.errno = ERROR_INSUFFICIENT_FUNDS; return; } evm.caller.balance -= evm.value; evm.target.balance += evm.value; } if (1 <= evm.target.addr && evm.target.addr <= 8) { (evm.returnData, evm.errno) = evm.handlers.p[uint(evm.target.addr)](evm.data); } else { // If there is no code to run, just continue. TODO if (evm.target.code.length == 0) { return; } evm.code = evm.target.code; if (evmInput.stack.size > 0) { evm.stack = evmInput.stack; } else { evm.stack = EVMStack.newStack(); } if (evmInput.mem.size > 0) { evm.mem = evmInput.mem; } else { evm.mem = EVMMemory.newMemory(); } _run(evm, evmInput.pcStart, evmInput.pcEnd); } } function _create(EVMCreateInput memory evmInput) internal pure returns (EVM memory evm, address addr) { evm.context = evmInput.context; evm.handlers = evmInput.handlers; evm.accounts = evmInput.accounts.copy(); evm.logs = evmInput.logs.copy(); evm.value = evmInput.value; evm.gas = evmInput.gas; evm.caller = evm.accounts.get(evmInput.caller); // Increase the nonce. TODO evm.caller.nonce++; // Transfer value check. TODO if (evm.value > 0) { if (evm.caller.balance < evm.value) { evm.errno = ERROR_INSUFFICIENT_FUNDS; return; } } address newAddress = EVMUtils.newAddress(evm.caller.addr, evm.caller.nonce); EVMAccounts.Account memory newAcc = evm.accounts.get(newAddress); // TODO if (newAcc.nonce != 0) { evm.errno = ERROR_CONTRACT_CREATION_COLLISION; return; } evm.caller.balance -= evm.value; newAcc.balance += evm.value; evm.target = newAcc; evm.code = evmInput.code; evm.stack = EVMStack.newStack(); evm.mem = EVMMemory.newMemory(); _run(evm, 0, 0); // TODO if (evm.errno != NO_ERROR) { return; } if (evm.returnData.length > MAX_CODE_SIZE) { evm.errno = ERROR_MAX_CODE_SIZE_EXCEEDED; return; } newAcc.code = evm.returnData; addr = newAddress; } // solhint-disable-next-line code-complexity, function-max-lines, security/no-assign-params function _run(EVM memory evm, uint pc, uint pcEnd) internal pure { uint pcNext = 0; uint errno = NO_ERROR; bytes memory code = evm.code; if (pcEnd == 0) { pcEnd = code.length; } if (evm.gas > evm.context.gasLimit) { // remaining gas goes below 0, so it is overflowed errno = ERROR_OUT_OF_GAS; } while (errno == NO_ERROR && pc < pcEnd) { uint opcode = uint(code[pc]); Instruction memory ins = evm.handlers.ins[opcode]; if (ins.gas > evm.gas) { errno = ERROR_OUT_OF_GAS; break; } evm.gas -= ins.gas; // Check for violation of static execution. if ( evm.staticExec && (opcode == OP_SSTORE || opcode == OP_CREATE || (OP_LOG0 <= opcode && opcode <= OP_LOG4)) ) { errno = ERROR_ILLEGAL_WRITE_OPERATION; break; } // Check for stack errors if (evm.stack.size < ins.stackIn) { errno = ERROR_STACK_UNDERFLOW; break; } else if (ins.stackOut > ins.stackIn && evm.stack.size + ins.stackOut - ins.stackIn > MAX_STACK_SIZE) { errno = ERROR_STACK_OVERFLOW; break; } if (OP_PUSH1 <= opcode && opcode <= OP_PUSH32) { evm.pc = pc; uint n = opcode - OP_PUSH1 + 1; evm.n = n; errno = ins.handler(evm); pcNext = pc + n + 1; } else if (opcode == OP_JUMP || opcode == OP_JUMPI) { evm.pc = pc; errno = ins.handler(evm); pcNext = evm.pc; } else if (opcode == OP_RETURN || opcode == OP_REVERT || opcode == OP_STOP || opcode == OP_SELFDESTRUCT) { errno = ins.handler(evm); break; } else { if (OP_DUP1 <= opcode && opcode <= OP_DUP16) { evm.n = opcode - OP_DUP1 + 1; errno = ins.handler(evm); } else if (OP_SWAP1 <= opcode && opcode <= OP_SWAP16) { evm.n = opcode - OP_SWAP1 + 1; errno = ins.handler(evm); } else if (OP_LOG0 <= opcode && opcode <= OP_LOG4) { evm.n = opcode - OP_LOG0; errno = ins.handler(evm); } else if (opcode == OP_PC) { evm.pc = pc; errno = ins.handler(evm); } else { errno = ins.handler(evm); } pcNext = pc + 1; } if (errno == NO_ERROR) { pc = pcNext; } } evm.errno = errno; evm.pc = pc; } // ************************* Handlers *************************** // solhint-disable-next-line func-name-mixedcase function handlePreC_ECRECOVER(bytes memory input) internal pure returns (bytes memory ret, uint errno) { uint hash = EVMUtils.toUint(input, 0, 32); uint v = uint8(EVMUtils.toUint(input, 32, 32)); uint r = EVMUtils.toUint(input, 64, 32); uint s = EVMUtils.toUint(input, 96, 32); address result = ecrecover(bytes32(hash), uint8(v), bytes32(r), bytes32(s)); ret = EVMUtils.fromUint(uint(result)); } // solhint-disable-next-line func-name-mixedcase function handlePreC_SHA256(bytes memory input) internal pure returns (bytes memory ret, uint errno) { bytes32 result = sha256(input); ret = EVMUtils.fromUint(uint(result)); } // solhint-disable-next-line func-name-mixedcase function handlePreC_RIPEMD160(bytes memory input) internal pure returns (bytes memory ret, uint errno) { bytes20 result = ripemd160(input); ret = EVMUtils.fromUint(uint(result)); } // solhint-disable-next-line func-name-mixedcase function handlePreC_IDENTITY(bytes memory input) internal pure returns (bytes memory ret, uint errno) { ret = input; } // solhint-disable-next-line func-name-mixedcase function handlePreC_UNIMPLEMENTED(bytes memory) internal pure returns (bytes memory ret, uint errno) { errno = ERROR_PRECOMPILE_NOT_IMPLEMENTED; } // 0x0X // solhint-disable-next-line no-empty-blocks function handleSTOP(EVM memory state) internal pure returns (uint) { } function handleADD(EVM memory state) internal pure returns (uint) { uint a = state.stack.pop(); uint b = state.stack.pop(); uint c; assembly { c := add(a, b) } state.stack.push(c); } function handleMUL(EVM memory state) internal pure returns (uint) { uint a = state.stack.pop(); uint b = state.stack.pop(); uint c; assembly { c := mul(a, b) } state.stack.push(c); } function handleSUB(EVM memory state) internal pure returns (uint) { uint a = state.stack.pop(); uint b = state.stack.pop(); uint c; assembly { c := sub(a, b) } state.stack.push(c); } function handleDIV(EVM memory state) internal pure returns (uint) { uint a = state.stack.pop(); uint b = state.stack.pop(); uint c; assembly { c := div(a, b) } state.stack.push(c); } function handleSDIV(EVM memory state) internal pure returns (uint) { uint a = state.stack.pop(); uint b = state.stack.pop(); uint c; assembly { c := sdiv(a, b) } state.stack.push(c); } function handleMOD(EVM memory state) internal pure returns (uint) { uint a = state.stack.pop(); uint b = state.stack.pop(); uint c; assembly { c := mod(a, b) } state.stack.push(c); } function handleSMOD(EVM memory state) internal pure returns (uint) { uint a = state.stack.pop(); uint b = state.stack.pop(); uint c; assembly { c := smod(a, b) } state.stack.push(c); } function handleADDMOD(EVM memory state) internal pure returns (uint) { uint a = state.stack.pop(); uint b = state.stack.pop(); uint m = state.stack.pop(); uint c; assembly { c := addmod(a, b, m) } state.stack.push(c); } function handleMULMOD(EVM memory state) internal pure returns (uint) { uint a = state.stack.pop(); uint b = state.stack.pop(); uint m = state.stack.pop(); uint c; assembly { c := mulmod(a, b, m) } state.stack.push(c); } function handleEXP(EVM memory state) internal pure returns (uint) { uint a = state.stack.pop(); uint b = state.stack.pop(); uint c; assembly { c := exp(a, b) } state.stack.push(c); } function handleSIGNEXTEND(EVM memory state) internal pure returns (uint) { uint a = state.stack.pop(); uint b = state.stack.pop(); uint c; assembly { c := signextend(a, b) } state.stack.push(c); } function handleSHL(EVM memory state) internal pure returns (uint) { uint a = state.stack.pop(); uint b = state.stack.pop(); uint c; assembly { c := shl(a, b) } state.stack.push(c); } function handleSHR(EVM memory state) internal pure returns (uint) { uint a = state.stack.pop(); uint b = state.stack.pop(); uint c; assembly { c := shr(a, b) } state.stack.push(c); } function handleSAR(EVM memory state) internal pure returns (uint) { uint a = state.stack.pop(); uint b = state.stack.pop(); uint c; assembly { c := sar(a, b) } state.stack.push(c); } // 0x1X function handleLT(EVM memory state) internal pure returns (uint) { uint a = state.stack.pop(); uint b = state.stack.pop(); uint c; assembly { c := lt(a, b) } state.stack.push(c); } function handleGT(EVM memory state) internal pure returns (uint) { uint a = state.stack.pop(); uint b = state.stack.pop(); uint c; assembly { c := gt(a, b) } state.stack.push(c); } function handleSLT(EVM memory state) internal pure returns (uint) { uint a = state.stack.pop(); uint b = state.stack.pop(); uint c; assembly { c := slt(a, b) } state.stack.push(c); } function handleSGT(EVM memory state) internal pure returns (uint) { uint a = state.stack.pop(); uint b = state.stack.pop(); uint c; assembly { c := sgt(a, b) } state.stack.push(c); } function handleEQ(EVM memory state) internal pure returns (uint) { uint a = state.stack.pop(); uint b = state.stack.pop(); uint c; assembly { c := eq(a, b) } state.stack.push(c); } function handleISZERO(EVM memory state) internal pure returns (uint) { uint data = state.stack.pop(); uint res; assembly { res := iszero(data) } state.stack.push(res); } function handleAND(EVM memory state) internal pure returns (uint) { uint a = state.stack.pop(); uint b = state.stack.pop(); uint c; assembly { c := and(a, b) } state.stack.push(c); } function handleOR(EVM memory state) internal pure returns (uint) { uint a = state.stack.pop(); uint b = state.stack.pop(); uint c; assembly { c := or(a, b) } state.stack.push(c); } function handleXOR(EVM memory state) internal pure returns (uint) { uint a = state.stack.pop(); uint b = state.stack.pop(); uint c; assembly { c := xor(a, b) } state.stack.push(c); } function handleNOT(EVM memory state) internal pure returns (uint) { uint data = state.stack.pop(); uint res; assembly { res := not(data) } state.stack.push(res); } function handleBYTE(EVM memory state) internal pure returns (uint) { uint n = state.stack.pop(); uint x = state.stack.pop(); uint b; assembly { b := byte(n, x) } state.stack.push(b); } // 0x2X function handleSHA3(EVM memory state) internal pure returns (uint) { uint mp = state.mem.memUPtr(state.stack.pop()); uint n = state.stack.pop(); uint res; assembly { res := keccak256(mp, n) } state.stack.push(res); } // 0x3X function handleADDRESS(EVM memory state) internal pure returns (uint) { state.stack.push(uint(state.target.addr)); } function handleBALANCE(EVM memory state) internal pure returns (uint) { state.stack.push(state.accounts.get(address(state.stack.pop())).balance); } function handleORIGIN(EVM memory state) internal pure returns (uint) { state.stack.push(uint(state.context.origin)); } function handleCALLER(EVM memory state) internal pure returns (uint) { state.stack.push(uint(state.caller.addr)); } function handleCALLVALUE(EVM memory state) internal pure returns (uint) { state.stack.push(state.value); } function handleCALLDATALOAD(EVM memory state) internal pure returns (uint) { uint addr = state.stack.pop(); bytes memory data = state.data; uint val; // When some or all of the 32 bytes fall outside of the calldata array, // we have to replace those bytes with zeroes. if (addr >= data.length) { val = 0; } else { assembly { val := mload(add(data, add(0x20, addr))) } if (addr + WORD_SIZE > data.length) { val &= ~uint(0) << 8 * (32 - data.length + addr); } } state.stack.push(val); } function handleCALLDATASIZE(EVM memory state) internal pure returns (uint) { state.stack.push(state.data.length); } function handleCALLDATACOPY(EVM memory state) internal pure returns (uint) { uint mAddr = state.stack.pop(); state.mem.storeBytesAndPadWithZeroes( state.data, // dAddr state.stack.pop(), mAddr, // len state.stack.pop() ); } function handleCODESIZE(EVM memory state) internal pure returns (uint) { state.stack.push(state.code.length); } function handleCODECOPY(EVM memory state) internal pure returns (uint) { uint mAddr = state.stack.pop(); uint cAddr = state.stack.pop(); uint len = state.stack.pop(); if (cAddr + len > state.code.length) { return ERROR_INDEX_OOB; } state.mem.storeBytes(state.code, cAddr, mAddr, len); } function handleGASPRICE(EVM memory state) internal pure returns (uint) { state.stack.push(state.context.gasPrice); } function handleEXTCODESIZE(EVM memory state) internal pure returns (uint) { state.stack.push(state.accounts.get(address(state.stack.pop())).code.length); } function handleEXTCODECOPY(EVM memory state) internal pure returns (uint) { bytes memory code = state.accounts.get(address(state.stack.pop())).code; uint mAddr = state.stack.pop(); uint dAddr = state.stack.pop(); uint len = state.stack.pop(); if (dAddr + len > code.length) { return ERROR_INDEX_OOB; } state.mem.storeBytes(code, dAddr, mAddr, len); } function handleRETURNDATASIZE(EVM memory state) internal pure returns (uint) { state.stack.push(state.lastRet.length); } function handleRETURNDATACOPY(EVM memory state) internal pure returns (uint) { uint mAddr = state.stack.pop(); state.mem.storeBytesAndPadWithZeroes( state.lastRet, // rAddr state.stack.pop(), mAddr, // len state.stack.pop() ); } // 0x4X function handleBLOCKHASH(EVM memory state) internal pure returns (uint) { state.stack.pop(); state.stack.push(0); } function handleCOINBASE(EVM memory state) internal pure returns (uint) { state.stack.push(state.context.coinBase); } function handleTIMESTAMP(EVM memory state) internal pure returns (uint) { state.stack.push(state.context.time); } function handleNUMBER(EVM memory state) internal pure returns (uint) { state.stack.push(state.context.blockNumber); } function handleDIFFICULTY(EVM memory state) internal pure returns (uint) { state.stack.push(state.context.difficulty); } function handleGASLIMIT(EVM memory state) internal pure returns (uint) { state.stack.push(state.context.gasLimit); } // 0x5X function handlePOP(EVM memory state) internal pure returns (uint) { state.stack.pop(); } function handleMLOAD(EVM memory state) internal pure returns (uint) { state.stack.push(state.mem.load(state.stack.pop())); } function handleMSTORE(EVM memory state) internal pure returns (uint) { state.mem.store( // addr state.stack.pop(), // val state.stack.pop() ); } function handleMSTORE8(EVM memory state) internal pure returns (uint) { state.mem.store8( // addr state.stack.pop(), // val uint8(state.stack.pop()) ); } function handleSLOAD(EVM memory state) internal pure returns (uint) { state.stack.push(state.target.stge.load(state.stack.pop())); } function handleSSTORE(EVM memory state) internal pure returns (uint) { state.target.stge.store( // addr state.stack.pop(), // val state.stack.pop() ); } function handleJUMP(EVM memory state) internal pure returns (uint) { uint dest = state.stack.pop(); if (dest >= state.code.length || uint(state.code[dest]) != OP_JUMPDEST) { return ERROR_INVALID_JUMP_DESTINATION; } state.pc = dest; } function handleJUMPI(EVM memory state) internal pure returns (uint) { uint dest = state.stack.pop(); uint cnd = state.stack.pop(); if (cnd == 0) { state.pc = state.pc + 1; return; } if (dest >= state.code.length || uint(state.code[dest]) != OP_JUMPDEST) { return ERROR_INVALID_JUMP_DESTINATION; } state.pc = dest; } function handlePC(EVM memory state) internal pure returns (uint) { state.stack.push(state.pc); } function handleMSIZE(EVM memory state) internal pure returns (uint) { state.stack.push(32 * state.mem.size); } function handleGAS(EVM memory state) internal pure returns (uint) { state.stack.push(state.gas); } // solhint-disable-next-line no-empty-blocks function handleJUMPDEST(EVM memory state) internal pure returns (uint) { } // 0x6X, 0x7X function handlePUSH(EVM memory state) internal pure returns (uint) { assert(1 <= state.n && state.n <= 32); if (state.pc + state.n > state.code.length) { return ERROR_INDEX_OOB; } state.stack.push(EVMUtils.toUint(state.code, state.pc + 1, state.n)); } // 0x8X function handleDUP(EVM memory state) internal pure returns (uint) { assert(1 <= state.n && state.n <= 16); state.stack.dup(state.n); } // 0x9X function handleSWAP(EVM memory state) internal pure returns (uint) { assert(1 <= state.n && state.n <= 16); state.stack.swap(state.n); } // 0xaX function handleLOG(EVM memory state) internal pure returns (uint) { EVMLogs.LogEntry memory log; log.account = state.target.addr; log.data = state.mem.toArray( // mAddr state.stack.pop(), // mSize state.stack.pop() ); for (uint i = 0; i < state.n; i++) { log.topics[i] = state.stack.pop(); } state.logs.add(log); } // 0xfX function handleCREATE(EVM memory state) internal pure returns (uint) { assert(!state.staticExec); EVMCreateInput memory input; input.gas = state.gas; input.value = state.stack.pop(); // memPos, size input.code = state.mem.toArray(state.stack.pop(), state.stack.pop()); input.caller = state.target.addr; input.context = state.context; input.accounts = state.accounts; input.logs = state.logs; input.handlers = state.handlers; EVM memory retEvm; address newAddress; (retEvm, newAddress) = _create(input); if (retEvm.errno != NO_ERROR) { state.stack.push(0); } else { state.stack.push(uint(newAddress)); state.accounts = retEvm.accounts; state.caller = state.accounts.get(state.caller.addr); state.target = state.accounts.get(state.target.addr); state.logs = retEvm.logs; } state.gas = retEvm.gas; } function handleCREATE2(EVM memory) internal pure returns (uint) { return ERROR_INSTRUCTION_NOT_SUPPORTED; } function handleCALL(EVM memory state) internal pure returns (uint) { EVMInput memory input; input.gas = state.stack.pop(); input.caller = state.target.addr; input.target = address(state.stack.pop()); input.value = state.stack.pop(); input.data = state.mem.toArray( // inOffset state.stack.pop(), // inSize state.stack.pop() ); uint retOffset = state.stack.pop(); // return offset uint retSize = state.stack.pop(); // return size if (input.gas > state.gas) { return ERROR_OUT_OF_GAS; } input.context = state.context; input.accounts = state.accounts; input.logs = state.logs; input.handlers = state.handlers; input.staticExec = state.staticExec; // solhint-disable-next-line avoid-low-level-calls EVM memory retEvm = _call(input, CallType.Call); if (retEvm.errno != NO_ERROR) { state.stack.push(0); state.lastRet = new bytes(0); } else { state.stack.push(1); state.mem.storeBytesAndPadWithZeroes(retEvm.returnData, 0, retOffset, retSize); state.lastRet = retEvm.returnData; // Update to the new state. state.accounts = retEvm.accounts; state.caller = state.accounts.get(state.caller.addr); state.target = state.accounts.get(state.target.addr); state.logs = retEvm.logs; } state.gas -= input.gas - retEvm.gas; } function handleCALLCODE(EVM memory) internal pure returns (uint) { return ERROR_INSTRUCTION_NOT_SUPPORTED; } function handleRETURN(EVM memory state) internal pure returns (uint) { state.returnData = state.mem.toArray( // start state.stack.pop(), // len state.stack.pop() ); } function handleDELEGATECALL(EVM memory state) internal pure returns (uint) { EVMInput memory input; input.gas = state.stack.pop(); bytes memory oldCode = state.target.code; state.target.code = state.accounts.get(address(state.stack.pop())).code; input.target = state.target.addr; input.data = state.mem.toArray( // inOffset state.stack.pop(), // inSize state.stack.pop() ); uint retOffset = state.stack.pop(); uint retSize = state.stack.pop(); if (input.gas > state.gas) { return ERROR_OUT_OF_GAS; } input.value = state.value; input.caller = state.caller.addr; input.context = state.context; input.accounts = state.accounts; input.logs = state.logs; input.handlers = state.handlers; input.staticExec = state.staticExec; // solhint-disable-next-line avoid-low-level-calls EVM memory retEvm = _call(input, CallType.DelegateCall); if (retEvm.errno != NO_ERROR) { state.stack.push(0); state.lastRet = new bytes(0); } else { state.stack.push(1); state.mem.storeBytesAndPadWithZeroes(retEvm.returnData, 0, retOffset, retSize); state.lastRet = retEvm.returnData; state.accounts = retEvm.accounts; state.caller = state.accounts.get(state.caller.addr); state.target = state.accounts.get(state.target.addr); state.logs = retEvm.logs; } state.target.code = oldCode; state.gas -= input.gas - retEvm.gas; } function handleSTATICCALL(EVM memory state) internal pure returns (uint) { EVMInput memory input; input.gas = state.stack.pop(); input.caller = state.target.addr; input.target = address(state.stack.pop()); input.data = state.mem.toArray( // inOffset state.stack.pop(), // inSize state.stack.pop() ); uint retOffset = state.stack.pop(); uint retSize = state.stack.pop(); if (input.gas > state.gas) { return ERROR_OUT_OF_GAS; } input.context = state.context; input.accounts = state.accounts; input.logs = state.logs; input.handlers = state.handlers; input.staticExec = true; // solhint-disable-next-line avoid-low-level-calls EVM memory retEvm = _call(input, CallType.StaticCall); if (retEvm.errno != NO_ERROR) { state.stack.push(0); state.lastRet = new bytes(0); } else { state.stack.push(1); state.mem.storeBytesAndPadWithZeroes(retEvm.returnData, 0, retOffset, retSize); state.lastRet = retEvm.returnData; } state.gas -= input.gas - retEvm.gas; } function handleREVERT(EVM memory state) internal pure returns (uint) { state.returnData = state.mem.toArray( // start state.stack.pop(), // len state.stack.pop() ); return ERROR_STATE_REVERTED; } function handleINVALID(EVM memory) internal pure returns (uint) { return ERROR_INVALID_OPCODE; } function handleSELFDESTRUCT(EVM memory state) internal pure returns (uint) { uint bal = state.target.balance; state.target.balance = 0; // receiver state.accounts.get(address(state.stack.pop())).balance += bal; state.target.destroyed = true; } // Since reference types can't be constant. // solhint-disable-next-line function-max-lines function _newHandlers() internal pure returns (Handlers memory handlers) { Instruction memory inv = Instruction(handleINVALID, 0, 0, 0); Instruction memory push = Instruction(handlePUSH, 0, 1, GAS_VERYLOW); handlers.ins = [ // 0x0X Instruction(handleSTOP, 0, 0, GAS_ZERO), Instruction(handleADD, 2, 1, GAS_VERYLOW), Instruction(handleMUL, 2, 1, GAS_LOW), Instruction(handleSUB, 2, 1, GAS_VERYLOW), Instruction(handleDIV, 2, 1, GAS_LOW), Instruction(handleSDIV, 2, 1, GAS_LOW), Instruction(handleMOD, 2, 1, GAS_LOW), Instruction(handleSMOD, 2, 1, GAS_LOW), Instruction(handleADDMOD, 3, 1, GAS_MID), Instruction(handleMULMOD, 3, 1, GAS_MID), Instruction(handleEXP, 2, 1, GAS_EXP), Instruction(handleSIGNEXTEND, 0, 0, GAS_LOW), inv, inv, inv, inv, // 0x1X Instruction(handleLT, 2, 1, GAS_VERYLOW), Instruction(handleGT, 2, 1, GAS_VERYLOW), Instruction(handleSLT, 2, 1, GAS_VERYLOW), Instruction(handleSGT, 2, 1, GAS_VERYLOW), Instruction(handleEQ, 2, 1, GAS_VERYLOW), Instruction(handleISZERO, 1, 1, GAS_VERYLOW), Instruction(handleAND, 2, 1, GAS_VERYLOW), Instruction(handleOR, 2, 1, GAS_VERYLOW), Instruction(handleXOR, 2, 1, GAS_VERYLOW), Instruction(handleNOT, 1, 1, GAS_VERYLOW), Instruction(handleBYTE, 2, 1, GAS_VERYLOW), Instruction(handleSHL, 2, 1, GAS_VERYLOW), Instruction(handleSHR, 2, 1, GAS_VERYLOW), Instruction(handleSAR, 2, 1, GAS_VERYLOW), inv, inv, // 0x2X Instruction(handleSHA3, 2, 1, GAS_SHA3), inv, inv, inv, inv, inv, inv, inv, inv, inv, inv, inv, inv, inv, inv, inv, // 0x3X Instruction(handleADDRESS, 0, 1, GAS_BASE), Instruction(handleBALANCE, 1, 1, GAS_BALANCE), Instruction(handleORIGIN, 0, 1, GAS_BASE), Instruction(handleCALLER, 0, 1, GAS_BASE), Instruction(handleCALLVALUE, 0, 1, GAS_BASE), Instruction(handleCALLDATALOAD, 1, 1, GAS_VERYLOW), Instruction(handleCALLDATASIZE, 0, 1, GAS_BASE), Instruction(handleCALLDATACOPY, 3, 0, GAS_VERYLOW), Instruction(handleCODESIZE, 0, 1, GAS_BASE), Instruction(handleCODECOPY, 3, 0, GAS_VERYLOW), Instruction(handleGASPRICE, 0, 1, GAS_BASE), Instruction(handleEXTCODESIZE, 1, 1, GAS_EXTCODE), Instruction(handleEXTCODECOPY, 4, 0, GAS_EXTCODE), Instruction(handleRETURNDATASIZE, 0, 1, GAS_BASE), Instruction(handleRETURNDATACOPY, 3, 0, GAS_VERYLOW), inv, // 0x4X Instruction(handleBLOCKHASH, 1, 1, GAS_BLOCKHASH), Instruction(handleCOINBASE, 0, 1, GAS_BASE), Instruction(handleTIMESTAMP, 0, 1, GAS_BASE), Instruction(handleNUMBER, 0, 1, GAS_BASE), Instruction(handleDIFFICULTY, 0, 1, GAS_BASE), Instruction(handleGASLIMIT, 0, 1, GAS_BASE), inv, inv, inv, inv, inv, inv, inv, inv, inv, inv, // 0x5X Instruction(handlePOP, 1, 0, GAS_BASE), Instruction(handleMLOAD, 1, 1, GAS_VERYLOW), Instruction(handleMSTORE, 2, 0, GAS_VERYLOW), Instruction(handleMSTORE8, 2, 0, GAS_VERYLOW), Instruction(handleSLOAD, 1, 1, GAS_SLOAD), Instruction(handleSSTORE, 2, 0, GAS_ZERO), Instruction(handleJUMP, 1, 0, GAS_MID), Instruction(handleJUMPI, 2, 0, GAS_HIGH), Instruction(handlePC, 0, 1, GAS_BASE), Instruction(handleMSIZE, 0, 1, GAS_BASE), Instruction(handleGAS, 0, 1, GAS_BASE), Instruction(handleJUMPDEST, 0, 0, GAS_JUMPDEST), inv, inv, inv, inv, // 0x6X push, push, push, push, push, push, push, push, push, push, push, push, push, push, push, push, // 0x7X push, push, push, push, push, push, push, push, push, push, push, push, push, push, push, push, // 0x8X Instruction(handleDUP, 1, 2, GAS_VERYLOW), Instruction(handleDUP, 2, 3, GAS_VERYLOW), Instruction(handleDUP, 3, 4, GAS_VERYLOW), Instruction(handleDUP, 4, 5, GAS_VERYLOW), Instruction(handleDUP, 5, 6, GAS_VERYLOW), Instruction(handleDUP, 6, 7, GAS_VERYLOW), Instruction(handleDUP, 7, 8, GAS_VERYLOW), Instruction(handleDUP, 8, 9, GAS_VERYLOW), Instruction(handleDUP, 9, 10, GAS_VERYLOW), Instruction(handleDUP, 10, 11, GAS_VERYLOW), Instruction(handleDUP, 11, 12, GAS_VERYLOW), Instruction(handleDUP, 12, 13, GAS_VERYLOW), Instruction(handleDUP, 13, 14, GAS_VERYLOW), Instruction(handleDUP, 14, 15, GAS_VERYLOW), Instruction(handleDUP, 15, 16, GAS_VERYLOW), Instruction(handleDUP, 16, 17, GAS_VERYLOW), // 0x9X Instruction(handleSWAP, 2, 2, GAS_VERYLOW), Instruction(handleSWAP, 3, 3, GAS_VERYLOW), Instruction(handleSWAP, 4, 4, GAS_VERYLOW), Instruction(handleSWAP, 5, 5, GAS_VERYLOW), Instruction(handleSWAP, 6, 6, GAS_VERYLOW), Instruction(handleSWAP, 7, 7, GAS_VERYLOW), Instruction(handleSWAP, 8, 8, GAS_VERYLOW), Instruction(handleSWAP, 9, 9, GAS_VERYLOW), Instruction(handleSWAP, 10, 10, GAS_VERYLOW), Instruction(handleSWAP, 11, 11, GAS_VERYLOW), Instruction(handleSWAP, 12, 12, GAS_VERYLOW), Instruction(handleSWAP, 13, 13, GAS_VERYLOW), Instruction(handleSWAP, 14, 14, GAS_VERYLOW), Instruction(handleSWAP, 15, 15, GAS_VERYLOW), Instruction(handleSWAP, 16, 16, GAS_VERYLOW), Instruction(handleSWAP, 17, 17, GAS_VERYLOW), // 0xaX Instruction(handleLOG, 2, 0, GAS_LOG), Instruction(handleLOG, 3, 0, GAS_LOG + GAS_LOGTOPIC), Instruction(handleLOG, 4, 0, GAS_LOG + 2 * GAS_LOGTOPIC), Instruction(handleLOG, 5, 0, GAS_LOG + 3 * GAS_LOGTOPIC), Instruction(handleLOG, 6, 0, GAS_LOG + 4 * GAS_LOGTOPIC), inv, inv, inv, inv, inv, inv, inv, inv, inv, inv, inv, // 0xbX inv, inv, inv, inv, inv, inv, inv, inv, inv, inv, inv, inv, inv, inv, inv, inv, // 0xcX inv, inv, inv, inv, inv, inv, inv, inv, inv, inv, inv, inv, inv, inv, inv, inv, // 0xdX inv, inv, inv, inv, inv, inv, inv, inv, inv, inv, inv, inv, inv, inv, inv, inv, // 0xeX inv, inv, inv, inv, inv, inv, inv, inv, inv, inv, inv, inv, inv, inv, inv, inv, // 0xfX Instruction(handleCREATE, 3, 1, GAS_CREATE), Instruction(handleCALL, 7, 1, GAS_CALL), Instruction(handleCALLCODE, 7, 1, GAS_CALL), Instruction(handleRETURN, 2, 0, GAS_ZERO), Instruction(handleDELEGATECALL, 6, 1, GAS_CALL), inv, inv, inv, inv, inv, Instruction(handleSTATICCALL, 6, 1, GAS_CALL), inv, inv, Instruction(handleREVERT, 2, 0, GAS_ZERO), inv, Instruction(handleSELFDESTRUCT, 1, 0, GAS_SELFDESTRUCT) ]; handlers.p[1] = handlePreC_ECRECOVER; handlers.p[2] = handlePreC_SHA256; handlers.p[3] = handlePreC_RIPEMD160; handlers.p[4] = handlePreC_IDENTITY; handlers.p[5] = handlePreC_UNIMPLEMENTED; handlers.p[6] = handlePreC_UNIMPLEMENTED; handlers.p[7] = handlePreC_UNIMPLEMENTED; handlers.p[8] = handlePreC_UNIMPLEMENTED; } }
************************* Handlers *************************** solhint-disable-next-line func-name-mixedcase
function handlePreC_ECRECOVER(bytes memory input) internal pure returns (bytes memory ret, uint errno) { uint hash = EVMUtils.toUint(input, 0, 32); uint v = uint8(EVMUtils.toUint(input, 32, 32)); uint r = EVMUtils.toUint(input, 64, 32); uint s = EVMUtils.toUint(input, 96, 32); address result = ecrecover(bytes32(hash), uint8(v), bytes32(r), bytes32(s)); ret = EVMUtils.fromUint(uint(result)); }
5,515,973
[ 1, 6919, 225, 3704, 11317, 17, 8394, 17, 4285, 17, 1369, 1326, 17, 529, 17, 19562, 3593, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1640, 1386, 39, 67, 41, 5458, 3865, 2204, 12, 3890, 3778, 810, 13, 2713, 16618, 1135, 261, 3890, 3778, 325, 16, 2254, 8402, 13, 288, 203, 3639, 2254, 1651, 273, 512, 7397, 1989, 18, 869, 5487, 12, 2630, 16, 374, 16, 3847, 1769, 203, 3639, 2254, 331, 273, 2254, 28, 12, 41, 7397, 1989, 18, 869, 5487, 12, 2630, 16, 3847, 16, 3847, 10019, 203, 3639, 2254, 436, 273, 512, 7397, 1989, 18, 869, 5487, 12, 2630, 16, 5178, 16, 3847, 1769, 203, 3639, 2254, 272, 273, 512, 7397, 1989, 18, 869, 5487, 12, 2630, 16, 19332, 16, 3847, 1769, 203, 3639, 1758, 563, 273, 425, 1793, 3165, 12, 3890, 1578, 12, 2816, 3631, 2254, 28, 12, 90, 3631, 1731, 1578, 12, 86, 3631, 1731, 1578, 12, 87, 10019, 203, 3639, 325, 273, 512, 7397, 1989, 18, 2080, 5487, 12, 11890, 12, 2088, 10019, 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 ]
pragma solidity ^0.4.19; /* Interface for ERC20 Tokens */ contract Token { bytes32 public standard; bytes32 public name; bytes32 public symbol; uint256 public totalSupply; uint8 public decimals; bool public allowTransactions; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; function transfer(address _to, uint256 _value) returns (bool success); function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool success); } // The DMEX base Contract contract Exchange { function assert(bool assertion) { if (!assertion) throw; } // Safe Multiply Function - prevents integer overflow function safeMul(uint a, uint b) returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } // Safe Subtraction Function - prevents integer overflow function safeSub(uint a, uint b) returns (uint) { assert(b <= a); return a - b; } // Safe Addition Function - prevents integer overflow function safeAdd(uint a, uint b) returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } address public owner; // holds the address of the contract owner mapping (address => bool) public admins; // mapping of admin addresses mapping (address => bool) public futuresContracts; // mapping of connected futures contracts mapping (address => uint256) public futuresContractsAddedBlock; // mapping of connected futures contracts and connection block numbers event SetFuturesContract(address futuresContract, bool isFuturesContract); // Event fired when the owner of the contract is changed event SetOwner(address indexed previousOwner, address indexed newOwner); // Allows only the owner of the contract to execute the function modifier onlyOwner { assert(msg.sender == owner); _; } // Changes the owner of the contract function setOwner(address newOwner) onlyOwner { SetOwner(owner, newOwner); owner = newOwner; } // Owner getter function function getOwner() returns (address out) { return owner; } // Adds or disables an admin account function setAdmin(address admin, bool isAdmin) onlyOwner { admins[admin] = isAdmin; } // Adds or disables a futuresContract address function setFuturesContract(address futuresContract, bool isFuturesContract) onlyOwner { futuresContracts[futuresContract] = isFuturesContract; if (fistFuturesContract == address(0)) { fistFuturesContract = futuresContract; } futuresContractsAddedBlock[futuresContract] = block.number; emit SetFuturesContract(futuresContract, isFuturesContract); } // Allows for admins only to call the function modifier onlyAdmin { if (msg.sender != owner && !admins[msg.sender]) throw; _; } // Allows for futures contracts only to call the function modifier onlyFuturesContract { if (!futuresContracts[msg.sender]) throw; _; } function() external { throw; } //mapping (address => mapping (address => uint256)) public tokens; // mapping of token addresses to mapping of balances // tokens[token][user] //mapping (address => mapping (address => uint256)) public reserve; // mapping of token addresses to mapping of reserved balances // reserve[token][user] mapping (address => mapping (address => uint256)) public balances; // mapping of token addresses to mapping of balances and reserve (bitwise compressed) // balances[token][user] mapping (address => uint256) public lastActiveTransaction; // mapping of user addresses to last transaction block mapping (bytes32 => uint256) public orderFills; // mapping of orders to filled qunatity mapping (address => mapping (address => bool)) public userAllowedFuturesContracts; // mapping of allowed futures smart contracts per user mapping (address => uint256) public userFirstDeposits; // mapping of user addresses and block number of first deposit address public feeAccount; // the account that receives the trading fees address public EtmTokenAddress; // the address of the EtherMium token address public fistFuturesContract; // 0x if there are no futures contracts set yet uint256 public inactivityReleasePeriod; // period in blocks before a user can use the withdraw() function mapping (bytes32 => bool) public withdrawn; // mapping of withdraw requests, makes sure the same withdrawal is not executed twice uint256 public makerFee; // maker fee in percent expressed as a fraction of 1 ether (0.1 ETH = 10%) uint256 public takerFee; // taker fee in percent expressed as a fraction of 1 ether (0.1 ETH = 10%) enum Errors { INVLID_PRICE, // Order prices don't match INVLID_SIGNATURE, // Signature is invalid TOKENS_DONT_MATCH, // Maker/taker tokens don't match ORDER_ALREADY_FILLED, // Order was already filled GAS_TOO_HIGH // Too high gas fee } // Trade event fired when a trade is executed event Trade( address takerTokenBuy, uint256 takerAmountBuy, address takerTokenSell, uint256 takerAmountSell, address maker, address indexed taker, uint256 makerFee, uint256 takerFee, uint256 makerAmountTaken, uint256 takerAmountTaken, bytes32 indexed makerOrderHash, bytes32 indexed takerOrderHash ); // Deposit event fired when a deposit took place event Deposit(address indexed token, address indexed user, uint256 amount, uint256 balance); // Withdraw event fired when a withdrawal was executed event Withdraw(address indexed token, address indexed user, uint256 amount, uint256 balance, uint256 withdrawFee); event WithdrawTo(address indexed token, address indexed to, address indexed from, uint256 amount, uint256 balance, uint256 withdrawFee); // Fee change event event FeeChange(uint256 indexed makerFee, uint256 indexed takerFee); // Log event, logs errors in contract execution (used for debugging) event LogError(uint8 indexed errorId, bytes32 indexed makerOrderHash, bytes32 indexed takerOrderHash); event LogUint(uint8 id, uint256 value); event LogBool(uint8 id, bool value); event LogAddress(uint8 id, address value); // Change inactivity release period event event InactivityReleasePeriodChange(uint256 value); // Order cancelation event event CancelOrder( bytes32 indexed cancelHash, bytes32 indexed orderHash, address indexed user, address tokenSell, uint256 amountSell, uint256 cancelFee ); // Sets the inactivity period before a user can withdraw funds manually function setInactivityReleasePeriod(uint256 expiry) onlyOwner returns (bool success) { if (expiry > 1000000) throw; inactivityReleasePeriod = expiry; emit InactivityReleasePeriodChange(expiry); return true; } // Constructor function, initializes the contract and sets the core variables function Exchange(address feeAccount_, uint256 makerFee_, uint256 takerFee_, uint256 inactivityReleasePeriod_) { owner = msg.sender; feeAccount = feeAccount_; inactivityReleasePeriod = inactivityReleasePeriod_; makerFee = makerFee_; takerFee = takerFee_; } // Changes the fees function setFees(uint256 makerFee_, uint256 takerFee_) onlyOwner { require(makerFee_ < 10 finney && takerFee_ < 10 finney); // The fees cannot be set higher then 1% makerFee = makerFee_; takerFee = takerFee_; emit FeeChange(makerFee, takerFee); } function updateBalanceAndReserve (address token, address user, uint256 balance, uint256 reserve) private { uint256 character = uint256(balance); character |= reserve<<128; balances[token][user] = character; } function updateBalance (address token, address user, uint256 balance) private returns (bool) { uint256 character = uint256(balance); character |= getReserve(token, user)<<128; balances[token][user] = character; return true; } function updateReserve (address token, address user, uint256 reserve) private { uint256 character = uint256(balanceOf(token, user)); character |= reserve<<128; balances[token][user] = character; } function decodeBalanceAndReserve (address token, address user) returns (uint256[2]) { uint256 character = balances[token][user]; uint256 balance = uint256(uint128(character)); uint256 reserve = uint256(uint128(character>>128)); return [balance, reserve]; } function futuresContractAllowed (address futuresContract, address user) returns (bool) { if (fistFuturesContract == futuresContract) return true; if (userAllowedFuturesContracts[user][futuresContract] == true) return true; if (futuresContractsAddedBlock[futuresContract] < userFirstDeposits[user]) return true; return false; } // Returns the balance of a specific token for a specific user function balanceOf(address token, address user) view returns (uint256) { //return tokens[token][user]; return decodeBalanceAndReserve(token, user)[0]; } // Returns the reserved amound of token for user function getReserve(address token, address user) public view returns (uint256) { //return reserve[token][user]; return decodeBalanceAndReserve(token, user)[1]; } // Sets reserved amount for specific token and user (can only be called by futures contract) function setReserve(address token, address user, uint256 amount) onlyFuturesContract returns (bool success) { if (!futuresContractAllowed(msg.sender, user)) throw; if (availableBalanceOf(token, user) < amount) throw; updateReserve(token, user, amount); return true; } // Updates user balance (only can be used by futures contract) function setBalance(address token, address user, uint256 amount) onlyFuturesContract returns (bool success) { if (!futuresContractAllowed(msg.sender, user)) throw; updateBalance(token, user, amount); return true; } function subBalanceAddReserve(address token, address user, uint256 subBalance, uint256 addReserve) onlyFuturesContract returns (bool) { if (!futuresContractAllowed(msg.sender, user)) throw; updateBalanceAndReserve(token, user, safeSub(balanceOf(token, user), subBalance), safeAdd(getReserve(token, user), addReserve)); } function addBalanceSubReserve(address token, address user, uint256 addBalance, uint256 subReserve) onlyFuturesContract returns (bool) { if (!futuresContractAllowed(msg.sender, user)) throw; updateBalanceAndReserve(token, user, safeAdd(balanceOf(token, user), addBalance), safeSub(getReserve(token, user), subReserve)); } function subBalanceSubReserve(address token, address user, uint256 subBalance, uint256 subReserve) onlyFuturesContract returns (bool) { if (!futuresContractAllowed(msg.sender, user)) throw; updateBalanceAndReserve(token, user, safeSub(balanceOf(token, user), subBalance), safeSub(getReserve(token, user), subReserve)); } // Returns the available balance of a specific token for a specific user function availableBalanceOf(address token, address user) view returns (uint256) { return safeSub(balanceOf(token, user), getReserve(token, user)); } // Returns the inactivity release perios function getInactivityReleasePeriod() view returns (uint256) { return inactivityReleasePeriod; } // Increases the user balance function addBalance(address token, address user, uint256 amount) private { updateBalance(token, user, safeAdd(balanceOf(token, user), amount)); } // Decreases user balance function subBalance(address token, address user, uint256 amount) private { if (availableBalanceOf(token, user) < amount) throw; updateBalance(token, user, safeSub(balanceOf(token, user), amount)); } // Deposit ETH to contract function deposit() payable { //tokens[address(0)][msg.sender] = safeAdd(tokens[address(0)][msg.sender], msg.value); // adds the deposited amount to user balance addBalance(address(0), msg.sender, msg.value); // adds the deposited amount to user balance if (userFirstDeposits[msg.sender] == 0) userFirstDeposits[msg.sender] = block.number; lastActiveTransaction[msg.sender] = block.number; // sets the last activity block for the user emit Deposit(address(0), msg.sender, msg.value, balanceOf(address(0), msg.sender)); // fires the deposit event } // Deposit token to contract function depositToken(address token, uint128 amount) { //tokens[token][msg.sender] = safeAdd(tokens[token][msg.sender], amount); // adds the deposited amount to user balance //if (amount != uint128(amount) || safeAdd(amount, balanceOf(token, msg.sender)) != uint128(amount)) throw; addBalance(token, msg.sender, amount); // adds the deposited amount to user balance if (userFirstDeposits[msg.sender] == 0) userFirstDeposits[msg.sender] = block.number; lastActiveTransaction[msg.sender] = block.number; // sets the last activity block for the user if (!Token(token).transferFrom(msg.sender, this, amount)) throw; // attempts to transfer the token to this contract, if fails throws an error emit Deposit(token, msg.sender, amount, balanceOf(token, msg.sender)); // fires the deposit event } function withdraw(address token, uint256 amount) returns (bool success) { //if (safeSub(block.number, lastActiveTransaction[msg.sender]) < inactivityReleasePeriod) throw; // checks if the inactivity period has passed //if (tokens[token][msg.sender] < amount) throw; // checks that user has enough balance if (availableBalanceOf(token, msg.sender) < amount) throw; //tokens[token][msg.sender] = safeSub(tokens[token][msg.sender], amount); subBalance(token, msg.sender, amount); // subtracts the withdrawed amount from user balance if (token == address(0)) { // checks if withdrawal is a token or ETH, ETH has address 0x00000... if (!msg.sender.send(amount)) throw; // send ETH } else { if (!Token(token).transfer(msg.sender, amount)) throw; // Send token } emit Withdraw(token, msg.sender, amount, balanceOf(token, msg.sender), 0); // fires the Withdraw event } function userAllowFuturesContract(address futuresContract) { if (!futuresContracts[futuresContract]) throw; userAllowedFuturesContracts[msg.sender][futuresContract] = true; } // Withdrawal function used by the server to execute withdrawals function adminWithdraw( address token, // the address of the token to be withdrawn uint256 amount, // the amount to be withdrawn address user, // address of the user uint256 nonce, // nonce to make the request unique uint8 v, // part of user signature bytes32 r, // part of user signature bytes32 s, // part of user signature uint256 feeWithdrawal // the transaction gas fee that will be deducted from the user balance ) onlyAdmin returns (bool success) { bytes32 hash = keccak256(this, token, amount, user, nonce); // creates the hash for the withdrawal request if (withdrawn[hash]) throw; // checks if the withdrawal was already executed, if true, throws an error withdrawn[hash] = true; // sets the withdrawal as executed if (ecrecover(keccak256("\x19Ethereum Signed Message:\n32", hash), v, r, s) != user) throw; // checks that the provided signature is valid if (feeWithdrawal > 50 finney) feeWithdrawal = 50 finney; // checks that the gas fee is not higher than 0.05 ETH //if (tokens[token][user] < amount) throw; // checks that user has enough balance if (availableBalanceOf(token, user) < amount) throw; // checks that user has enough balance //tokens[token][user] = safeSub(tokens[token][user], amount); // subtracts the withdrawal amount from the user balance subBalance(token, user, amount); // subtracts the withdrawal amount from the user balance //tokens[address(0)][user] = safeSub(tokens[address(0x0)][user], feeWithdrawal); // subtracts the gas fee from the user ETH balance subBalance(address(0), user, feeWithdrawal); // subtracts the gas fee from the user ETH balance //tokens[address(0)][feeAccount] = safeAdd(tokens[address(0)][feeAccount], feeWithdrawal); // moves the gas fee to the feeAccount addBalance(address(0), feeAccount, feeWithdrawal); // moves the gas fee to the feeAccount if (token == address(0)) { // checks if the withdrawal is in ETH or Tokens if (!user.send(amount)) throw; // sends ETH } else { if (!Token(token).transfer(user, amount)) throw; // sends tokens } lastActiveTransaction[user] = block.number; // sets last user activity block emit Withdraw(token, user, amount, balanceOf(token, user), feeWithdrawal); // fires the withdraw event } function batchAdminWithdraw( address[] token, // the address of the token to be withdrawn uint256[] amount, // the amount to be withdrawn address[] user, // address of the user uint256[] nonce, // nonce to make the request unique uint8[] v, // part of user signature bytes32[] r, // part of user signature bytes32[] s, // part of user signature uint256[] feeWithdrawal // the transaction gas fee that will be deducted from the user balance ) onlyAdmin { for (uint i = 0; i < amount.length; i++) { adminWithdraw( token[i], amount[i], user[i], nonce[i], v[i], r[i], s[i], feeWithdrawal[i] ); } } function getMakerTakerBalances(address token, address maker, address taker) view returns (uint256[4]) { return [ balanceOf(token, maker), balanceOf(token, taker), getReserve(token, maker), getReserve(token, taker) ]; } // Structure that holds order values, used inside the trade() function struct OrderPair { uint256 makerAmountBuy; // amount being bought by the maker uint256 makerAmountSell; // amount being sold by the maker uint256 makerNonce; // maker order nonce, makes the order unique uint256 takerAmountBuy; // amount being bought by the taker uint256 takerAmountSell; // amount being sold by the taker uint256 takerNonce; // taker order nonce uint256 takerGasFee; // taker gas fee, taker pays the gas uint256 takerIsBuying; // true/false taker is the buyer address makerTokenBuy; // token bought by the maker address makerTokenSell; // token sold by the maker address maker; // address of the maker address takerTokenBuy; // token bought by the taker address takerTokenSell; // token sold by the taker address taker; // address of the taker bytes32 makerOrderHash; // hash of the maker order bytes32 takerOrderHash; // has of the taker order } // Structure that holds trade values, used inside the trade() function struct TradeValues { uint256 qty; // amount to be trade uint256 invQty; // amount to be traded in the opposite token uint256 makerAmountTaken; // final amount taken by the maker uint256 takerAmountTaken; // final amount taken by the taker } // Trades balances between user accounts function trade( uint8[2] v, bytes32[4] rs, uint256[8] tradeValues, address[6] tradeAddresses ) onlyAdmin returns (uint filledTakerTokenAmount) { /* tradeValues [0] makerAmountBuy [1] makerAmountSell [2] makerNonce [3] takerAmountBuy [4] takerAmountSell [5] takerNonce [6] takerGasFee [7] takerIsBuying tradeAddresses [0] makerTokenBuy [1] makerTokenSell [2] maker [3] takerTokenBuy [4] takerTokenSell [5] taker */ OrderPair memory t = OrderPair({ makerAmountBuy : tradeValues[0], makerAmountSell : tradeValues[1], makerNonce : tradeValues[2], takerAmountBuy : tradeValues[3], takerAmountSell : tradeValues[4], takerNonce : tradeValues[5], takerGasFee : tradeValues[6], takerIsBuying : tradeValues[7], makerTokenBuy : tradeAddresses[0], makerTokenSell : tradeAddresses[1], maker : tradeAddresses[2], takerTokenBuy : tradeAddresses[3], takerTokenSell : tradeAddresses[4], taker : tradeAddresses[5], // tokenBuy amountBuy tokenSell amountSell nonce user makerOrderHash : keccak256(this, tradeAddresses[0], tradeValues[0], tradeAddresses[1], tradeValues[1], tradeValues[2], tradeAddresses[2]), takerOrderHash : keccak256(this, tradeAddresses[3], tradeValues[3], tradeAddresses[4], tradeValues[4], tradeValues[5], tradeAddresses[5]) }); // Checks the signature for the maker order if (ecrecover(keccak256("\x19Ethereum Signed Message:\n32", t.makerOrderHash), v[0], rs[0], rs[1]) != t.maker) { emit LogError(uint8(Errors.INVLID_SIGNATURE), t.makerOrderHash, t.takerOrderHash); return 0; } // Checks the signature for the taker order if (ecrecover(keccak256("\x19Ethereum Signed Message:\n32", t.takerOrderHash), v[1], rs[2], rs[3]) != t.taker) { emit LogError(uint8(Errors.INVLID_SIGNATURE), t.makerOrderHash, t.takerOrderHash); return 0; } // Checks that orders trade the right tokens if (t.makerTokenBuy != t.takerTokenSell || t.makerTokenSell != t.takerTokenBuy) { emit LogError(uint8(Errors.TOKENS_DONT_MATCH), t.makerOrderHash, t.takerOrderHash); return 0; } // tokens don't match // Cheks that gas fee is not higher than 10% if (t.takerGasFee > 100 finney) { emit LogError(uint8(Errors.GAS_TOO_HIGH), t.makerOrderHash, t.takerOrderHash); return 0; } // takerGasFee too high // Checks that the prices match. // Taker always pays the maker price. This part checks that the taker price is as good or better than the maker price if (!( (t.takerIsBuying == 0 && safeMul(t.makerAmountSell, 1 ether) / t.makerAmountBuy >= safeMul(t.takerAmountBuy, 1 ether) / t.takerAmountSell) || (t.takerIsBuying > 0 && safeMul(t.makerAmountBuy, 1 ether) / t.makerAmountSell <= safeMul(t.takerAmountSell, 1 ether) / t.takerAmountBuy) )) { emit LogError(uint8(Errors.INVLID_PRICE), t.makerOrderHash, t.takerOrderHash); return 0; // prices don't match } // Initializing trade values structure TradeValues memory tv = TradeValues({ qty : 0, invQty : 0, makerAmountTaken : 0, takerAmountTaken : 0 }); // maker buy, taker sell if (t.takerIsBuying == 0) { // traded quantity is the smallest quantity between the maker and the taker, takes into account amounts already filled on the orders tv.qty = min(safeSub(t.makerAmountBuy, orderFills[t.makerOrderHash]), safeSub(t.takerAmountSell, safeMul(orderFills[t.takerOrderHash], t.takerAmountSell) / t.takerAmountBuy)); if (tv.qty == 0) { // order was already filled emit LogError(uint8(Errors.ORDER_ALREADY_FILLED), t.makerOrderHash, t.takerOrderHash); return 0; } // the traded quantity in opposite token terms tv.invQty = safeMul(tv.qty, t.makerAmountSell) / t.makerAmountBuy; // take fee from Token balance tv.makerAmountTaken = safeSub(tv.qty, safeMul(tv.qty, makerFee) / (1 ether)); // net amount received by maker, excludes maker fee //tokens[t.makerTokenBuy][feeAccount] = safeAdd(tokens[t.makerTokenBuy][feeAccount], safeMul(tv.qty, makerFee) / (1 ether)); // add maker fee to feeAccount addBalance(t.makerTokenBuy, feeAccount, safeMul(tv.qty, makerFee) / (1 ether)); // add maker fee to feeAccount // take fee from Token balance tv.takerAmountTaken = safeSub(safeSub(tv.invQty, safeMul(tv.invQty, takerFee) / (1 ether)), safeMul(tv.invQty, t.takerGasFee) / (1 ether)); // amount taken from taker minus taker fee //tokens[t.takerTokenBuy][feeAccount] = safeAdd(tokens[t.takerTokenBuy][feeAccount], safeAdd(safeMul(tv.invQty, takerFee) / (1 ether), safeMul(tv.invQty, t.takerGasFee) / (1 ether))); // add taker fee to feeAccount addBalance(t.takerTokenBuy, feeAccount, safeAdd(safeMul(tv.invQty, takerFee) / (1 ether), safeMul(tv.invQty, t.takerGasFee) / (1 ether))); // add taker fee to feeAccount //tokens[t.makerTokenSell][t.maker] = safeSub(tokens[t.makerTokenSell][t.maker], tv.invQty); // subtract sold token amount from maker balance subBalance(t.makerTokenSell, t.maker, tv.invQty); // subtract sold token amount from maker balance //tokens[t.makerTokenBuy][t.maker] = safeAdd(tokens[t.makerTokenBuy][t.maker], tv.makerAmountTaken); // add bought token amount to maker addBalance(t.makerTokenBuy, t.maker, tv.makerAmountTaken); // add bought token amount to maker //tokens[t.makerTokenBuy][tv.makerReferrer] = safeAdd(tokens[t.makerTokenBuy][tv.makerReferrer], safeMul(tv.qty, makerAffiliateFee) / (1 ether)); // add affiliate commission to maker affiliate balance //tokens[t.takerTokenSell][t.taker] = safeSub(tokens[t.takerTokenSell][t.taker], tv.qty); // subtract the sold token amount from taker subBalance(t.takerTokenSell, t.taker, tv.qty); // subtract the sold token amount from taker //tokens[t.takerTokenBuy][t.taker] = safeAdd(tokens[t.takerTokenBuy][t.taker], tv.takerAmountTaken); // amount received by taker, excludes taker fee //tokens[t.takerTokenBuy][tv.takerReferrer] = safeAdd(tokens[t.takerTokenBuy][tv.takerReferrer], safeMul(tv.invQty, takerAffiliateFee) / (1 ether)); // add affiliate commission to taker affiliate balance addBalance(t.takerTokenBuy, t.taker, tv.takerAmountTaken); // amount received by taker, excludes taker fee orderFills[t.makerOrderHash] = safeAdd(orderFills[t.makerOrderHash], tv.qty); // increase the maker order filled amount orderFills[t.takerOrderHash] = safeAdd(orderFills[t.takerOrderHash], safeMul(tv.qty, t.takerAmountBuy) / t.takerAmountSell); // increase the taker order filled amount lastActiveTransaction[t.maker] = block.number; // set last activity block number for maker lastActiveTransaction[t.taker] = block.number; // set last activity block number for taker // fire Trade event emit Trade( t.takerTokenBuy, tv.qty, t.takerTokenSell, tv.invQty, t.maker, t.taker, makerFee, takerFee, tv.makerAmountTaken , tv.takerAmountTaken, t.makerOrderHash, t.takerOrderHash ); return tv.qty; } // maker sell, taker buy else { // traded quantity is the smallest quantity between the maker and the taker, takes into account amounts already filled on the orders tv.qty = min(safeSub(t.makerAmountSell, safeMul(orderFills[t.makerOrderHash], t.makerAmountSell) / t.makerAmountBuy), safeSub(t.takerAmountBuy, orderFills[t.takerOrderHash])); if (tv.qty == 0) { // order was already filled emit LogError(uint8(Errors.ORDER_ALREADY_FILLED), t.makerOrderHash, t.takerOrderHash); return 0; } // the traded quantity in opposite token terms tv.invQty = safeMul(tv.qty, t.makerAmountBuy) / t.makerAmountSell; // take fee from ETH balance tv.makerAmountTaken = safeSub(tv.invQty, safeMul(tv.invQty, makerFee) / (1 ether)); // net amount received by maker, excludes maker fee //tokens[t.makerTokenBuy][feeAccount] = safeAdd(tokens[t.makerTokenBuy][feeAccount], safeMul(tv.invQty, makerFee) / (1 ether)); // add maker fee to feeAccount addBalance(t.makerTokenBuy, feeAccount, safeMul(tv.invQty, makerFee) / (1 ether)); // add maker fee to feeAccount // process fees for taker // take fee from ETH balance tv.takerAmountTaken = safeSub(safeSub(tv.qty, safeMul(tv.qty, takerFee) / (1 ether)), safeMul(tv.qty, t.takerGasFee) / (1 ether)); // amount taken from taker minus taker fee //tokens[t.takerTokenBuy][feeAccount] = safeAdd(tokens[t.takerTokenBuy][feeAccount], safeAdd(safeMul(tv.qty, takerFee) / (1 ether), safeMul(tv.qty, t.takerGasFee) / (1 ether))); // add taker fee to feeAccount addBalance(t.takerTokenBuy, feeAccount, safeAdd(safeMul(tv.qty, takerFee) / (1 ether), safeMul(tv.qty, t.takerGasFee) / (1 ether))); // add taker fee to feeAccount //tokens[t.makerTokenSell][t.maker] = safeSub(tokens[t.makerTokenSell][t.maker], tv.qty); // subtract sold token amount from maker balance subBalance(t.makerTokenSell, t.maker, tv.qty); // subtract sold token amount from maker balance //tv.makerAmountTaken = safeSub(tv.invQty, safeMul(tv.invQty, makerFee) / (1 ether)); // net amount received by maker, excludes maker fee //tokens[t.makerTokenBuy][t.maker] = safeAdd(tokens[t.makerTokenBuy][t.maker], tv.makerAmountTaken); // add bought token amount to maker addBalance(t.makerTokenBuy, t.maker, tv.makerAmountTaken); // add bought token amount to maker //tokens[t.makerTokenBuy][tv.makerReferrer] = safeAdd(tokens[t.makerTokenBuy][tv.makerReferrer], safeMul(tv.invQty, makerAffiliateFee) / (1 ether)); // add affiliate commission to maker affiliate balance //tokens[t.takerTokenSell][t.taker] = safeSub(tokens[t.takerTokenSell][t.taker], tv.invQty); // subtract the sold token amount from taker subBalance(t.takerTokenSell, t.taker, tv.invQty); //tv.takerAmountTaken = safeSub(safeSub(tv.qty, safeMul(tv.qty, takerFee) / (1 ether)), safeMul(tv.qty, t.takerGasFee) / (1 ether)); // amount taken from taker minus taker fee //tokens[t.takerTokenBuy][t.taker] = safeAdd(tokens[t.takerTokenBuy][t.taker], tv.takerAmountTaken); // amount received by taker, excludes taker fee addBalance(t.takerTokenBuy, t.taker, tv.takerAmountTaken); // amount received by taker, excludes taker fee //tokens[t.takerTokenBuy][tv.takerReferrer] = safeAdd(tokens[t.takerTokenBuy][tv.takerReferrer], safeMul(tv.qty, takerAffiliateFee) / (1 ether)); // add affiliate commission to taker affiliate balance //tokens[t.makerTokenBuy][feeAccount] = safeAdd(tokens[t.makerTokenBuy][feeAccount], safeMul(tv.invQty, safeSub(makerFee, makerAffiliateFee)) / (1 ether)); // add maker fee excluding affiliate commission to feeAccount //tokens[t.takerTokenBuy][feeAccount] = safeAdd(tokens[t.takerTokenBuy][feeAccount], safeAdd(safeMul(tv.qty, safeSub(takerFee, takerAffiliateFee)) / (1 ether), safeMul(tv.qty, t.takerGasFee) / (1 ether))); // add taker fee excluding affiliate commission to feeAccount orderFills[t.makerOrderHash] = safeAdd(orderFills[t.makerOrderHash], tv.invQty); // increase the maker order filled amount orderFills[t.takerOrderHash] = safeAdd(orderFills[t.takerOrderHash], tv.qty); // increase the taker order filled amount lastActiveTransaction[t.maker] = block.number; // set last activity block number for maker lastActiveTransaction[t.taker] = block.number; // set last activity block number for taker // fire Trade event emit Trade( t.takerTokenBuy, tv.qty, t.takerTokenSell, tv.invQty, t.maker, t.taker, makerFee, takerFee, tv.makerAmountTaken , tv.takerAmountTaken, t.makerOrderHash, t.takerOrderHash ); return tv.qty; } } // Executes multiple trades in one transaction, saves gas fees function batchOrderTrade( uint8[2][] v, bytes32[4][] rs, uint256[8][] tradeValues, address[6][] tradeAddresses ) onlyAdmin { for (uint i = 0; i < tradeAddresses.length; i++) { trade( v[i], rs[i], tradeValues[i], tradeAddresses[i] ); } } // Cancels order by setting amount filled to toal order amount function cancelOrder( /* [0] orderV [1] cancelV */ uint8[2] v, /* [0] orderR [1] orderS [2] cancelR [3] cancelS */ bytes32[4] rs, /* [0] orderAmountBuy [1] orderAmountSell [2] orderNonce [3] cancelNonce [4] cancelFee */ uint256[5] cancelValues, /* [0] orderTokenBuy [1] orderTokenSell [2] orderUser [3] cancelUser */ address[4] cancelAddresses ) onlyAdmin { // Order values should be valid and signed by order owner bytes32 orderHash = keccak256( this, cancelAddresses[0], cancelValues[0], cancelAddresses[1], cancelValues[1], cancelValues[2], cancelAddresses[2] ); require(ecrecover(keccak256("\x19Ethereum Signed Message:\n32", orderHash), v[0], rs[0], rs[1]) == cancelAddresses[2]); // Cancel action should be signed by order owner bytes32 cancelHash = keccak256(this, orderHash, cancelAddresses[3], cancelValues[3]); require(ecrecover(keccak256("\x19Ethereum Signed Message:\n32", cancelHash), v[1], rs[2], rs[3]) == cancelAddresses[3]); // Order owner should be the same as cancel's initiator require(cancelAddresses[2] == cancelAddresses[3]); // Do not allow to cancel already canceled or filled orders require(orderFills[orderHash] != cancelValues[0]); // Cancel gas fee cannot exceed 0.05 ETh if (cancelValues[4] > 50 finney) { cancelValues[4] = 50 finney; } // Take cancel fee // This operation throws an error if fee amount is greater than the user balance //tokens[address(0)][cancelAddresses[3]] = safeSub(tokens[address(0)][cancelAddresses[3]], cancelValues[4]); subBalance(address(0), cancelAddresses[3], cancelValues[4]); // Cancel order by setting amount filled to total order value, i.e. making the order filled orderFills[orderHash] = cancelValues[0]; // Fire cancel order event emit CancelOrder(cancelHash, orderHash, cancelAddresses[3], cancelAddresses[1], cancelValues[1], cancelValues[4]); } // Returns the smaller of two values function min(uint a, uint b) private pure returns (uint) { return a < b ? a : b; } }
mapping of connected futures contracts and connection block numbers
mapping (address => uint256) public futuresContractsAddedBlock;
2,554,680
[ 1, 6770, 434, 5840, 15583, 20092, 471, 1459, 1203, 5600, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2874, 261, 2867, 516, 2254, 5034, 13, 1071, 15583, 20723, 8602, 1768, 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 ]
./partial_match/3/0x58Fc8E8fb1A60225F8B3805b8153246A00f53bF2/sources/VVVSale.sol
require(now < icoEnd && now > icoStart);
function buy() public payable { require(msg.sender!=owner); require(tokensRaised < fundingGoal); uint tokensToBuy; uint etherUsed = msg.value; tokensToBuy = (etherUsed/ 1 ether) * tokenRate; if(tokensRaised + tokensToBuy > fundingGoal) { uint exceedingTokens = tokensRaised + tokensToBuy - fundingGoal; uint exceedingEther; exceedingEther = (exceedingTokens * 1 ether) / tokenRate; msg.sender.transfer(exceedingEther); tokensToBuy -= exceedingTokens; etherUsed -= exceedingEther; } token.releaseTokens(msg.sender, tokensToBuy); tokensRaised += tokensToBuy; etherRaised += etherUsed; }
5,336,873
[ 1, 6528, 12, 3338, 411, 277, 2894, 1638, 597, 2037, 405, 277, 2894, 1685, 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, 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, 282, 445, 30143, 1435, 1071, 8843, 429, 288, 203, 203, 1377, 2583, 12, 3576, 18, 15330, 5, 33, 8443, 1769, 203, 1377, 2583, 12, 7860, 12649, 5918, 411, 22058, 27716, 1769, 203, 1377, 2254, 2430, 774, 38, 9835, 31, 203, 1377, 2254, 225, 2437, 6668, 273, 1234, 18, 1132, 31, 203, 1377, 2430, 774, 38, 9835, 273, 261, 2437, 6668, 19, 404, 225, 2437, 13, 380, 1147, 4727, 31, 203, 203, 1377, 309, 12, 7860, 12649, 5918, 397, 2430, 774, 38, 9835, 405, 22058, 27716, 13, 288, 203, 540, 2254, 9943, 310, 5157, 273, 2430, 12649, 5918, 397, 2430, 774, 38, 9835, 300, 22058, 27716, 31, 203, 540, 2254, 9943, 310, 41, 1136, 31, 203, 203, 540, 9943, 310, 41, 1136, 273, 261, 338, 5288, 310, 5157, 380, 404, 225, 2437, 13, 342, 1147, 4727, 31, 203, 540, 1234, 18, 15330, 18, 13866, 12, 338, 5288, 310, 41, 1136, 1769, 203, 203, 540, 2430, 774, 38, 9835, 3947, 9943, 310, 5157, 31, 203, 540, 225, 2437, 6668, 3947, 9943, 310, 41, 1136, 31, 203, 1377, 289, 203, 203, 1377, 1147, 18, 9340, 5157, 12, 3576, 18, 15330, 16, 2430, 774, 38, 9835, 1769, 203, 203, 203, 1377, 2430, 12649, 5918, 1011, 2430, 774, 38, 9835, 31, 203, 1377, 225, 2437, 12649, 5918, 1011, 225, 2437, 6668, 31, 203, 282, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol"; import "./VaultCalculator.sol"; /// @title IVault Interface interface IVault { function getAccessor() external view returns (address); } /// @title IComptroller Interface interface IComptroller { function calcGav(bool) external returns (uint256, bool); function getDenominationAsset() external view returns (address); } /// @title IFundValueCalculatorUsdWrapper interface interface IFundValueCalculatorUsdWrapper { function calcNetValueForSharesHolder( address _vaultProxy, address _sharesHolder ) external returns (uint256 netValue_); } /// @title IFundValueCalculator interface interface IFundValueCalculatorRouter { function calcNetValueForSharesHolder( address _vaultProxy, address _sharesHolder ) external returns (address denominationAsset_, uint256 netValue_); function calcNetValueForSharesHolderInAsset( address _vaultProxy, address _sharesHolder, address _quoteAsset ) external returns (uint256 netValue_); } /// @title EnzymeCurrencyCalculatorCustom /// @dev This contract is used as an adapter to get a calculated dollar value for an Enzyme Vault contract EnzymeCurrencyCalculatorCustom is IVaultCalculator { address calculator; address sharesHolder; constructor(address _calculator, address _sharesHolder) { require( _calculator != address(0), "calculator can not be the zero address" ); require( _sharesHolder != address(0), "share holder can not be the zero address" ); calculator = _calculator; sharesHolder = _sharesHolder; } /// @notice The decimals are assumed to be 18, and the security is dependant on the Enzyme implementation /// @dev Read the dollar denominated value with a custom calculator for a given vault /// @param vaultProxy The address of an Enzyme vault function calculate(address vaultProxy) external override returns (uint256 answer) { answer = IFundValueCalculatorUsdWrapper(calculator) .calcNetValueForSharesHolder(vaultProxy, sharesHolder); } } /// @title EnzymeCurrencyCalculatorStandard /// @dev This contract is used as an adapter to get a calculated dollar value for an Enzyme Vault contract EnzymeCurrencyCalculatorStandard is IVaultCalculator { AggregatorV3Interface price; constructor(AggregatorV3Interface _price) { price = _price; } /// @notice The decimals are assumed to be 18, and the security is dependant on the Enzyme implementation /// @dev Read the dollar denominated value with of a vault using a Chainlink price feed and the denomination token /// quantity /// @param vault The address of an Enzyme vault function calculate(address vault) external override returns (uint256) { IComptroller accessor = IComptroller(IVault(vault).getAccessor()); address denominationAsset = accessor.getDenominationAsset(); uint256 answer; (answer, ) = IComptroller(accessor).calcGav(false); int256 latestRoundData; (, latestRoundData, , , ) = AggregatorV3Interface(price) .latestRoundData(); uint256 decimals = uint256(ERC20(denominationAsset).decimals()); uint256 priceDecimals = uint256( AggregatorV3Interface(price).decimals() ); require(latestRoundData > 0, "price feed error"); require( 18 >= decimals && 18 >= priceDecimals, "invalid token decimals" ); uint256 priceFeed = uint256(latestRoundData); return (answer * priceFeed * 10**uint256(18 - priceDecimals)) / 10**uint256(decimals); // return (answer * priceFeed) / 10**8; } } /// @title EnzymeCurrencyCalculatorStandard /// @dev This contract is used as an adapter to get a calculated token value for an Enzyme Vault contract EnzymeTokenCalculatorCustom is IVaultCalculator { address calculator; address sharesHolder; constructor(address _calculator, address _sharesHolder) { require( _calculator != address(0), "calculator can not be the zero address" ); require( _sharesHolder != address(0), "share holder can not be the zero address" ); calculator = _calculator; sharesHolder = _sharesHolder; } /// @notice The decimals are assumed to be 18, and the security is dependant on the Enzyme implementation /// @dev Read the token quantity value with a custom calculator for a given vault /// @param vaultProxy The address of an Enzyme vault function calculate(address vaultProxy) external override returns (uint256) { address denominationAsset; (denominationAsset, ) = IFundValueCalculatorRouter(calculator) .calcNetValueForSharesHolder(vaultProxy, sharesHolder); return IFundValueCalculatorRouter(calculator) .calcNetValueForSharesHolderInAsset( vaultProxy, sharesHolder, denominationAsset ); } } /// @title EnzymeCurrencyCalculatorStandard /// @dev This contract is used as an adapter to get a calculated token value for an Enzyme Vault contract EnzymeTokenCalculatorStandard is IVaultCalculator { /// @notice The decimals are assumed to be 18, and the security is dependant on the Enzyme implementation /// @dev Read the token quantity value calling the peripheral contract directly /// @param vault The address of an Enzyme vault function calculate(address vault) external override returns (uint256) { IComptroller accessor = IComptroller(IVault(vault).getAccessor()); address denominationAsset = accessor.getDenominationAsset(); uint256 answer; (answer, ) = accessor.calcGav(false); uint256 decimals = uint256(ERC20(denominationAsset).decimals()); require(18 >= decimals); return answer * 10**uint256(18 - decimals); } }
@title IComptroller Interface
interface IComptroller { function calcGav(bool) external returns (uint256, bool); function getDenominationAsset() external view returns (address); }
14,024,279
[ 1, 45, 799, 337, 1539, 6682, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 467, 799, 337, 1539, 288, 203, 565, 445, 7029, 43, 842, 12, 6430, 13, 3903, 1135, 261, 11890, 5034, 16, 1426, 1769, 203, 203, 565, 445, 2343, 275, 362, 1735, 6672, 1435, 3903, 1476, 1135, 261, 2867, 1769, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; contract ResolverBase { bytes4 private constant INTERFACE_META_ID = 0x01ffc9a7; function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == INTERFACE_META_ID; } function isAuthorised(bytes32 node) internal view returns(bool); modifier authorised(bytes32 node) { require(isAuthorised(node)); _; } function bytesToAddress(bytes memory b) internal pure returns(address payable a) { require(b.length == 20); assembly { a := div(mload(add(b, 32)), exp(256, 12)) } } function addressToBytes(address a) internal pure returns(bytes memory b) { b = new bytes(20); assembly { mstore(add(b, 32), mul(a, exp(256, 12))) } } } pragma solidity >=0.5.0; interface ENS { // Logged when the owner of a node assigns a new owner to a subnode. event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner); // Logged when the owner of a node transfers ownership to a new account. event Transfer(bytes32 indexed node, address owner); // Logged when the resolver for a node changes. event NewResolver(bytes32 indexed node, address resolver); // Logged when the TTL of a node changes event NewTTL(bytes32 indexed node, uint64 ttl); // Logged when an operator is added or removed. event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function setRecord(bytes32 node, address owner, address resolver, uint64 ttl) external; function setSubnodeRecord(bytes32 node, bytes32 label, address owner, address resolver, uint64 ttl) external; function setSubnodeOwner(bytes32 node, bytes32 label, address owner) external returns(bytes32); function setResolver(bytes32 node, address resolver) external; function setOwner(bytes32 node, address owner) external; function setTTL(bytes32 node, uint64 ttl) external; function setApprovalForAll(address operator, bool approved) external; function owner(bytes32 node) external view returns (address); function resolver(bytes32 node) external view returns (address); function ttl(bytes32 node) external view returns (uint64); function recordExists(bytes32 node) external view returns (bool); function isApprovedForAll(address owner, address operator) external view returns (bool); } /** * The ENS registry contract. */ contract ENSRegistry is ENS { struct Record { address owner; address resolver; uint64 ttl; } mapping (bytes32 => Record) records; mapping (address => mapping(address => bool)) operators; // Permits modifications only by the owner of the specified node. modifier authorised(bytes32 node) { address owner = records[node].owner; require(owner == msg.sender || operators[owner][msg.sender]); _; } /** * @dev Constructs a new ENS registrar. */ constructor() public { records[0x0].owner = msg.sender; } /** * @dev Sets the record for a node. * @param node The node to update. * @param owner The address of the new owner. * @param resolver The address of the resolver. * @param ttl The TTL in seconds. */ function setRecord(bytes32 node, address owner, address resolver, uint64 ttl) external { setOwner(node, owner); _setResolverAndTTL(node, resolver, ttl); } /** * @dev Sets the record for a subnode. * @param node The parent node. * @param label The hash of the label specifying the subnode. * @param owner The address of the new owner. * @param resolver The address of the resolver. * @param ttl The TTL in seconds. */ function setSubnodeRecord(bytes32 node, bytes32 label, address owner, address resolver, uint64 ttl) external { bytes32 subnode = setSubnodeOwner(node, label, owner); _setResolverAndTTL(subnode, resolver, ttl); } /** * @dev Transfers ownership of a node to a new address. May only be called by the current owner of the node. * @param node The node to transfer ownership of. * @param owner The address of the new owner. */ function setOwner(bytes32 node, address owner) public authorised(node) { _setOwner(node, owner); emit Transfer(node, owner); } /** * @dev Transfers ownership of a subnode keccak256(node, label) to a new address. May only be called by the owner of the parent node. * @param node The parent node. * @param label The hash of the label specifying the subnode. * @param owner The address of the new owner. */ function setSubnodeOwner(bytes32 node, bytes32 label, address owner) public authorised(node) returns(bytes32) { bytes32 subnode = keccak256(abi.encodePacked(node, label)); _setOwner(subnode, owner); emit NewOwner(node, label, owner); return subnode; } /** * @dev Sets the resolver address for the specified node. * @param node The node to update. * @param resolver The address of the resolver. */ function setResolver(bytes32 node, address resolver) public authorised(node) { emit NewResolver(node, resolver); records[node].resolver = resolver; } /** * @dev Sets the TTL for the specified node. * @param node The node to update. * @param ttl The TTL in seconds. */ function setTTL(bytes32 node, uint64 ttl) public authorised(node) { emit NewTTL(node, ttl); records[node].ttl = ttl; } /** * @dev Enable or disable approval for a third party ("operator") to manage * all of `msg.sender`'s ENS records. Emits the ApprovalForAll event. * @param operator Address to add to the set of authorized operators. * @param approved True if the operator is approved, false to revoke approval. */ function setApprovalForAll(address operator, bool approved) external { operators[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } /** * @dev Returns the address that owns the specified node. * @param node The specified node. * @return address of the owner. */ function owner(bytes32 node) public view returns (address) { address addr = records[node].owner; if (addr == address(this)) { return address(0x0); } return addr; } /** * @dev Returns the address of the resolver for the specified node. * @param node The specified node. * @return address of the resolver. */ function resolver(bytes32 node) public view returns (address) { return records[node].resolver; } /** * @dev Returns the TTL of a node, and any records associated with it. * @param node The specified node. * @return ttl of the node. */ function ttl(bytes32 node) public view returns (uint64) { return records[node].ttl; } /** * @dev Returns whether a record has been imported to the registry. * @param node The specified node. * @return Bool if record exists */ function recordExists(bytes32 node) public view returns (bool) { return records[node].owner != address(0x0); } /** * @dev Query if an address is an authorized operator for another address. * @param owner The address that owns the records. * @param operator The address that acts on behalf of the owner. * @return True if `operator` is an approved operator for `owner`, false otherwise. */ function isApprovedForAll(address owner, address operator) external view returns (bool) { return operators[owner][operator]; } function _setOwner(bytes32 node, address owner) internal { records[node].owner = owner; } function _setResolverAndTTL(bytes32 node, address resolver, uint64 ttl) internal { if(resolver != records[node].resolver) { records[node].resolver = resolver; emit NewResolver(node, resolver); } if(ttl != records[node].ttl) { records[node].ttl = ttl; emit NewTTL(node, ttl); } } } pragma solidity ^0.5.0; contract ABIResolver is ResolverBase { bytes4 constant private ABI_INTERFACE_ID = 0x2203ab56; event ABIChanged(bytes32 indexed node, uint256 indexed contentType); mapping(bytes32=>mapping(uint256=>bytes)) abis; /** * Sets the ABI associated with an ENS node. * Nodes may have one ABI of each content type. To remove an ABI, set it to * the empty string. * @param node The node to update. * @param contentType The content type of the ABI * @param data The ABI data. */ function setABI(bytes32 node, uint256 contentType, bytes calldata data) external authorised(node) { // Content types must be powers of 2 require(((contentType - 1) & contentType) == 0); abis[node][contentType] = data; emit ABIChanged(node, contentType); } /** * Returns the ABI associated with an ENS node. * Defined in EIP205. * @param node The ENS node to query * @param contentTypes A bitwise OR of the ABI formats accepted by the caller. * @return contentType The content type of the return value * @return data The ABI data */ function ABI(bytes32 node, uint256 contentTypes) external view returns (uint256, bytes memory) { mapping(uint256=>bytes) storage abiset = abis[node]; for (uint256 contentType = 1; contentType <= contentTypes; contentType <<= 1) { if ((contentType & contentTypes) != 0 && abiset[contentType].length > 0) { return (contentType, abiset[contentType]); } } return (0, bytes("")); } function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == ABI_INTERFACE_ID || super.supportsInterface(interfaceID); } } pragma solidity ^0.5.0; contract AddrResolver is ResolverBase { bytes4 constant private ADDR_INTERFACE_ID = 0x3b3b57de; bytes4 constant private ADDRESS_INTERFACE_ID = 0xf1cb7e06; uint constant private COIN_TYPE_ETH = 60; event AddrChanged(bytes32 indexed node, address a); event AddressChanged(bytes32 indexed node, uint coinType, bytes newAddress); mapping(bytes32=>mapping(uint=>bytes)) _addresses; /** * Sets the address associated with an ENS node. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param a The address to set. */ function setAddr(bytes32 node, address a) external authorised(node) { setAddr(node, COIN_TYPE_ETH, addressToBytes(a)); } /** * Returns the address associated with an ENS node. * @param node The ENS node to query. * @return The associated address. */ function addr(bytes32 node) public view returns (address payable) { bytes memory a = addr(node, COIN_TYPE_ETH); if(a.length == 0) { return address(0); } return bytesToAddress(a); } function setAddr(bytes32 node, uint coinType, bytes memory a) public authorised(node) { emit AddressChanged(node, coinType, a); if(coinType == COIN_TYPE_ETH) { emit AddrChanged(node, bytesToAddress(a)); } _addresses[node][coinType] = a; } function addr(bytes32 node, uint coinType) public view returns(bytes memory) { return _addresses[node][coinType]; } function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == ADDR_INTERFACE_ID || interfaceID == ADDRESS_INTERFACE_ID || super.supportsInterface(interfaceID); } } pragma solidity ^0.5.0; contract ContentHashResolver is ResolverBase { bytes4 constant private CONTENT_HASH_INTERFACE_ID = 0xbc1c58d1; event ContenthashChanged(bytes32 indexed node, bytes hash); mapping(bytes32=>bytes) hashes; /** * Sets the contenthash associated with an ENS node. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param hash The contenthash to set */ function setContenthash(bytes32 node, bytes calldata hash) external authorised(node) { hashes[node] = hash; emit ContenthashChanged(node, hash); } /** * Returns the contenthash associated with an ENS node. * @param node The ENS node to query. * @return The associated contenthash. */ function contenthash(bytes32 node) external view returns (bytes memory) { return hashes[node]; } function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == CONTENT_HASH_INTERFACE_ID || super.supportsInterface(interfaceID); } } pragma solidity >0.4.23; library BytesUtils { /* * @dev Returns the keccak-256 hash of a byte range. * @param self The byte string to hash. * @param offset The position to start hashing at. * @param len The number of bytes to hash. * @return The hash of the byte range. */ function keccak(bytes memory self, uint offset, uint len) internal pure returns (bytes32 ret) { require(offset + len <= self.length); assembly { ret := keccak256(add(add(self, 32), offset), len) } } /* * @dev Returns a positive number if `other` comes lexicographically after * `self`, a negative number if it comes before, or zero if the * contents of the two bytes are equal. * @param self The first bytes to compare. * @param other The second bytes to compare. * @return The result of the comparison. */ function compare(bytes memory self, bytes memory other) internal pure returns (int) { return compare(self, 0, self.length, other, 0, other.length); } /* * @dev Returns a positive number if `other` comes lexicographically after * `self`, a negative number if it comes before, or zero if the * contents of the two bytes are equal. Comparison is done per-rune, * on unicode codepoints. * @param self The first bytes to compare. * @param offset The offset of self. * @param len The length of self. * @param other The second bytes to compare. * @param otheroffset The offset of the other string. * @param otherlen The length of the other string. * @return The result of the comparison. */ function compare(bytes memory self, uint offset, uint len, bytes memory other, uint otheroffset, uint otherlen) internal pure returns (int) { uint shortest = len; if (otherlen < len) shortest = otherlen; uint selfptr; uint otherptr; assembly { selfptr := add(self, add(offset, 32)) otherptr := add(other, add(otheroffset, 32)) } for (uint idx = 0; idx < shortest; idx += 32) { uint a; uint b; assembly { a := mload(selfptr) b := mload(otherptr) } if (a != b) { // Mask out irrelevant bytes and check again uint mask; if (shortest > 32) { mask = uint256(- 1); // aka 0xffffff.... } else { mask = ~(2 ** (8 * (32 - shortest + idx)) - 1); } uint diff = (a & mask) - (b & mask); if (diff != 0) return int(diff); } selfptr += 32; otherptr += 32; } return int(len) - int(otherlen); } /* * @dev Returns true if the two byte ranges are equal. * @param self The first byte range to compare. * @param offset The offset into the first byte range. * @param other The second byte range to compare. * @param otherOffset The offset into the second byte range. * @param len The number of bytes to compare * @return True if the byte ranges are equal, false otherwise. */ function equals(bytes memory self, uint offset, bytes memory other, uint otherOffset, uint len) internal pure returns (bool) { return keccak(self, offset, len) == keccak(other, otherOffset, len); } /* * @dev Returns true if the two byte ranges are equal with offsets. * @param self The first byte range to compare. * @param offset The offset into the first byte range. * @param other The second byte range to compare. * @param otherOffset The offset into the second byte range. * @return True if the byte ranges are equal, false otherwise. */ function equals(bytes memory self, uint offset, bytes memory other, uint otherOffset) internal pure returns (bool) { return keccak(self, offset, self.length - offset) == keccak(other, otherOffset, other.length - otherOffset); } /* * @dev Compares a range of 'self' to all of 'other' and returns True iff * they are equal. * @param self The first byte range to compare. * @param offset The offset into the first byte range. * @param other The second byte range to compare. * @return True if the byte ranges are equal, false otherwise. */ function equals(bytes memory self, uint offset, bytes memory other) internal pure returns (bool) { return self.length >= offset + other.length && equals(self, offset, other, 0, other.length); } /* * @dev Returns true if the two byte ranges are equal. * @param self The first byte range to compare. * @param other The second byte range to compare. * @return True if the byte ranges are equal, false otherwise. */ function equals(bytes memory self, bytes memory other) internal pure returns(bool) { return self.length == other.length && equals(self, 0, other, 0, self.length); } /* * @dev Returns the 8-bit number at the specified index of self. * @param self The byte string. * @param idx The index into the bytes * @return The specified 8 bits of the string, interpreted as an integer. */ function readUint8(bytes memory self, uint idx) internal pure returns (uint8 ret) { return uint8(self[idx]); } /* * @dev Returns the 16-bit number at the specified index of self. * @param self The byte string. * @param idx The index into the bytes * @return The specified 16 bits of the string, interpreted as an integer. */ function readUint16(bytes memory self, uint idx) internal pure returns (uint16 ret) { require(idx + 2 <= self.length); assembly { ret := and(mload(add(add(self, 2), idx)), 0xFFFF) } } /* * @dev Returns the 32-bit number at the specified index of self. * @param self The byte string. * @param idx The index into the bytes * @return The specified 32 bits of the string, interpreted as an integer. */ function readUint32(bytes memory self, uint idx) internal pure returns (uint32 ret) { require(idx + 4 <= self.length); assembly { ret := and(mload(add(add(self, 4), idx)), 0xFFFFFFFF) } } /* * @dev Returns the 32 byte value at the specified index of self. * @param self The byte string. * @param idx The index into the bytes * @return The specified 32 bytes of the string. */ function readBytes32(bytes memory self, uint idx) internal pure returns (bytes32 ret) { require(idx + 32 <= self.length); assembly { ret := mload(add(add(self, 32), idx)) } } /* * @dev Returns the 32 byte value at the specified index of self. * @param self The byte string. * @param idx The index into the bytes * @return The specified 32 bytes of the string. */ function readBytes20(bytes memory self, uint idx) internal pure returns (bytes20 ret) { require(idx + 20 <= self.length); assembly { ret := and(mload(add(add(self, 32), idx)), 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000000) } } /* * @dev Returns the n byte value at the specified index of self. * @param self The byte string. * @param idx The index into the bytes. * @param len The number of bytes. * @return The specified 32 bytes of the string. */ function readBytesN(bytes memory self, uint idx, uint len) internal pure returns (bytes32 ret) { require(len <= 32); require(idx + len <= self.length); assembly { let mask := not(sub(exp(256, sub(32, len)), 1)) ret := and(mload(add(add(self, 32), idx)), mask) } } function memcpy(uint dest, uint src, uint len) private pure { // Copy word-length chunks while possible for (; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } /* * @dev Copies a substring into a new byte string. * @param self The byte string to copy from. * @param offset The offset to start copying at. * @param len The number of bytes to copy. */ function substring(bytes memory self, uint offset, uint len) internal pure returns(bytes memory) { require(offset + len <= self.length); bytes memory ret = new bytes(len); uint dest; uint src; assembly { dest := add(ret, 32) src := add(add(self, 32), offset) } memcpy(dest, src, len); return ret; } // Maps characters from 0x30 to 0x7A to their base32 values. // 0xFF represents invalid characters in that range. bytes constant base32HexTable = hex'00010203040506070809FFFFFFFFFFFFFF0A0B0C0D0E0F101112131415161718191A1B1C1D1E1FFFFFFFFFFFFFFFFFFFFF0A0B0C0D0E0F101112131415161718191A1B1C1D1E1F'; /** * @dev Decodes unpadded base32 data of up to one word in length. * @param self The data to decode. * @param off Offset into the string to start at. * @param len Number of characters to decode. * @return The decoded data, left aligned. */ function base32HexDecodeWord(bytes memory self, uint off, uint len) internal pure returns(bytes32) { require(len <= 52); uint ret = 0; uint8 decoded; for(uint i = 0; i < len; i++) { bytes1 char = self[off + i]; require(char >= 0x30 && char <= 0x7A); decoded = uint8(base32HexTable[uint(uint8(char)) - 0x30]); require(decoded <= 0x20); if(i == len - 1) { break; } ret = (ret << 5) | decoded; } uint bitlen = len * 5; if(len % 8 == 0) { // Multiple of 8 characters, no padding ret = (ret << 5) | decoded; } else if(len % 8 == 2) { // Two extra characters - 1 byte ret = (ret << 3) | (decoded >> 2); bitlen -= 2; } else if(len % 8 == 4) { // Four extra characters - 2 bytes ret = (ret << 1) | (decoded >> 4); bitlen -= 4; } else if(len % 8 == 5) { // Five extra characters - 3 bytes ret = (ret << 4) | (decoded >> 1); bitlen -= 1; } else if(len % 8 == 7) { // Seven extra characters - 4 bytes ret = (ret << 2) | (decoded >> 3); bitlen -= 3; } else { revert(); } return bytes32(ret << (256 - bitlen)); } } pragma solidity >0.4.18; /** * @dev A library for working with mutable byte buffers in Solidity. * * Byte buffers are mutable and expandable, and provide a variety of primitives * for writing to them. At any time you can fetch a bytes object containing the * current contents of the buffer. The bytes object should not be stored between * operations, as it may change due to resizing of the buffer. */ library Buffer { /** * @dev Represents a mutable buffer. Buffers have a current value (buf) and * a capacity. The capacity may be longer than the current value, in * which case it can be extended without the need to allocate more memory. */ struct buffer { bytes buf; uint capacity; } /** * @dev Initializes a buffer with an initial capacity. * @param buf The buffer to initialize. * @param capacity The number of bytes of space to allocate the buffer. * @return The buffer, for chaining. */ function init(buffer memory buf, uint capacity) internal pure returns(buffer memory) { if (capacity % 32 != 0) { capacity += 32 - (capacity % 32); } // Allocate space for the buffer data buf.capacity = capacity; assembly { let ptr := mload(0x40) mstore(buf, ptr) mstore(ptr, 0) mstore(0x40, add(32, add(ptr, capacity))) } return buf; } /** * @dev Initializes a new buffer from an existing bytes object. * Changes to the buffer may mutate the original value. * @param b The bytes object to initialize the buffer with. * @return A new buffer. */ function fromBytes(bytes memory b) internal pure returns(buffer memory) { buffer memory buf; buf.buf = b; buf.capacity = b.length; return buf; } function resize(buffer memory buf, uint capacity) private pure { bytes memory oldbuf = buf.buf; init(buf, capacity); append(buf, oldbuf); } function max(uint a, uint b) private pure returns(uint) { if (a > b) { return a; } return b; } /** * @dev Sets buffer length to 0. * @param buf The buffer to truncate. * @return The original buffer, for chaining.. */ function truncate(buffer memory buf) internal pure returns (buffer memory) { assembly { let bufptr := mload(buf) mstore(bufptr, 0) } return buf; } /** * @dev Writes a byte string to a buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param off The start offset to write to. * @param data The data to append. * @param len The number of bytes to copy. * @return The original buffer, for chaining. */ function write(buffer memory buf, uint off, bytes memory data, uint len) internal pure returns(buffer memory) { require(len <= data.length); if (off + len > buf.capacity) { resize(buf, max(buf.capacity, len + off) * 2); } uint dest; uint src; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Start address = buffer address + offset + sizeof(buffer length) dest := add(add(bufptr, 32), off) // Update buffer length if we're extending it if gt(add(len, off), buflen) { mstore(bufptr, add(len, off)) } src := add(data, 32) } // Copy word-length chunks while possible for (; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } return buf; } /** * @dev Appends a byte string to a buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @param len The number of bytes to copy. * @return The original buffer, for chaining. */ function append(buffer memory buf, bytes memory data, uint len) internal pure returns (buffer memory) { return write(buf, buf.buf.length, data, len); } /** * @dev Appends a byte string to a buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer, for chaining. */ function append(buffer memory buf, bytes memory data) internal pure returns (buffer memory) { return write(buf, buf.buf.length, data, data.length); } /** * @dev Writes a byte to the buffer. Resizes if doing so would exceed the * capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write the byte at. * @param data The data to append. * @return The original buffer, for chaining. */ function writeUint8(buffer memory buf, uint off, uint8 data) internal pure returns(buffer memory) { if (off >= buf.capacity) { resize(buf, buf.capacity * 2); } assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Address = buffer address + sizeof(buffer length) + off let dest := add(add(bufptr, off), 32) mstore8(dest, data) // Update buffer length if we extended it if eq(off, buflen) { mstore(bufptr, add(buflen, 1)) } } return buf; } /** * @dev Appends a byte to the buffer. Resizes if doing so would exceed the * capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer, for chaining. */ function appendUint8(buffer memory buf, uint8 data) internal pure returns(buffer memory) { return writeUint8(buf, buf.buf.length, data); } /** * @dev Writes up to 32 bytes to the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write at. * @param data The data to append. * @param len The number of bytes to write (left-aligned). * @return The original buffer, for chaining. */ function write(buffer memory buf, uint off, bytes32 data, uint len) private pure returns(buffer memory) { if (len + off > buf.capacity) { resize(buf, (len + off) * 2); } uint mask = 256 ** len - 1; // Right-align data data = data >> (8 * (32 - len)); assembly { // Memory address of the buffer data let bufptr := mload(buf) // Address = buffer address + sizeof(buffer length) + off + len let dest := add(add(bufptr, off), len) mstore(dest, or(and(mload(dest), not(mask)), data)) // Update buffer length if we extended it if gt(add(off, len), mload(bufptr)) { mstore(bufptr, add(off, len)) } } return buf; } /** * @dev Writes a bytes20 to the buffer. Resizes if doing so would exceed the * capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write at. * @param data The data to append. * @return The original buffer, for chaining. */ function writeBytes20(buffer memory buf, uint off, bytes20 data) internal pure returns (buffer memory) { return write(buf, off, bytes32(data), 20); } /** * @dev Appends a bytes20 to the buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer, for chhaining. */ function appendBytes20(buffer memory buf, bytes20 data) internal pure returns (buffer memory) { return write(buf, buf.buf.length, bytes32(data), 20); } /** * @dev Appends a bytes32 to the buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer, for chaining. */ function appendBytes32(buffer memory buf, bytes32 data) internal pure returns (buffer memory) { return write(buf, buf.buf.length, data, 32); } /** * @dev Writes an integer to the buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write at. * @param data The data to append. * @param len The number of bytes to write (right-aligned). * @return The original buffer, for chaining. */ function writeInt(buffer memory buf, uint off, uint data, uint len) private pure returns(buffer memory) { if (len + off > buf.capacity) { resize(buf, (len + off) * 2); } uint mask = 256 ** len - 1; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Address = buffer address + off + sizeof(buffer length) + len let dest := add(add(bufptr, off), len) mstore(dest, or(and(mload(dest), not(mask)), data)) // Update buffer length if we extended it if gt(add(off, len), mload(bufptr)) { mstore(bufptr, add(off, len)) } } return buf; } /** * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) { return writeInt(buf, buf.buf.length, data, len); } } pragma solidity >0.4.23; /** * @dev RRUtils is a library that provides utilities for parsing DNS resource records. */ library RRUtils { using BytesUtils for *; using Buffer for *; /** * @dev Returns the number of bytes in the DNS name at 'offset' in 'self'. * @param self The byte array to read a name from. * @param offset The offset to start reading at. * @return The length of the DNS name at 'offset', in bytes. */ function nameLength(bytes memory self, uint offset) internal pure returns(uint) { uint idx = offset; while (true) { assert(idx < self.length); uint labelLen = self.readUint8(idx); idx += labelLen + 1; if (labelLen == 0) { break; } } return idx - offset; } /** * @dev Returns a DNS format name at the specified offset of self. * @param self The byte array to read a name from. * @param offset The offset to start reading at. * @return The name. */ function readName(bytes memory self, uint offset) internal pure returns(bytes memory ret) { uint len = nameLength(self, offset); return self.substring(offset, len); } /** * @dev Returns the number of labels in the DNS name at 'offset' in 'self'. * @param self The byte array to read a name from. * @param offset The offset to start reading at. * @return The number of labels in the DNS name at 'offset', in bytes. */ function labelCount(bytes memory self, uint offset) internal pure returns(uint) { uint count = 0; while (true) { assert(offset < self.length); uint labelLen = self.readUint8(offset); offset += labelLen + 1; if (labelLen == 0) { break; } count += 1; } return count; } /** * @dev An iterator over resource records. */ struct RRIterator { bytes data; uint offset; uint16 dnstype; uint16 class; uint32 ttl; uint rdataOffset; uint nextOffset; } /** * @dev Begins iterating over resource records. * @param self The byte string to read from. * @param offset The offset to start reading at. * @return An iterator object. */ function iterateRRs(bytes memory self, uint offset) internal pure returns (RRIterator memory ret) { ret.data = self; ret.nextOffset = offset; next(ret); } /** * @dev Returns true iff there are more RRs to iterate. * @param iter The iterator to check. * @return True iff the iterator has finished. */ function done(RRIterator memory iter) internal pure returns(bool) { return iter.offset >= iter.data.length; } /** * @dev Moves the iterator to the next resource record. * @param iter The iterator to advance. */ function next(RRIterator memory iter) internal pure { iter.offset = iter.nextOffset; if (iter.offset >= iter.data.length) { return; } // Skip the name uint off = iter.offset + nameLength(iter.data, iter.offset); // Read type, class, and ttl iter.dnstype = iter.data.readUint16(off); off += 2; iter.class = iter.data.readUint16(off); off += 2; iter.ttl = iter.data.readUint32(off); off += 4; // Read the rdata uint rdataLength = iter.data.readUint16(off); off += 2; iter.rdataOffset = off; iter.nextOffset = off + rdataLength; } /** * @dev Returns the name of the current record. * @param iter The iterator. * @return A new bytes object containing the owner name from the RR. */ function name(RRIterator memory iter) internal pure returns(bytes memory) { return iter.data.substring(iter.offset, nameLength(iter.data, iter.offset)); } /** * @dev Returns the rdata portion of the current record. * @param iter The iterator. * @return A new bytes object containing the RR's RDATA. */ function rdata(RRIterator memory iter) internal pure returns(bytes memory) { return iter.data.substring(iter.rdataOffset, iter.nextOffset - iter.rdataOffset); } /** * @dev Checks if a given RR type exists in a type bitmap. * @param self The byte string to read the type bitmap from. * @param offset The offset to start reading at. * @param rrtype The RR type to check for. * @return True if the type is found in the bitmap, false otherwise. */ function checkTypeBitmap(bytes memory self, uint offset, uint16 rrtype) internal pure returns (bool) { uint8 typeWindow = uint8(rrtype >> 8); uint8 windowByte = uint8((rrtype & 0xff) / 8); uint8 windowBitmask = uint8(uint8(1) << (uint8(7) - uint8(rrtype & 0x7))); for (uint off = offset; off < self.length;) { uint8 window = self.readUint8(off); uint8 len = self.readUint8(off + 1); if (typeWindow < window) { // We've gone past our window; it's not here. return false; } else if (typeWindow == window) { // Check this type bitmap if (len * 8 <= windowByte) { // Our type is past the end of the bitmap return false; } return (self.readUint8(off + windowByte + 2) & windowBitmask) != 0; } else { // Skip this type bitmap off += len + 2; } } return false; } function compareNames(bytes memory self, bytes memory other) internal pure returns (int) { if (self.equals(other)) { return 0; } uint off; uint otheroff; uint prevoff; uint otherprevoff; uint counts = labelCount(self, 0); uint othercounts = labelCount(other, 0); // Keep removing labels from the front of the name until both names are equal length while (counts > othercounts) { prevoff = off; off = progress(self, off); counts--; } while (othercounts > counts) { otherprevoff = otheroff; otheroff = progress(other, otheroff); othercounts--; } // Compare the last nonequal labels to each other while (counts > 0 && !self.equals(off, other, otheroff)) { prevoff = off; off = progress(self, off); otherprevoff = otheroff; otheroff = progress(other, otheroff); counts -= 1; } if (off == 0) { return -1; } if(otheroff == 0) { return 1; } return self.compare(prevoff + 1, self.readUint8(prevoff), other, otherprevoff + 1, other.readUint8(otherprevoff)); } function progress(bytes memory body, uint off) internal pure returns(uint) { return off + 1 + body.readUint8(off); } } pragma solidity ^0.5.0; contract DNSResolver is ResolverBase { using RRUtils for *; using BytesUtils for bytes; bytes4 constant private DNS_RECORD_INTERFACE_ID = 0xa8fa5682; bytes4 constant private DNS_ZONE_INTERFACE_ID = 0x5c47637c; // DNSRecordChanged is emitted whenever a given node/name/resource's RRSET is updated. event DNSRecordChanged(bytes32 indexed node, bytes name, uint16 resource, bytes record); // DNSRecordDeleted is emitted whenever a given node/name/resource's RRSET is deleted. event DNSRecordDeleted(bytes32 indexed node, bytes name, uint16 resource); // DNSZoneCleared is emitted whenever a given node's zone information is cleared. event DNSZoneCleared(bytes32 indexed node); // DNSZonehashChanged is emitted whenever a given node's zone hash is updated. event DNSZonehashChanged(bytes32 indexed node, bytes lastzonehash, bytes zonehash); // Zone hashes for the domains. // A zone hash is an EIP-1577 content hash in binary format that should point to a // resource containing a single zonefile. // node => contenthash mapping(bytes32=>bytes) private zonehashes; // Version the mapping for each zone. This allows users who have lost // track of their entries to effectively delete an entire zone by bumping // the version number. // node => version mapping(bytes32=>uint256) private versions; // The records themselves. Stored as binary RRSETs // node => version => name => resource => data mapping(bytes32=>mapping(uint256=>mapping(bytes32=>mapping(uint16=>bytes)))) private records; // Count of number of entries for a given name. Required for DNS resolvers // when resolving wildcards. // node => version => name => number of records mapping(bytes32=>mapping(uint256=>mapping(bytes32=>uint16))) private nameEntriesCount; /** * Set one or more DNS records. Records are supplied in wire-format. * Records with the same node/name/resource must be supplied one after the * other to ensure the data is updated correctly. For example, if the data * was supplied: * a.example.com IN A 1.2.3.4 * a.example.com IN A 5.6.7.8 * www.example.com IN CNAME a.example.com. * then this would store the two A records for a.example.com correctly as a * single RRSET, however if the data was supplied: * a.example.com IN A 1.2.3.4 * www.example.com IN CNAME a.example.com. * a.example.com IN A 5.6.7.8 * then this would store the first A record, the CNAME, then the second A * record which would overwrite the first. * * @param node the namehash of the node for which to set the records * @param data the DNS wire format records to set */ function setDNSRecords(bytes32 node, bytes calldata data) external authorised(node) { uint16 resource = 0; uint256 offset = 0; bytes memory name; bytes memory value; bytes32 nameHash; // Iterate over the data to add the resource records for (RRUtils.RRIterator memory iter = data.iterateRRs(0); !iter.done(); iter.next()) { if (resource == 0) { resource = iter.dnstype; name = iter.name(); nameHash = keccak256(abi.encodePacked(name)); value = bytes(iter.rdata()); } else { bytes memory newName = iter.name(); if (resource != iter.dnstype || !name.equals(newName)) { setDNSRRSet(node, name, resource, data, offset, iter.offset - offset, value.length == 0); resource = iter.dnstype; offset = iter.offset; name = newName; nameHash = keccak256(name); value = bytes(iter.rdata()); } } } if (name.length > 0) { setDNSRRSet(node, name, resource, data, offset, data.length - offset, value.length == 0); } } /** * Obtain a DNS record. * @param node the namehash of the node for which to fetch the record * @param name the keccak-256 hash of the fully-qualified name for which to fetch the record * @param resource the ID of the resource as per https://en.wikipedia.org/wiki/List_of_DNS_record_types * @return the DNS record in wire format if present, otherwise empty */ function dnsRecord(bytes32 node, bytes32 name, uint16 resource) public view returns (bytes memory) { return records[node][versions[node]][name][resource]; } /** * Check if a given node has records. * @param node the namehash of the node for which to check the records * @param name the namehash of the node for which to check the records */ function hasDNSRecords(bytes32 node, bytes32 name) public view returns (bool) { return (nameEntriesCount[node][versions[node]][name] != 0); } /** * Clear all information for a DNS zone. * @param node the namehash of the node for which to clear the zone */ function clearDNSZone(bytes32 node) public authorised(node) { versions[node]++; emit DNSZoneCleared(node); } /** * setZonehash sets the hash for the zone. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param hash The zonehash to set */ function setZonehash(bytes32 node, bytes calldata hash) external authorised(node) { bytes memory oldhash = zonehashes[node]; zonehashes[node] = hash; emit DNSZonehashChanged(node, oldhash, hash); } /** * zonehash obtains the hash for the zone. * @param node The ENS node to query. * @return The associated contenthash. */ function zonehash(bytes32 node) external view returns (bytes memory) { return zonehashes[node]; } function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == DNS_RECORD_INTERFACE_ID || interfaceID == DNS_ZONE_INTERFACE_ID || super.supportsInterface(interfaceID); } function setDNSRRSet( bytes32 node, bytes memory name, uint16 resource, bytes memory data, uint256 offset, uint256 size, bool deleteRecord) private { uint256 version = versions[node]; bytes32 nameHash = keccak256(name); bytes memory rrData = data.substring(offset, size); if (deleteRecord) { if (records[node][version][nameHash][resource].length != 0) { nameEntriesCount[node][version][nameHash]--; } delete(records[node][version][nameHash][resource]); emit DNSRecordDeleted(node, name, resource); } else { if (records[node][version][nameHash][resource].length == 0) { nameEntriesCount[node][version][nameHash]++; } records[node][version][nameHash][resource] = rrData; emit DNSRecordChanged(node, name, resource, rrData); } } } pragma solidity ^0.5.0; contract InterfaceResolver is ResolverBase, AddrResolver { bytes4 constant private INTERFACE_INTERFACE_ID = bytes4(keccak256("interfaceImplementer(bytes32,bytes4)")); bytes4 private constant INTERFACE_META_ID = 0x01ffc9a7; event InterfaceChanged(bytes32 indexed node, bytes4 indexed interfaceID, address implementer); mapping(bytes32=>mapping(bytes4=>address)) interfaces; /** * Sets an interface associated with a name. * Setting the address to 0 restores the default behaviour of querying the contract at `addr()` for interface support. * @param node The node to update. * @param interfaceID The EIP 165 interface ID. * @param implementer The address of a contract that implements this interface for this node. */ function setInterface(bytes32 node, bytes4 interfaceID, address implementer) external authorised(node) { interfaces[node][interfaceID] = implementer; emit InterfaceChanged(node, interfaceID, implementer); } /** * Returns the address of a contract that implements the specified interface for this name. * If an implementer has not been set for this interfaceID and name, the resolver will query * the contract at `addr()`. If `addr()` is set, a contract exists at that address, and that * contract implements EIP165 and returns `true` for the specified interfaceID, its address * will be returned. * @param node The ENS node to query. * @param interfaceID The EIP 165 interface ID to check for. * @return The address that implements this interface, or 0 if the interface is unsupported. */ function interfaceImplementer(bytes32 node, bytes4 interfaceID) external view returns (address) { address implementer = interfaces[node][interfaceID]; if(implementer != address(0)) { return implementer; } address a = addr(node); if(a == address(0)) { return address(0); } (bool success, bytes memory returnData) = a.staticcall(abi.encodeWithSignature("supportsInterface(bytes4)", INTERFACE_META_ID)); if(!success || returnData.length < 32 || returnData[31] == 0) { // EIP 165 not supported by target return address(0); } (success, returnData) = a.staticcall(abi.encodeWithSignature("supportsInterface(bytes4)", interfaceID)); if(!success || returnData.length < 32 || returnData[31] == 0) { // Specified interface not supported by target return address(0); } return a; } function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == INTERFACE_INTERFACE_ID || super.supportsInterface(interfaceID); } } pragma solidity ^0.5.0; contract NameResolver is ResolverBase { bytes4 constant private NAME_INTERFACE_ID = 0x691f3431; event NameChanged(bytes32 indexed node, string name); mapping(bytes32=>string) names; /** * Sets the name associated with an ENS node, for reverse records. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param name The name to set. */ function setName(bytes32 node, string calldata name) external authorised(node) { names[node] = name; emit NameChanged(node, name); } /** * Returns the name associated with an ENS node, for reverse records. * Defined in EIP181. * @param node The ENS node to query. * @return The associated name. */ function name(bytes32 node) external view returns (string memory) { return names[node]; } function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == NAME_INTERFACE_ID || super.supportsInterface(interfaceID); } } pragma solidity ^0.5.0; contract PubkeyResolver is ResolverBase { bytes4 constant private PUBKEY_INTERFACE_ID = 0xc8690233; event PubkeyChanged(bytes32 indexed node, bytes32 x, bytes32 y); struct PublicKey { bytes32 x; bytes32 y; } mapping(bytes32=>PublicKey) pubkeys; /** * Sets the SECP256k1 public key associated with an ENS node. * @param node The ENS node to query * @param x the X coordinate of the curve point for the public key. * @param y the Y coordinate of the curve point for the public key. */ function setPubkey(bytes32 node, bytes32 x, bytes32 y) external authorised(node) { pubkeys[node] = PublicKey(x, y); emit PubkeyChanged(node, x, y); } /** * Returns the SECP256k1 public key associated with an ENS node. * Defined in EIP 619. * @param node The ENS node to query * @return x, y the X and Y coordinates of the curve point for the public key. */ function pubkey(bytes32 node) external view returns (bytes32 x, bytes32 y) { return (pubkeys[node].x, pubkeys[node].y); } function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == PUBKEY_INTERFACE_ID || super.supportsInterface(interfaceID); } } pragma solidity ^0.5.0; contract TextResolver is ResolverBase { bytes4 constant private TEXT_INTERFACE_ID = 0x59d1d43c; event TextChanged(bytes32 indexed node, string indexed indexedKey, string key); mapping(bytes32=>mapping(string=>string)) texts; /** * Sets the text data associated with an ENS node and key. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param key The key to set. * @param value The text data value to set. */ function setText(bytes32 node, string calldata key, string calldata value) external authorised(node) { texts[node][key] = value; emit TextChanged(node, key, key); } /** * Returns the text data associated with an ENS node and key. * @param node The ENS node to query. * @param key The text data key to query. * @return The associated text data. */ function text(bytes32 node, string calldata key) external view returns (string memory) { return texts[node][key]; } function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == TEXT_INTERFACE_ID || super.supportsInterface(interfaceID); } } pragma solidity ^0.5.0; /** * A simple resolver anyone can use; only allows the owner of a node to set its * address. */ contract PublicResolver is ABIResolver, AddrResolver, ContentHashResolver, DNSResolver, InterfaceResolver, NameResolver, PubkeyResolver, TextResolver { ENS ens; /** * A mapping of authorisations. An address that is authorised for a name * may make any changes to the name that the owner could, but may not update * the set of authorisations. * (node, owner, caller) => isAuthorised */ mapping(bytes32=>mapping(address=>mapping(address=>bool))) public authorisations; event AuthorisationChanged(bytes32 indexed node, address indexed owner, address indexed target, bool isAuthorised); constructor(ENS _ens) public { ens = _ens; } /** * @dev Sets or clears an authorisation. * Authorisations are specific to the caller. Any account can set an authorisation * for any name, but the authorisation that is checked will be that of the * current owner of a name. Thus, transferring a name effectively clears any * existing authorisations, and new authorisations can be set in advance of * an ownership transfer if desired. * * @param node The name to change the authorisation on. * @param target The address that is to be authorised or deauthorised. * @param isAuthorised True if the address should be authorised, or false if it should be deauthorised. */ function setAuthorisation(bytes32 node, address target, bool isAuthorised) external { authorisations[node][msg.sender][target] = isAuthorised; emit AuthorisationChanged(node, msg.sender, target, isAuthorised); } function isAuthorised(bytes32 node) internal view returns(bool) { address owner = ens.owner(node); return owner == msg.sender || authorisations[node][owner][msg.sender]; } }
* @dev RRUtils is a library that provides utilities for parsing DNS resource records./
library RRUtils { using BytesUtils for *; using Buffer for *; function nameLength(bytes memory self, uint offset) internal pure returns(uint) { uint idx = offset; while (true) { assert(idx < self.length); uint labelLen = self.readUint8(idx); idx += labelLen + 1; if (labelLen == 0) { break; } } return idx - offset; } function nameLength(bytes memory self, uint offset) internal pure returns(uint) { uint idx = offset; while (true) { assert(idx < self.length); uint labelLen = self.readUint8(idx); idx += labelLen + 1; if (labelLen == 0) { break; } } return idx - offset; } function nameLength(bytes memory self, uint offset) internal pure returns(uint) { uint idx = offset; while (true) { assert(idx < self.length); uint labelLen = self.readUint8(idx); idx += labelLen + 1; if (labelLen == 0) { break; } } return idx - offset; } function readName(bytes memory self, uint offset) internal pure returns(bytes memory ret) { uint len = nameLength(self, offset); return self.substring(offset, len); } function labelCount(bytes memory self, uint offset) internal pure returns(uint) { uint count = 0; while (true) { assert(offset < self.length); uint labelLen = self.readUint8(offset); offset += labelLen + 1; if (labelLen == 0) { break; } count += 1; } return count; } function labelCount(bytes memory self, uint offset) internal pure returns(uint) { uint count = 0; while (true) { assert(offset < self.length); uint labelLen = self.readUint8(offset); offset += labelLen + 1; if (labelLen == 0) { break; } count += 1; } return count; } function labelCount(bytes memory self, uint offset) internal pure returns(uint) { uint count = 0; while (true) { assert(offset < self.length); uint labelLen = self.readUint8(offset); offset += labelLen + 1; if (labelLen == 0) { break; } count += 1; } return count; } struct RRIterator { bytes data; uint offset; uint16 dnstype; uint16 class; uint32 ttl; uint rdataOffset; uint nextOffset; } function iterateRRs(bytes memory self, uint offset) internal pure returns (RRIterator memory ret) { ret.data = self; ret.nextOffset = offset; next(ret); } function done(RRIterator memory iter) internal pure returns(bool) { return iter.offset >= iter.data.length; } function next(RRIterator memory iter) internal pure { iter.offset = iter.nextOffset; if (iter.offset >= iter.data.length) { return; } off += 2; iter.class = iter.data.readUint16(off); off += 2; iter.ttl = iter.data.readUint32(off); off += 4; off += 2; iter.rdataOffset = off; iter.nextOffset = off + rdataLength; } function next(RRIterator memory iter) internal pure { iter.offset = iter.nextOffset; if (iter.offset >= iter.data.length) { return; } off += 2; iter.class = iter.data.readUint16(off); off += 2; iter.ttl = iter.data.readUint32(off); off += 4; off += 2; iter.rdataOffset = off; iter.nextOffset = off + rdataLength; } uint off = iter.offset + nameLength(iter.data, iter.offset); iter.dnstype = iter.data.readUint16(off); uint rdataLength = iter.data.readUint16(off); function name(RRIterator memory iter) internal pure returns(bytes memory) { return iter.data.substring(iter.offset, nameLength(iter.data, iter.offset)); } function rdata(RRIterator memory iter) internal pure returns(bytes memory) { return iter.data.substring(iter.rdataOffset, iter.nextOffset - iter.rdataOffset); } function checkTypeBitmap(bytes memory self, uint offset, uint16 rrtype) internal pure returns (bool) { uint8 typeWindow = uint8(rrtype >> 8); uint8 windowByte = uint8((rrtype & 0xff) / 8); uint8 windowBitmask = uint8(uint8(1) << (uint8(7) - uint8(rrtype & 0x7))); for (uint off = offset; off < self.length;) { uint8 window = self.readUint8(off); uint8 len = self.readUint8(off + 1); if (typeWindow < window) { return false; if (len * 8 <= windowByte) { return false; } return (self.readUint8(off + windowByte + 2) & windowBitmask) != 0; } } return false; } function checkTypeBitmap(bytes memory self, uint offset, uint16 rrtype) internal pure returns (bool) { uint8 typeWindow = uint8(rrtype >> 8); uint8 windowByte = uint8((rrtype & 0xff) / 8); uint8 windowBitmask = uint8(uint8(1) << (uint8(7) - uint8(rrtype & 0x7))); for (uint off = offset; off < self.length;) { uint8 window = self.readUint8(off); uint8 len = self.readUint8(off + 1); if (typeWindow < window) { return false; if (len * 8 <= windowByte) { return false; } return (self.readUint8(off + windowByte + 2) & windowBitmask) != 0; } } return false; } function checkTypeBitmap(bytes memory self, uint offset, uint16 rrtype) internal pure returns (bool) { uint8 typeWindow = uint8(rrtype >> 8); uint8 windowByte = uint8((rrtype & 0xff) / 8); uint8 windowBitmask = uint8(uint8(1) << (uint8(7) - uint8(rrtype & 0x7))); for (uint off = offset; off < self.length;) { uint8 window = self.readUint8(off); uint8 len = self.readUint8(off + 1); if (typeWindow < window) { return false; if (len * 8 <= windowByte) { return false; } return (self.readUint8(off + windowByte + 2) & windowBitmask) != 0; } } return false; } } else if (typeWindow == window) { function checkTypeBitmap(bytes memory self, uint offset, uint16 rrtype) internal pure returns (bool) { uint8 typeWindow = uint8(rrtype >> 8); uint8 windowByte = uint8((rrtype & 0xff) / 8); uint8 windowBitmask = uint8(uint8(1) << (uint8(7) - uint8(rrtype & 0x7))); for (uint off = offset; off < self.length;) { uint8 window = self.readUint8(off); uint8 len = self.readUint8(off + 1); if (typeWindow < window) { return false; if (len * 8 <= windowByte) { return false; } return (self.readUint8(off + windowByte + 2) & windowBitmask) != 0; } } return false; } } else { off += len + 2; function compareNames(bytes memory self, bytes memory other) internal pure returns (int) { if (self.equals(other)) { return 0; } uint off; uint otheroff; uint prevoff; uint otherprevoff; uint counts = labelCount(self, 0); uint othercounts = labelCount(other, 0); while (counts > othercounts) { prevoff = off; off = progress(self, off); counts--; } while (othercounts > counts) { otherprevoff = otheroff; otheroff = progress(other, otheroff); othercounts--; } while (counts > 0 && !self.equals(off, other, otheroff)) { prevoff = off; off = progress(self, off); otherprevoff = otheroff; otheroff = progress(other, otheroff); counts -= 1; } if (off == 0) { return -1; } if(otheroff == 0) { return 1; } return self.compare(prevoff + 1, self.readUint8(prevoff), other, otherprevoff + 1, other.readUint8(otherprevoff)); } function compareNames(bytes memory self, bytes memory other) internal pure returns (int) { if (self.equals(other)) { return 0; } uint off; uint otheroff; uint prevoff; uint otherprevoff; uint counts = labelCount(self, 0); uint othercounts = labelCount(other, 0); while (counts > othercounts) { prevoff = off; off = progress(self, off); counts--; } while (othercounts > counts) { otherprevoff = otheroff; otheroff = progress(other, otheroff); othercounts--; } while (counts > 0 && !self.equals(off, other, otheroff)) { prevoff = off; off = progress(self, off); otherprevoff = otheroff; otheroff = progress(other, otheroff); counts -= 1; } if (off == 0) { return -1; } if(otheroff == 0) { return 1; } return self.compare(prevoff + 1, self.readUint8(prevoff), other, otherprevoff + 1, other.readUint8(otherprevoff)); } function compareNames(bytes memory self, bytes memory other) internal pure returns (int) { if (self.equals(other)) { return 0; } uint off; uint otheroff; uint prevoff; uint otherprevoff; uint counts = labelCount(self, 0); uint othercounts = labelCount(other, 0); while (counts > othercounts) { prevoff = off; off = progress(self, off); counts--; } while (othercounts > counts) { otherprevoff = otheroff; otheroff = progress(other, otheroff); othercounts--; } while (counts > 0 && !self.equals(off, other, otheroff)) { prevoff = off; off = progress(self, off); otherprevoff = otheroff; otheroff = progress(other, otheroff); counts -= 1; } if (off == 0) { return -1; } if(otheroff == 0) { return 1; } return self.compare(prevoff + 1, self.readUint8(prevoff), other, otherprevoff + 1, other.readUint8(otherprevoff)); } function compareNames(bytes memory self, bytes memory other) internal pure returns (int) { if (self.equals(other)) { return 0; } uint off; uint otheroff; uint prevoff; uint otherprevoff; uint counts = labelCount(self, 0); uint othercounts = labelCount(other, 0); while (counts > othercounts) { prevoff = off; off = progress(self, off); counts--; } while (othercounts > counts) { otherprevoff = otheroff; otheroff = progress(other, otheroff); othercounts--; } while (counts > 0 && !self.equals(off, other, otheroff)) { prevoff = off; off = progress(self, off); otherprevoff = otheroff; otheroff = progress(other, otheroff); counts -= 1; } if (off == 0) { return -1; } if(otheroff == 0) { return 1; } return self.compare(prevoff + 1, self.readUint8(prevoff), other, otherprevoff + 1, other.readUint8(otherprevoff)); } function compareNames(bytes memory self, bytes memory other) internal pure returns (int) { if (self.equals(other)) { return 0; } uint off; uint otheroff; uint prevoff; uint otherprevoff; uint counts = labelCount(self, 0); uint othercounts = labelCount(other, 0); while (counts > othercounts) { prevoff = off; off = progress(self, off); counts--; } while (othercounts > counts) { otherprevoff = otheroff; otheroff = progress(other, otheroff); othercounts--; } while (counts > 0 && !self.equals(off, other, otheroff)) { prevoff = off; off = progress(self, off); otherprevoff = otheroff; otheroff = progress(other, otheroff); counts -= 1; } if (off == 0) { return -1; } if(otheroff == 0) { return 1; } return self.compare(prevoff + 1, self.readUint8(prevoff), other, otherprevoff + 1, other.readUint8(otherprevoff)); } function compareNames(bytes memory self, bytes memory other) internal pure returns (int) { if (self.equals(other)) { return 0; } uint off; uint otheroff; uint prevoff; uint otherprevoff; uint counts = labelCount(self, 0); uint othercounts = labelCount(other, 0); while (counts > othercounts) { prevoff = off; off = progress(self, off); counts--; } while (othercounts > counts) { otherprevoff = otheroff; otheroff = progress(other, otheroff); othercounts--; } while (counts > 0 && !self.equals(off, other, otheroff)) { prevoff = off; off = progress(self, off); otherprevoff = otheroff; otheroff = progress(other, otheroff); counts -= 1; } if (off == 0) { return -1; } if(otheroff == 0) { return 1; } return self.compare(prevoff + 1, self.readUint8(prevoff), other, otherprevoff + 1, other.readUint8(otherprevoff)); } function compareNames(bytes memory self, bytes memory other) internal pure returns (int) { if (self.equals(other)) { return 0; } uint off; uint otheroff; uint prevoff; uint otherprevoff; uint counts = labelCount(self, 0); uint othercounts = labelCount(other, 0); while (counts > othercounts) { prevoff = off; off = progress(self, off); counts--; } while (othercounts > counts) { otherprevoff = otheroff; otheroff = progress(other, otheroff); othercounts--; } while (counts > 0 && !self.equals(off, other, otheroff)) { prevoff = off; off = progress(self, off); otherprevoff = otheroff; otheroff = progress(other, otheroff); counts -= 1; } if (off == 0) { return -1; } if(otheroff == 0) { return 1; } return self.compare(prevoff + 1, self.readUint8(prevoff), other, otherprevoff + 1, other.readUint8(otherprevoff)); } function progress(bytes memory body, uint off) internal pure returns(uint) { return off + 1 + body.readUint8(off); } }
15,546
[ 1, 17950, 1989, 353, 279, 5313, 716, 8121, 22538, 364, 5811, 8858, 1058, 3853, 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, 12083, 21618, 1989, 288, 203, 565, 1450, 5985, 1989, 364, 380, 31, 203, 565, 1450, 3525, 364, 380, 31, 203, 203, 565, 445, 508, 1782, 12, 3890, 3778, 365, 16, 2254, 1384, 13, 2713, 16618, 1135, 12, 11890, 13, 288, 203, 3639, 2254, 2067, 273, 1384, 31, 203, 3639, 1323, 261, 3767, 13, 288, 203, 5411, 1815, 12, 3465, 411, 365, 18, 2469, 1769, 203, 5411, 2254, 1433, 2891, 273, 365, 18, 896, 5487, 28, 12, 3465, 1769, 203, 5411, 2067, 1011, 1433, 2891, 397, 404, 31, 203, 5411, 309, 261, 1925, 2891, 422, 374, 13, 288, 203, 7734, 898, 31, 203, 5411, 289, 203, 3639, 289, 203, 3639, 327, 2067, 300, 1384, 31, 203, 565, 289, 203, 203, 565, 445, 508, 1782, 12, 3890, 3778, 365, 16, 2254, 1384, 13, 2713, 16618, 1135, 12, 11890, 13, 288, 203, 3639, 2254, 2067, 273, 1384, 31, 203, 3639, 1323, 261, 3767, 13, 288, 203, 5411, 1815, 12, 3465, 411, 365, 18, 2469, 1769, 203, 5411, 2254, 1433, 2891, 273, 365, 18, 896, 5487, 28, 12, 3465, 1769, 203, 5411, 2067, 1011, 1433, 2891, 397, 404, 31, 203, 5411, 309, 261, 1925, 2891, 422, 374, 13, 288, 203, 7734, 898, 31, 203, 5411, 289, 203, 3639, 289, 203, 3639, 327, 2067, 300, 1384, 31, 203, 565, 289, 203, 203, 565, 445, 508, 1782, 12, 3890, 3778, 365, 16, 2254, 1384, 13, 2713, 16618, 1135, 12, 11890, 13, 288, 203, 3639, 2254, 2067, 273, 1384, 31, 203, 3639, 1323, 261, 3767, 13, 288, 203, 5411, 1815, 12, 2 ]
pragma ton-solidity >=0.52.0; pragma AbiHeader time; pragma AbiHeader pubkey; pragma AbiHeader expire; //================================================================================ // import "../interfaces/IBasicCollection.sol"; import "../interfaces/IBase.sol"; import "../contracts/BasicToken.sol"; //================================================================================ // contract BasicCollection is IBase, IBasicCollection { //======================================== // Error codes uint constant ERROR_MESSAGE_SENDER_IS_NOT_MY_OWNER = 100; uint constant ERROR_MESSAGE_OWNER_CAN_NOT_BE_ZERO = 103; uint constant ERROR_VALUE_NOT_ENOUGH_TO_MINT = 200; //======================================== // Variables uint256 static _nonce; // Random number to randomize collection address; TvmCell static _tokenCode; // uint256 _tokensIssued; // address _ownerAddress; // // Metadata string _metadata; // Collection metadata, for the collection cover and info; //======================================== // Modifiers modifier onlyOwner { require(_checkSenderAddress(_ownerAddress), ERROR_MESSAGE_SENDER_IS_NOT_MY_OWNER); _; } //======================================== // Getters function getBasicInfo(bool includeMetadata, bool includeTokenCode) external view responsible override reserve returns( uint256 nonce, TvmCell tokenCode, uint256 tokensIssued, address ownerAddress, string metadata) { TvmCell empty; return {value: 0, flag: 128}( _nonce, includeTokenCode ? _tokenCode : empty, _tokensIssued, _ownerAddress, includeMetadata ? _metadata : "{}"); } //======================================== // function calculateFutureTokenAddress(uint256 tokenID) private inline view returns (address, TvmCell) { TvmCell stateInit = tvm.buildStateInit({ contr: BasicToken, varInit: { _collectionAddress: address(this), // _tokenID: tokenID // }, code: _tokenCode }); return (address(tvm.hash(stateInit)), stateInit); } //======================================== // function getTokenAddress(uint256 targetTokenID) external view responsible override reserve returns (uint256 tokenID, address tokenAddress) { (address addr, ) = calculateFutureTokenAddress(targetTokenID); return {value: 0, flag: 128}(targetTokenID, addr); } //======================================== // constructor(address ownerAddress, address initiatorAddress, string metadata) public reserve returnChangeTo(initiatorAddress) { if(msg.isExternal){ tvm.accept(); } require(ownerAddress != addressZero, ERROR_MESSAGE_OWNER_CAN_NOT_BE_ZERO); // Collection configuration _tokensIssued = 0; _ownerAddress = ownerAddress; _metadata = metadata; } //======================================== // function createToken( address ownerAddress, address authorityAddress, address initiatorAddress, string metadata) external onlyOwner reserve returns (address tokenAddress) { require(msg.value >= gasToValue(400000, address(this).wid), ERROR_VALUE_NOT_ENOUGH_TO_MINT); // TODO: adjust value (address addr, TvmCell stateInit) = calculateFutureTokenAddress(_tokensIssued); emit mint(_tokensIssued, addr, ownerAddress, initiatorAddress); new BasicToken{value: 0, flag: 128, stateInit: stateInit}( ownerAddress, authorityAddress, initiatorAddress, metadata); _tokensIssued += 1; return addr; } //======================================== // function setOwner(address ownerAddress) external override onlyOwner reserve returnChange { emit ownerChanged(_ownerAddress, ownerAddress); _ownerAddress = ownerAddress; } //======================================== // } //================================================================================ //
========================================
function getTokenAddress(uint256 targetTokenID) external view responsible override reserve returns (uint256 tokenID, address tokenAddress) { (address addr, ) = calculateFutureTokenAddress(targetTokenID); }
13,138,319
[ 1, 4428, 1432, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 9162, 1887, 12, 11890, 5034, 1018, 1345, 734, 13, 3903, 1476, 14549, 3849, 20501, 1135, 261, 11890, 5034, 1147, 734, 16, 1758, 1147, 1887, 13, 203, 565, 288, 203, 3639, 261, 2867, 3091, 16, 262, 273, 4604, 4118, 1345, 1887, 12, 3299, 1345, 734, 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 ]
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 long 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 long 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 ); event onAirPot( uint256 roundID, uint256 potType, address winner, uint256 prize ); } //============================================================================== // _ _ _ _|_ _ _ __|_ _ _ _|_ _ . // (_(_)| | | | (_|(_ | _\(/_ | |_||_) . //====================================|========================================= contract modularLong is F3Devents {} contract FoMo3Dlong is modularLong { using SafeMath for *; using NameFilter for string; using F3DKeysCalcLong for uint256; address private owner = 0x0c204d9C438553a107B29cdE1d1e7954673b29B3; address private opAddress = 0x0c204d9C438553a107B29cdE1d1e7954673b29B3; address private comAddress = 0x24D160101C72c035287f772a8ac2b744a477F489; PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0x0f717ffff71e639636fcdd33727ee8c17c4724bf); //============================================================================== // _ _ _ |`. _ _ _ |_ | _ _ . // (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings) //=================_|=========================================================== string constant public name = "FoMo3D Long Official"; string constant public symbol = "F3D"; uint256 private rndExtra_ = 0;//extSettings.getLongExtra(); // length of the very first ICO //uint256 private rndGap_ = 0 hours ;// extSettings.getLongGap(); // length of ICO phase, set to 1 year for EOS. uint256 constant private rndInit_ = 2 hours; // round timer starts at this uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer uint256 constant private rndMax_ = 2 hours; // max length a round timer can be uint256 constant private comDropGap_ = 24 hours; uint256 constant private rndNTR_ = 168 hours; //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes) //=============================|================================================ uint256 public airDropPot_; // person who gets the airdrop wins part of this pot uint256 public airDropPot2_; uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop uint256 public airDropTracker2_ = 0; uint256 public rID_; // round id number / total rounds that have happened uint256 public comReWards_; uint256 public comAirDrop_; //**************** // 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) mapping (uint256 => uint256) public inviteCount_; mapping (address => bool) public addrLock_; //**************** // 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 mapping (uint256 => uint256[10]) public lastTen_; mapping (uint256 => uint256) public roundBetCount_; //rId => team => datetime mapping (uint256 => mapping (uint256 =>uint256)) public comDropLastTime_; //**************** // 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. //not p3d change to owner 20% fees_[0] = F3Ddatasets.TeamFee(48,0);//(30,6); //50% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot fees_[1] = F3Ddatasets.TeamFee(33,0);//(43,0); //43% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot fees_[2] = F3Ddatasets.TeamFee(18,0);//(56,10); //20% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot // fees_[3] = F3Ddatasets.TeamFee(51,0);//(43,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(10,20);//(15,10); //48% to winner, 25% to next round, 2% to com potSplit_[1] = F3Ddatasets.PotSplit(5,20); //48% to winner, 25% to next round, 2% to com potSplit_[2] = F3Ddatasets.PotSplit(20,20);//(20,20); //48% to winner, 10% to next round, 2% to com // potSplit_[3] = F3Ddatasets.PotSplit(40,20);//(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"); _; } /* modifier locked() { require(!addrLock_[msg.sender],"this address is locked"); _; }*/ //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) //====|========================================================================= /** * @dev emergency buy uses last stored affiliate ID and team snek */ function() isActivated() isHuman() //locked() 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() //locked() 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() //locked() 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() //locked() 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() //locked() 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() //locked() 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() //locked() 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 && (_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 ) return( (round_[_rID].end).sub(_now) ); else return( (round_[_rID].strt ).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 && (_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 && (_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; lastTen_[_rID][roundBetCount_[_rID] % 10] = _pID; roundBetCount_[_rID]++; 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; emit onAirPot(_rID,1,plyr_[_pID].addr,_prize); // reset air drop tracker airDropTracker_ = 0; } } if (_eth >= 500000000000000000 && round_[_rID].pot >=100000000000000000000){ air2( _rID, _pID, _affID); } if(inviteCount_[_pID] >= 100 && (comDropLastTime_[_rID][_team] + comDropGap_) <= now){ comDrop(_rID,_pID,_affID,_team); } // 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_); } } function air2(uint256 _rID, uint256 _pID, uint256 _affID) private { // airDrop2 // uint256 compressedData = 0; airDropTracker2_++; if (airdrop2() == true) { // gib muni uint256 _prize2; // calculate prize and give it to winner _prize2 = ((airDropPot2_).mul(50)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize2.mul(80) / 100); uint256 _affIDUp = plyr_[_affID].laff; if (_affIDUp !=0 && _affIDUp != _pID && plyr_[_affIDUp].name != '') { plyr_[_affIDUp].win = (plyr_[_affIDUp].win).add(_prize2.mul(20) / 100); }else{ _prize2 = (_prize2.mul(80) / 100); } // adjust airDropPot2 airDropPot2_ = (airDropPot2_).sub(_prize2); // let event know a tier 3 prize was won // compressedData = 300000000000000000000000000000000; // set airdrop happened bool to true // compressedData += 10000000000000000000000000000000; // let event know how much was won // compressedData += _prize2 * 1000000000000000000000000000000000; emit onAirPot(_rID,2,plyr_[_pID].addr,_prize2); // reset air drop tracker airDropTracker2_ = 0; } // return compressedData; } function comDrop(uint256 _rID, uint256 _pID, uint256 _affID, uint256 _team) private { // uint256 compressedData = 0; 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)) ))); if((seed - ((seed / 100) * 100)) < 15){ // calculate prize and give it to winner uint256 _prize3 = comAirDrop_ / 10; plyr_[_pID].win = (plyr_[_pID].win).add(_prize3.mul(2)); uint256 _affIDUp = plyr_[_affID].laff; if (_affIDUp !=0 && _affIDUp != _pID && plyr_[_affIDUp].name != '') { plyr_[_affIDUp].win = (plyr_[_affIDUp].win).add(_prize3); _prize3 = _prize3.mul(3) ; }else{ _prize3 = _prize3.mul(2) ; } comAirDrop_ = (comAirDrop_).sub(_prize3); // let event know a tier 3 prize was won // compressedData = 300000000000000000000000000000000; // set airdrop happened bool to true // compressedData += 10000000000000000000000000000000; // let event know how much was won // compressedData += _prize3 * 1000000000000000000000000000000000; emit onAirPot(_rID,3,plyr_[_pID].addr,_prize3); comDropLastTime_[_rID][_team] = now; } // return compressedData; } //============================================================================== // _ _ | _ | _ _|_ _ _ _ . // (_(_||(_|_||(_| | (_)| _\ . //============================================================================== /** * @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 && (_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 && (_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 > 2) return(0); 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; // community rewards uint256 _com = (_pot / 50); //uint256 _comTotal = ; comAddress.transfer(_com.add(comAirDrop_).add(comReWards_).add(airDropPot_).add(airDropPot2_)); comAirDrop_ = 0; comReWards_ = 0; airDropPot_ = 0; airDropPot2_ = 0; 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); //last ten share shareLastTen( _rID, _win); // distribute gen portion to key holders round_[_rID].mask = _ppt.add(round_[_rID].mask); // send share for p3d to divies //if (_p3d > 0) opAddress.transfer(_p3d); // 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.add(comDropGap_); round_[_rID].end = now.add(comDropGap_).add(rndInit_); round_[_rID].pot = _res; return(_eventData_); } function shareLastTen(uint256 _rID, uint256 _win) private { if(roundBetCount_[_rID] >= 10){ uint256 _singleWin = _win / 10; plyr_[lastTen_[_rID][0]].win = _singleWin.add(plyr_[lastTen_[_rID][0]].win); plyr_[lastTen_[_rID][1]].win = _singleWin.add(plyr_[lastTen_[_rID][1]].win); plyr_[lastTen_[_rID][2]].win = _singleWin.add(plyr_[lastTen_[_rID][2]].win); plyr_[lastTen_[_rID][3]].win = _singleWin.add(plyr_[lastTen_[_rID][3]].win); plyr_[lastTen_[_rID][4]].win = _singleWin.add(plyr_[lastTen_[_rID][4]].win); plyr_[lastTen_[_rID][5]].win = _singleWin.add(plyr_[lastTen_[_rID][5]].win); plyr_[lastTen_[_rID][6]].win = _singleWin.add(plyr_[lastTen_[_rID][6]].win); plyr_[lastTen_[_rID][7]].win = _singleWin.add(plyr_[lastTen_[_rID][7]].win); plyr_[lastTen_[_rID][8]].win = _singleWin.add(plyr_[lastTen_[_rID][8]].win); plyr_[lastTen_[_rID][9]].win = _singleWin.add(plyr_[lastTen_[_rID][9]].win); } else{ uint256 _avarageWin = _win / roundBetCount_[_rID]; for(uint256 _index = 0; _index < roundBetCount_[_rID] ; _index++ ){ plyr_[lastTen_[_rID][_index]].win = _avarageWin.add(plyr_[lastTen_[_rID][_index]].win); } } } /** * @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); if(round_[_rID].strt.add(rndNTR_) >= now){ // 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); } function airdrop2() 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)) < airDropTracker2_) 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) { uint256 _p3d = 0; uint256 opEth = _eth.mul(18) / 100; opAddress.transfer(opEth); // decide what to do with affiliate share of fees // affiliate must not be self, and must have a name registered _p3d = affsend( _affID, _pID, _rID, _eth, _p3d); // pay out p3d //_p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100)); if (_p3d > 0) { // deposit to divies contract //change to owner //Divies.deposit.value(_p3d)(); owner.transfer(_p3d); // set up event data _eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount); } return(_eventData_); } function affsend(uint256 _affID, uint256 _pID, uint256 _rID, uint256 _eth, uint256 _p3d) private returns(uint256) { // distribute share to affiliate 10% uint256 _aff = _eth / 10; // distribute share to affiliate 3% uint256 _affUp = _eth.mul(3) / 100; 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); uint256 _affIDUp = plyr_[_affID].laff; inviteCount_[_affID] ++; if (_affIDUp !=0 && _affIDUp != _pID && plyr_[_affIDUp].name != '') { plyr_[_affIDUp].aff = _affUp.add(plyr_[_affIDUp].aff); emit F3Devents.onAffiliatePayout(_affIDUp, plyr_[_affIDUp].addr, plyr_[_affIDUp].name, _rID, _pID, _affUp, now); inviteCount_[_affIDUp] ++; }else{ _p3d = _p3d.add(_affUp); } } else { _p3d = _aff; } return _p3d; } 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) { //1. pay 2% out to community rewards comReWards_ = comReWards_.add(_eth / 50); comAirDrop_ = comAirDrop_.add(_eth / 100); // calculate gen share uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; // toss 1% into airdrop pot uint256 _air = (_eth / 100); airDropPot_ = airDropPot_.add(_air); // toss 10% into airdrop2 pot airDropPot2_ = airDropPot2_.add(_eth / 10); // update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share)) _eth = _eth.sub(((_eth.mul(39)) / 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 == owner , "only team just can activate" ); // make sure that its been linked. //require(address(otherF3D_) != address(0), "must link to other FoMo3D first"); // can only be ran once require(activated_ == false, "fomo3d already activated"); // activate the contract activated_ = true; // lets start first round rID_ = 1; round_[1].strt = now + rndExtra_ ; 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 F3DKeysCalcLong { 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); } 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); } } }
locked() set up our tx event data fetch player ID manage affiliate residuals if no affiliate code was given or player tried to use their own, lolz
{ F3Ddatasets.EventReturns memory _eventData_; uint256 _pID = pIDxAddr_[msg.sender]; uint256 _affID; if (_affCode == '' || _affCode == plyr_[_pID].name) function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { _affID = plyr_[_pID].laff; _affID = pIDxName_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } } else { function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { _affID = plyr_[_pID].laff; _affID = pIDxName_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } _team = verifyTeam(_team); reLoadCore(_pID, _affID, _team, _eth, _eventData_); }
11,990,459
[ 1, 15091, 1435, 444, 731, 3134, 2229, 871, 501, 2158, 7291, 1599, 10680, 7103, 330, 3840, 29252, 309, 1158, 7103, 330, 3840, 981, 1703, 864, 578, 7291, 12928, 358, 999, 3675, 4953, 16, 328, 355, 94, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 288, 203, 3639, 478, 23, 40, 21125, 18, 1133, 1356, 3778, 389, 2575, 751, 67, 31, 203, 540, 203, 3639, 2254, 5034, 389, 84, 734, 273, 293, 734, 92, 3178, 67, 63, 3576, 18, 15330, 15533, 203, 540, 203, 3639, 2254, 5034, 389, 7329, 734, 31, 203, 3639, 309, 261, 67, 7329, 1085, 422, 875, 747, 389, 7329, 1085, 422, 293, 715, 86, 67, 63, 67, 84, 734, 8009, 529, 13, 203, 565, 445, 283, 2563, 60, 529, 12, 3890, 1578, 389, 7329, 1085, 16, 2254, 5034, 389, 10035, 16, 2254, 5034, 389, 546, 13, 203, 3639, 353, 28724, 1435, 203, 3639, 27803, 6925, 1435, 203, 3639, 353, 18949, 12768, 24899, 546, 13, 203, 3639, 1071, 203, 3639, 288, 203, 5411, 389, 7329, 734, 273, 293, 715, 86, 67, 63, 67, 84, 734, 8009, 80, 7329, 31, 203, 540, 203, 5411, 389, 7329, 734, 273, 293, 734, 92, 461, 67, 63, 67, 7329, 1085, 15533, 203, 2398, 203, 5411, 309, 261, 67, 7329, 734, 480, 293, 715, 86, 67, 63, 67, 84, 734, 8009, 80, 7329, 13, 203, 5411, 288, 203, 7734, 293, 715, 86, 67, 63, 67, 84, 734, 8009, 80, 7329, 273, 389, 7329, 734, 31, 203, 5411, 289, 203, 3639, 289, 203, 540, 203, 540, 203, 3639, 289, 469, 288, 203, 565, 445, 283, 2563, 60, 529, 12, 3890, 1578, 389, 7329, 1085, 16, 2254, 5034, 389, 10035, 16, 2254, 5034, 389, 546, 13, 203, 3639, 353, 28724, 1435, 203, 3639, 27803, 6925, 1435, 203, 3639, 353, 18949, 12768, 24899, 2 ]
//! A Multi-signature, daily-limited account proxy/wallet library. //! //! Inheritable "property" contract that enables methods to be protected by //! requiring the acquiescence of either a single, or, crucially, each of a //! number of, designated owners. //! //! Usage: use modifiers onlyowner (just own owned) or onlymanyowners(hash), //! whereby the same hash must be provided by some number (specified in //! constructor) of the set of owners (specified in the constructor, modifiable) //! before the interior is executed. //! //! Version: Parity fork 1.0 //! //! Copyright 2016-17 Gavin Wood and Nicolas Gotchac, Parity Technologies Ltd. //! //! Licensed under the Apache License, Version 2.0 (the "License"); //! you may not use this file except in compliance with the License. //! You may obtain a copy of the License at //! //! http://www.apache.org/licenses/LICENSE-2.0 //! //! Unless required by applicable law or agreed to in writing, software //! distributed under the License is distributed on an "AS IS" BASIS, //! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //! See the License for the specific language governing permissions and //! limitations under the License. pragma solidity ^0.4.13; contract multiowned { // TYPES // struct for the status of a pending operation. struct PendingState { uint yetNeeded; uint ownersDone; uint index; } // EVENTS // this contract only has six types of events: it can accept a confirmation, in which case // we record owner and operation (hash) alongside it. event Confirmation(address owner, bytes32 operation); event Revoke(address owner, bytes32 operation); // some others are in the case of an owner changing. event OwnerChanged(address oldOwner, address newOwner); event OwnerAdded(address newOwner); event OwnerRemoved(address oldOwner); // the last one is emitted if the required signatures change event RequirementChanged(uint newRequirement); // MODIFIERS // simple single-sig function modifier. modifier onlyowner { if (isOwner(msg.sender)) _; } // multi-sig function modifier: the operation must have an intrinsic hash in order // that later attempts can be realised as the same underlying operation and // thus count as confirmations. modifier onlymanyowners(bytes32 _operation) { if (confirmAndCheck(_operation)) _; } modifier only_uninitialized { require(m_numOwners == 0); _; } // METHODS // constructor is given number of sigs required to do protected "onlymanyowners" transactions // as well as the selection of addresses capable of confirming them. function init_multiowned(address[] _owners, uint _required) only_uninitialized internal { require(_required > 0); require(_owners.length >= _required); m_numOwners = _owners.length; for (uint i = 0; i < _owners.length; ++i) { m_owners[1 + i] = uint(_owners[i]); m_ownerIndex[uint(_owners[i])] = 1 + i; } m_required = _required; } // Revokes a prior confirmation of the given operation function revoke(bytes32 _operation) external { uint ownerIndex = m_ownerIndex[uint(msg.sender)]; // make sure they're an owner if (ownerIndex == 0) return; uint ownerIndexBit = 2**ownerIndex; var pending = m_pending[_operation]; if (pending.ownersDone & ownerIndexBit > 0) { pending.yetNeeded++; pending.ownersDone -= ownerIndexBit; Revoke(msg.sender, _operation); } } // Replaces an owner `_from` with another `_to`. function changeOwner(address _from, address _to) onlymanyowners(sha3(msg.data)) external { if (isOwner(_to)) return; uint ownerIndex = m_ownerIndex[uint(_from)]; if (ownerIndex == 0) return; clearPending(); m_owners[ownerIndex] = uint(_to); m_ownerIndex[uint(_from)] = 0; m_ownerIndex[uint(_to)] = ownerIndex; OwnerChanged(_from, _to); } function addOwner(address _owner) onlymanyowners(sha3(msg.data)) external { if (isOwner(_owner)) return; clearPending(); if (m_numOwners >= c_maxOwners) reorganizeOwners(); if (m_numOwners >= c_maxOwners) return; m_numOwners++; m_owners[m_numOwners] = uint(_owner); m_ownerIndex[uint(_owner)] = m_numOwners; OwnerAdded(_owner); } function removeOwner(address _owner) onlymanyowners(sha3(msg.data)) external { uint ownerIndex = m_ownerIndex[uint(_owner)]; if (ownerIndex == 0) return; if (m_required > m_numOwners - 1) return; m_owners[ownerIndex] = 0; m_ownerIndex[uint(_owner)] = 0; clearPending(); reorganizeOwners(); //make sure m_numOwner is equal to the number of owners and always points to the optimal free slot OwnerRemoved(_owner); } function changeRequirement(uint _newRequired) onlymanyowners(sha3(msg.data)) external { if (_newRequired == 0) return; if (_newRequired > m_numOwners) return; m_required = _newRequired; clearPending(); RequirementChanged(_newRequired); } // Gets an owner by 0-indexed position (using numOwners as the count) function getOwner(uint ownerIndex) external constant returns (address) { return address(m_owners[ownerIndex + 1]); } function isOwner(address _addr) public constant returns (bool) { return m_ownerIndex[uint(_addr)] > 0; } function hasConfirmed(bytes32 _operation, address _owner) external constant returns (bool) { var pending = m_pending[_operation]; uint ownerIndex = m_ownerIndex[uint(_owner)]; // make sure they're an owner if (ownerIndex == 0) return false; // determine the bit to set for this owner. uint ownerIndexBit = 2**ownerIndex; return !(pending.ownersDone & ownerIndexBit == 0); } // INTERNAL METHODS function confirmAndCheck(bytes32 _operation) internal returns (bool) { // determine what index the present sender is: uint ownerIndex = m_ownerIndex[uint(msg.sender)]; // make sure they're an owner if (ownerIndex == 0) return; var pending = m_pending[_operation]; // if we're not yet working on this operation, switch over and reset the confirmation status. if (pending.yetNeeded == 0) { // reset count of confirmations needed. pending.yetNeeded = m_required; // reset which owners have confirmed (none) - set our bitmap to 0. pending.ownersDone = 0; pending.index = m_pendingIndex.length++; m_pendingIndex[pending.index] = _operation; } // determine the bit to set for this owner. uint ownerIndexBit = 2**ownerIndex; // make sure we (the message sender) haven't confirmed this operation previously. if (pending.ownersDone & ownerIndexBit == 0) { Confirmation(msg.sender, _operation); // ok - check if count is enough to go ahead. if (pending.yetNeeded == 1) { // enough confirmations: reset and run interior. delete m_pendingIndex[m_pending[_operation].index]; delete m_pending[_operation]; return true; } else { // not enough: record that this owner in particular confirmed. pending.yetNeeded--; pending.ownersDone |= ownerIndexBit; } } } function reorganizeOwners() private { uint free = 1; while (free < m_numOwners) { while (free < m_numOwners && m_owners[free] != 0) free++; while (m_numOwners > 1 && m_owners[m_numOwners] == 0) m_numOwners--; if (free < m_numOwners && m_owners[m_numOwners] != 0 && m_owners[free] == 0) { m_owners[free] = m_owners[m_numOwners]; m_ownerIndex[m_owners[free]] = free; m_owners[m_numOwners] = 0; } } } function clearPending() internal { uint length = m_pendingIndex.length; for (uint i = 0; i < length; ++i) if (m_pendingIndex[i] != 0) delete m_pending[m_pendingIndex[i]]; delete m_pendingIndex; } // FIELDS // the number of owners that must confirm the same operation before it is run. uint public m_required; // pointer used to find a free slot in m_owners uint public m_numOwners; // list of owners uint[256] m_owners; uint constant c_maxOwners = 250; // index on the list of owners to allow reverse lookup mapping(uint => uint) m_ownerIndex; // the ongoing operations. mapping(bytes32 => PendingState) m_pending; bytes32[] m_pendingIndex; } // inheritable "property" contract that enables methods to be protected by placing a linear limit (specifiable) // on a particular resource per calendar day. is multiowned to allow the limit to be altered. resource that method // uses is specified in the modifier. contract daylimit is multiowned { // METHODS // constructor - stores initial daily limit and records the present day's index. function init_daylimit(uint _limit) only_uninitialized internal { m_dailyLimit = _limit; m_lastDay = today(); } // (re)sets the daily limit. needs many of the owners to confirm. doesn't alter the amount already spent today. function setDailyLimit(uint _newLimit) onlymanyowners(sha3(msg.data)) external { m_dailyLimit = _newLimit; } // resets the amount already spent today. needs many of the owners to confirm. function resetSpentToday() onlymanyowners(sha3(msg.data)) external { m_spentToday = 0; } // INTERNAL METHODS // checks to see if there is at least `_value` left from the daily limit today. if there is, subtracts it and // returns true. otherwise just returns false. function underLimit(uint _value) onlyowner internal returns (bool) { // reset the spend limit if we're on a different day to last time. if (today() > m_lastDay) { m_spentToday = 0; m_lastDay = today(); } // check to see if there's enough left - if so, subtract and return true. // overflow protection // dailyLimit check if (m_spentToday + _value >= m_spentToday && m_spentToday + _value <= m_dailyLimit) { m_spentToday += _value; return true; } return false; } // determines today's index. function today() private constant returns (uint) { return now / 1 days; } // FIELDS uint public m_dailyLimit; uint public m_spentToday; uint public m_lastDay; } // interface contract for multisig proxy contracts; see below for docs. contract multisig { // EVENTS // logged events: // Funds has arrived into the wallet (record how much). event Deposit(address _from, uint value); // Single transaction going out of the wallet (record who signed for it, how much, and to whom it's going). event SingleTransact(address owner, uint value, address to, bytes data, address created); // Multi-sig transaction going out of the wallet (record who signed for it last, the operation hash, how much, and to whom it's going). event MultiTransact(address owner, bytes32 operation, uint value, address to, bytes data, address created); // Confirmation still needed for a transaction. event ConfirmationNeeded(bytes32 operation, address initiator, uint value, address to, bytes data); // FUNCTIONS // TODO: document function changeOwner(address _from, address _to) external; function execute(address _to, uint _value, bytes _data) external returns (bytes32 o_hash); function confirm(bytes32 _h) public returns (bool o_success); } contract creator { function doCreate(uint _value, bytes _code) internal returns (address o_addr) { bool failed; assembly { o_addr := create(_value, add(_code, 0x20), mload(_code)) failed := iszero(extcodesize(o_addr)) } require(!failed); } } // usage: // bytes32 h = Wallet(w).from(oneOwner).execute(to, value, data); // Wallet(w).from(anotherOwner).confirm(h); contract WalletLibrary is multisig, multiowned, daylimit, creator { // TYPES // Transaction structure to remember details of transaction lest it need be saved for a later call. struct Transaction { address to; uint value; bytes data; } // METHODS // constructor - just pass on the owner array to the multiowned and // the limit to daylimit function WalletLibrary() { address[] owners; owners.push(address(0x0)); init_wallet(owners, 1, 0); } function init_wallet(address[] _owners, uint _required, uint _daylimit) only_uninitialized public { init_daylimit(_daylimit); init_multiowned(_owners, _required); } // kills the contract sending everything to `_to`. function kill(address _to) onlymanyowners(sha3(msg.data)) external { suicide(_to); } // gets called when no other function matches function() payable { // just being sent some cash? if (msg.value > 0) Deposit(msg.sender, msg.value); } // Outside-visible transact entry point. Executes transaction immediately if below daily spend limit. // If not, goes into multisig process. We provide a hash on return to allow the sender to provide // shortcuts for the other confirmations (allowing them to avoid replicating the _to, _value // and _data arguments). They still get the option of using them if they want, anyways. function execute(address _to, uint _value, bytes _data) onlyowner external returns (bytes32 o_hash) { // first, take the opportunity to check that we're under the daily limit. if ((_data.length == 0 && underLimit(_value)) || m_required == 1) { // yes - just execute the call. address created; if (_to == 0) { created = create(_value, _data); } else { require(_to.call.value(_value)(_data)); } SingleTransact(msg.sender, _value, _to, _data, created); } else { // determine our operation hash. o_hash = sha3(msg.data, block.number); // store if it's new if (m_txs[o_hash].to == 0 && m_txs[o_hash].value == 0 && m_txs[o_hash].data.length == 0) { m_txs[o_hash].to = _to; m_txs[o_hash].value = _value; m_txs[o_hash].data = _data; } if (!confirm(o_hash)) { ConfirmationNeeded(o_hash, msg.sender, _value, _to, _data); } } } function create(uint _value, bytes _code) internal returns (address o_addr) { return doCreate(_value, _code); } // confirm a transaction through just the hash. we use the previous transactions map, m_txs, in order // to determine the body of the transaction from the hash provided. function confirm(bytes32 _h) onlymanyowners(_h) public returns (bool o_success) { if (m_txs[_h].to != 0 || m_txs[_h].value != 0 || m_txs[_h].data.length != 0) { address created; if (m_txs[_h].to == 0) { created = create(m_txs[_h].value, m_txs[_h].data); } else { require(m_txs[_h].to.call.value(m_txs[_h].value)(m_txs[_h].data)); } MultiTransact(msg.sender, _h, m_txs[_h].value, m_txs[_h].to, m_txs[_h].data, created); delete m_txs[_h]; return true; } } // INTERNAL METHODS function clearPending() internal { uint length = m_pendingIndex.length; for (uint i = 0; i < length; ++i) delete m_txs[m_pendingIndex[i]]; super.clearPending(); } // FIELDS // pending transactions we have at present. mapping (bytes32 => Transaction) m_txs; }
the number of owners that must confirm the same operation before it is run.
uint public m_required;
1,737,697
[ 1, 5787, 1300, 434, 25937, 716, 1297, 6932, 326, 1967, 1674, 1865, 518, 353, 1086, 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 ]
[ 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, 11890, 1071, 312, 67, 4718, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./utils/ReentrancyGuard.sol"; import "./libs/LibUnitConverter.sol"; import "./libs/LibValidator.sol"; import "./libs/MarginalFunctionality.sol"; import "./OrionVault.sol"; /** * @title Exchange * @dev Exchange contract for the Orion Protocol * @author @wafflemakr */ /* Overflow safety: We do not use SafeMath and control overflows by not accepting large ints on input. Balances inside contract are stored as int192. Allowed input amounts are int112 or uint112: it is enough for all practically used tokens: for instance if decimal unit is 1e18, int112 allow to encode up to 2.5e15 decimal units. That way adding/subtracting any amount from balances won't overflow, since minimum number of operations to reach max int is practically infinite: ~1e24. Allowed prices are uint64. Note, that price is represented as price per 1e8 tokens. That means that amount*price always fit uint256, while amount*price/1e8 not only fit int192, but also can be added, subtracted without overflow checks: number of malicion operations to overflow ~1e13. */ contract Exchange is OrionVault, ReentrancyGuard { using LibValidator for LibValidator.Order; using SafeERC20 for IERC20; // Flags for updateOrders // All flags are explicit uint8 constant kSell = 0; uint8 constant kBuy = 1; // if 0 - then sell uint8 constant kCorrectMatcherFeeByOrderAmount = 2; // EVENTS event NewAssetTransaction( address indexed user, address indexed assetAddress, bool isDeposit, uint112 amount, uint64 timestamp ); event NewTrade( address indexed buyer, address indexed seller, address baseAsset, address quoteAsset, uint64 filledPrice, uint192 filledAmount, uint192 amountQuote ); // MAIN FUNCTIONS /** * @dev Since Exchange will work behind the Proxy contract it can not have constructor */ function initialize() public payable initializer { OwnableUpgradeSafe.__Ownable_init(); } /** * @dev set basic Exchange params * @param orionToken - base token address * @param priceOracleAddress - adress of PriceOracle contract * @param allowedMatcher - address which has authorization to match orders */ function setBasicParams(address orionToken, address priceOracleAddress, address allowedMatcher) public onlyOwner { require((orionToken != address(0)) && (priceOracleAddress != address(0)), "E15"); _orionToken = IERC20(orionToken); _oracleAddress = priceOracleAddress; _allowedMatcher = allowedMatcher; } /** * @dev set marginal settings * @param _collateralAssets - list of addresses of assets which may be used as collateral * @param _stakeRisk - risk coefficient for staken orion as uint8 (0=0, 255=1) * @param _liquidationPremium - premium for liquidator as uint8 (0=0, 255=1) * @param _priceOverdue - time after that price became outdated * @param _positionOverdue - time after that liabilities became overdue and may be liquidated */ function updateMarginalSettings(address[] calldata _collateralAssets, uint8 _stakeRisk, uint8 _liquidationPremium, uint64 _priceOverdue, uint64 _positionOverdue) public onlyOwner { collateralAssets = _collateralAssets; stakeRisk = _stakeRisk; liquidationPremium = _liquidationPremium; priceOverdue = _priceOverdue; positionOverdue = _positionOverdue; } /** * @dev set risk coefficients for collateral assets * @param assets - list of assets * @param risks - list of risks as uint8 (0=0, 255=1) */ function updateAssetRisks(address[] calldata assets, uint8[] calldata risks) public onlyOwner { for(uint256 i; i< assets.length; i++) assetRisks[assets[i]] = risks[i]; } /** * @dev Deposit ERC20 tokens to the exchange contract * @dev User needs to approve token contract first * @param amount asset amount to deposit in its base unit */ function depositAsset(address assetAddress, uint112 amount) external { //require(asset.transferFrom(msg.sender, address(this), uint256(amount)), "E6"); IERC20(assetAddress).safeTransferFrom(msg.sender, address(this), uint256(amount)); generalDeposit(assetAddress,amount); } /** * @notice Deposit ETH to the exchange contract * @dev deposit event will be emitted with the amount in decimal format (10^8) * @dev balance will be stored in decimal format too */ function deposit() external payable { generalDeposit(address(0), uint112(msg.value)); } /** * @dev internal implementation of deposits */ function generalDeposit(address assetAddress, uint112 amount) internal { address user = msg.sender; bool wasLiability = assetBalances[user][assetAddress]<0; int112 safeAmountDecimal = LibUnitConverter.baseUnitToDecimal( assetAddress, amount ); assetBalances[user][assetAddress] += safeAmountDecimal; if(amount>0) emit NewAssetTransaction(user, assetAddress, true, uint112(safeAmountDecimal), uint64(block.timestamp)); if(wasLiability) MarginalFunctionality.updateLiability(user, assetAddress, liabilities, uint112(safeAmountDecimal), assetBalances[user][assetAddress]); } /** * @dev Withdrawal of remaining funds from the contract back to the address * @param assetAddress address of the asset to withdraw * @param amount asset amount to withdraw in its base unit */ function withdraw(address assetAddress, uint112 amount) external nonReentrant { int112 safeAmountDecimal = LibUnitConverter.baseUnitToDecimal( assetAddress, amount ); address user = msg.sender; assetBalances[user][assetAddress] -= safeAmountDecimal; require(assetBalances[user][assetAddress]>=0, "E1w1"); //TODO require(checkPosition(user), "E1w2"); //TODO uint256 _amount = uint256(amount); if(assetAddress == address(0)) { (bool success, ) = user.call{value:_amount}(""); require(success, "E6w"); } else { IERC20(assetAddress).safeTransfer(user, _amount); } emit NewAssetTransaction(user, assetAddress, false, uint112(safeAmountDecimal), uint64(block.timestamp)); } /** * @dev Get asset balance for a specific address * @param assetAddress address of the asset to query * @param user user address to query */ function getBalance(address assetAddress, address user) public view returns (int192) { return assetBalances[user][assetAddress]; } /** * @dev Batch query of asset balances for a user * @param assetsAddresses array of addresses of the assets to query * @param user user address to query */ function getBalances(address[] memory assetsAddresses, address user) public view returns (int192[] memory balances) { balances = new int192[](assetsAddresses.length); for (uint256 i; i < assetsAddresses.length; i++) { balances[i] = assetBalances[user][assetsAddresses[i]]; } } /** * @dev Batch query of asset liabilities for a user * @param user user address to query */ function getLiabilities(address user) public view returns (MarginalFunctionality.Liability[] memory liabilitiesArray) { return liabilities[user]; } /** * @dev Return list of assets which can be used for collateral */ function getCollateralAssets() public view returns (address[] memory) { return collateralAssets; } /** * @dev get hash for an order * @dev we use order hash as order id to prevent double matching of the same order */ function getOrderHash(LibValidator.Order memory order) public pure returns (bytes32){ return order.getTypeValueHash(); } /** * @dev get filled amounts for a specific order */ function getFilledAmounts(bytes32 orderHash, LibValidator.Order memory order) public view returns (int192 totalFilled, int192 totalFeesPaid) { totalFilled = int192(filledAmounts[orderHash]); //It is safe to convert here: filledAmounts is result of ui112 additions totalFeesPaid = int192(uint256(order.matcherFee)*uint112(totalFilled)/order.amount); //matcherFee is u64; safe multiplication here } /** * @notice Settle a trade with two orders, filled price and amount * @dev 2 orders are submitted, it is necessary to match them: check conditions in orders for compliance filledPrice, filledAmountbuyOrderHash change balances on the contract respectively with buyer, seller, matcbuyOrderHashher * @param buyOrder structure of buy side orderbuyOrderHash * @param sellOrder structure of sell side order * @param filledPrice price at which the order was settled * @param filledAmount amount settled between orders */ function fillOrders( LibValidator.Order memory buyOrder, LibValidator.Order memory sellOrder, uint64 filledPrice, uint112 filledAmount ) public nonReentrant { // --- VARIABLES --- // // Amount of quote asset uint256 _amountQuote = uint256(filledAmount)*filledPrice/(10**8); require(_amountQuote<2**112-1, "E12G"); uint112 amountQuote = uint112(_amountQuote); // Order Hashes bytes32 buyOrderHash = buyOrder.getTypeValueHash(); bytes32 sellOrderHash = sellOrder.getTypeValueHash(); // --- VALIDATIONS --- // // Validate signatures using eth typed sign V1 require( LibValidator.checkOrdersInfo( buyOrder, sellOrder, msg.sender, filledAmount, filledPrice, block.timestamp, _allowedMatcher ), "E3G" ); // --- UPDATES --- // //updateFilledAmount filledAmounts[buyOrderHash] += filledAmount; //it is safe to add ui112 to each other to get i192 filledAmounts[sellOrderHash] += filledAmount; require(filledAmounts[buyOrderHash] <= buyOrder.amount, "E12B"); require(filledAmounts[sellOrderHash] <= sellOrder.amount, "E12S"); // Update User's balances updateOrderBalance(buyOrder, filledAmount, amountQuote, kBuy | kCorrectMatcherFeeByOrderAmount); updateOrderBalance(sellOrder, filledAmount, amountQuote, kSell | kCorrectMatcherFeeByOrderAmount); require(checkPosition(buyOrder.senderAddress), "Incorrect margin position for buyer"); require(checkPosition(sellOrder.senderAddress), "Incorrect margin position for seller"); emit NewTrade( buyOrder.senderAddress, sellOrder.senderAddress, buyOrder.baseAsset, buyOrder.quoteAsset, filledPrice, filledAmount, amountQuote ); } /** * @dev wrapper for LibValidator methods, may be deleted. */ function validateOrder(LibValidator.Order memory order) public pure returns (bool isValid) { isValid = order.isPersonalSign ? LibValidator.validatePersonal(order) : LibValidator.validateV3(order); } /** * @notice update user balances and send matcher fee * @param flags uint8, see constants for possible flags of order */ function updateOrderBalance( LibValidator.Order memory order, uint112 filledAmount, uint112 amountQuote, uint8 flags ) internal { address user = order.senderAddress; bool isBuyer = ((flags & kBuy) != 0); int192 temp; // this variable will be used for temporary variable storage (optimization purpose) { // Stack too deep bool isCorrectFee = ((flags & kCorrectMatcherFeeByOrderAmount) != 0); if(isCorrectFee) { // matcherFee: u64, filledAmount u128 => matcherFee*filledAmount fit u256 // result matcherFee fit u64 order.matcherFee = uint64(uint256(order.matcherFee)*filledAmount/order.amount); //rewrite in memory only } } if(filledAmount > 0) { if(!isBuyer) (filledAmount, amountQuote) = (amountQuote, filledAmount); (address firstAsset, address secondAsset) = isBuyer? (order.quoteAsset, order.baseAsset): (order.baseAsset, order.quoteAsset); int192 firstBalance = assetBalances[user][firstAsset]; int192 secondBalance = assetBalances[user][secondAsset]; // 'Stack too deep' correction // WAS: // bool firstInLiabilities = firstBalance<0; // bool secondInLiabilities = secondBalance<0; // NOW: // ENDFIX temp = assetBalances[user][firstAsset] - amountQuote; assetBalances[user][firstAsset] = temp; assetBalances[user][secondAsset] += filledAmount; // 'Stack too deep' correction // WAS: // if(!firstInLiabilities && (temp<0)){ // NOW: if(!(firstBalance<0) && (temp<0)){ // ENDFIX setLiability(user, firstAsset, temp); } // 'Stack too deep' correction // WAS: // if(secondInLiabilities) { // NOW: if(secondBalance<0) { // ENDFIX MarginalFunctionality.updateLiability(user, secondAsset, liabilities, filledAmount, assetBalances[user][secondAsset]); } } // User pay for fees bool feeAssetInLiabilities = assetBalances[user][order.matcherFeeAsset]<0; temp = assetBalances[user][order.matcherFeeAsset] - order.matcherFee; assetBalances[user][order.matcherFeeAsset] = temp; if(!feeAssetInLiabilities && (temp<0)) { setLiability(user, order.matcherFeeAsset, temp); } assetBalances[order.matcherAddress][order.matcherFeeAsset] += order.matcherFee; } /** * @notice users can cancel an order * @dev write an orderHash in the contract so that such an order cannot be filled (executed) */ /* Unused for now function cancelOrder(LibValidator.Order memory order) public { require(order.validateV3(), "E2"); require(msg.sender == order.senderAddress, "Not owner"); bytes32 orderHash = order.getTypeValueHash(); require(!isOrderCancelled(orderHash), "E4"); ( int192 totalFilled, //uint totalFeesPaid ) = getFilledAmounts(orderHash); if (totalFilled > 0) orderStatus[orderHash] = Status.PARTIALLY_CANCELLED; else orderStatus[orderHash] = Status.CANCELLED; emit OrderUpdate(orderHash, msg.sender, orderStatus[orderHash]); assert( orderStatus[orderHash] == Status.PARTIALLY_CANCELLED || orderStatus[orderHash] == Status.CANCELLED ); } */ /** * @dev check user marginal position (compare assets and liabilities) * @return isPositive - boolean whether liabilities are covered by collateral or not */ function checkPosition(address user) public view returns (bool) { if(liabilities[user].length == 0) return true; return calcPosition(user).state == MarginalFunctionality.PositionState.POSITIVE; } /** * @dev internal methods which collect all variables used my MarginalFunctionality to one structure * @param user user address to query * @return UsedConstants - MarginalFunctionality.UsedConstants structure */ function getConstants(address user) internal view returns (MarginalFunctionality.UsedConstants memory) { return MarginalFunctionality.UsedConstants(user, _oracleAddress, address(this), address(_orionToken), positionOverdue, priceOverdue, stakeRisk, liquidationPremium); } /** * @dev calc user marginal position (compare assets and liabilities) * @param user user address to query * @return position - MarginalFunctionality.Position structure */ function calcPosition(address user) public view returns (MarginalFunctionality.Position memory) { MarginalFunctionality.UsedConstants memory constants = getConstants(user); return MarginalFunctionality.calcPosition(collateralAssets, liabilities, assetBalances, assetRisks, constants); } /** * @dev method to cover some of overdue broker liabilities and get ORN in exchange same as liquidation or margin call * @param broker - broker which will be liquidated * @param redeemedAsset - asset, liability of which will be covered * @param amount - amount of covered asset */ function partiallyLiquidate(address broker, address redeemedAsset, uint112 amount) public { MarginalFunctionality.UsedConstants memory constants = getConstants(broker); MarginalFunctionality.partiallyLiquidate(collateralAssets, liabilities, assetBalances, assetRisks, constants, redeemedAsset, amount); } /** * @dev method to add liability * @param user - user which created liability * @param asset - liability asset * @param balance - current negative balance */ function setLiability(address user, address asset, int192 balance) internal { liabilities[user].push( MarginalFunctionality.Liability({ asset: asset, timestamp: uint64(block.timestamp), outstandingAmount: uint192(-balance)}) ); } /** * @dev method to update liability forcing removing any liabilities if balance > 0 * @param assetAddress - liability asset */ function forceUpdateLiability(address assetAddress) public { address user = msg.sender; MarginalFunctionality.updateLiability(user, assetAddress, liabilities, 0, assetBalances[user][assetAddress]); } /** * @dev revert on fallback function */ fallback() external { revert("E6"); } /* Error Codes E1: Insufficient Balance, flavor S - stake E2: Invalid Signature, flavor B,S - buyer, seller E3: Invalid Order Info, flavor G - general, M - wrong matcher, M2 unauthorized matcher, As - asset mismatch, AmB/AmS - amount mismatch (buyer,seller), PrB/PrS - price mismatch(buyer,seller), D - direction mismatch, E4: Order expired, flavor B,S - buyer,seller E5: Contract not active, E6: Transfer error E7: Incorrect state prior to liquidation E8: Liquidator doesn't satisfy requirements E9: Data for liquidation handling is outdated E10: Incorrect state after liquidation E11: Amount overflow E12: Incorrect filled amount, flavor G,B,S: general(overflow), buyer order overflow, seller order overflow E14: Authorization error, sfs - seizeFromStake E15: Wrong passed params */ } pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./libs/MarginalFunctionality.sol"; // Base contract which contain state variable of the first version of Exchange // deployed on mainnet. Changes of the state variables should be introduced // not in that contract but down the inheritance chain, to allow safe upgrades // More info about safe upgrades here: // https://blog.openzeppelin.com/the-state-of-smart-contract-upgrades/#upgrade-patterns contract ExchangeStorage { //order -> filledAmount mapping(bytes32 => uint192) public filledAmounts; // Get user balance by address and asset address mapping(address => mapping(address => int192)) internal assetBalances; // List of assets with negative balance for each user mapping(address => MarginalFunctionality.Liability[]) public liabilities; // List of assets which can be used as collateral and risk coefficients for them address[] internal collateralAssets; mapping(address => uint8) public assetRisks; // Risk coefficient for locked ORN uint8 public stakeRisk; // Liquidation premium uint8 public liquidationPremium; // Delays after which price and position become outdated uint64 public priceOverdue; uint64 public positionOverdue; // Base orion tokens (can be locked on stake) IERC20 _orionToken; // Address of price oracle contract address _oracleAddress; // Address from which matching of orders is allowed address _allowedMatcher; } pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "./Exchange.sol"; import "./utils/orionpool/periphery/interfaces/IOrionPoolV2Router02Ext.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; contract ExchangeWithOrionPool is Exchange { using SafeERC20 for IERC20; address public _orionpoolRouter; mapping (address => bool) orionpoolAllowances; modifier initialized { require(_orionpoolRouter!=address(0), "_orionpoolRouter is not set"); require(address(_orionToken)!=address(0), "_orionToken is not set"); require(_oracleAddress!=address(0), "_oracleAddress is not set"); require(_allowedMatcher!=address(0), "_allowedMatcher is not set"); _; } function _safeIncreaseAllowance(address token) internal { if(token != address(0) && !orionpoolAllowances[token]) { IERC20(token).safeIncreaseAllowance(_orionpoolRouter, 2**256-1); orionpoolAllowances[token] = true; } } /** * @dev set basic Exchange params * @param orionToken - base token address * @param priceOracleAddress - adress of PriceOracle contract * @param allowedMatcher - address which has authorization to match orders * @param orionpoolRouter - OrionPool Router address for changes through orionpool */ function setBasicParams(address orionToken, address priceOracleAddress, address allowedMatcher, address orionpoolRouter) public onlyOwner { _orionToken = IERC20(orionToken); _oracleAddress = priceOracleAddress; _allowedMatcher = allowedMatcher; _orionpoolRouter = orionpoolRouter; } // Important catch-all afunction that should only accept ethereum and don't allow do something with it // We accept ETH there only from out router. // If router sends some ETH to us - it's just swap completed, and we don't need to do smth // with ETH received - amount of ETH will be handled by ........... blah blah receive() external payable { require(msg.sender == _orionpoolRouter, "NPF"); } /** * @notice (partially) settle buy order with OrionPool as counterparty * @dev order and orionpool path are submitted, it is necessary to match them: check conditions in order for compliance filledPrice and filledAmount change tokens via OrionPool check that final price after exchange not worse than specified in order change balances on the contract respectively * @param order structure of buy side orderbuyOrderHash * @param filledAmount amount of purchaseable token * @param path array of assets addresses (each consequent asset pair is change pair) */ // Just to avoid stack too deep error; struct OrderExecutionData { uint64 filledPrice; uint112 amountQuote; uint tx_value; } function fillThroughOrionPool( LibValidator.Order memory order, uint112 filledAmount, uint64 blockchainFee, address[] calldata path ) public nonReentrant initialized { // Amount of quote asset uint256 _amountQuote = uint256(filledAmount)* order.price/(10**8); OrderExecutionData memory exec_data; if(order.buySide==1){ /* NOTE BUY ORDER ************************************************************/ (int112 amountQuoteBaseUnits, int112 filledAmountBaseUnits) = ( LibUnitConverter.decimalToBaseUnit(path[0], _amountQuote), LibUnitConverter.decimalToBaseUnit(path[path.length-1], filledAmount) ); // TODO: check // require(IERC20(order.quoteAsset).balanceOf(address(this)) >= uint(amountQuoteBaseUnits), "NEGT"); LibValidator.checkOrderSingleMatch(order, msg.sender, _allowedMatcher, filledAmount, block.timestamp, path, 1); // Change fee only after order validation if(blockchainFee < order.matcherFee) order.matcherFee = blockchainFee; _safeIncreaseAllowance(order.quoteAsset); if(order.quoteAsset == address(0)) exec_data.tx_value = uint(amountQuoteBaseUnits); try IOrionPoolV2Router02Ext(_orionpoolRouter).swapTokensForExactTokensAutoRoute{value: exec_data.tx_value}( uint(filledAmountBaseUnits), uint(amountQuoteBaseUnits), path, address(this)) // order.expiration/1000 returns(uint[] memory amounts) { exec_data.amountQuote = uint112(LibUnitConverter.baseUnitToDecimal( path[0], amounts[0] )); //require(_amountQuote<2**112-1, "E12G"); //TODO uint256 _filledPrice = exec_data.amountQuote*(10**8)/filledAmount; require(_filledPrice<= order.price, "EX"); //TODO exec_data.filledPrice = uint64(_filledPrice); // since _filledPrice<buyOrder.price it fits uint64 //uint112 amountQuote = uint112(_amountQuote); } catch(bytes memory) { filledAmount = 0; exec_data.filledPrice = order.price; } // Update User's balances updateOrderBalance(order, filledAmount, exec_data.amountQuote, kBuy); require(checkPosition(order.senderAddress), "Incorrect margin position for buyer"); }else{ /* NOTE: SELL ORDER **************************************************************************/ LibValidator.checkOrderSingleMatch(order, msg.sender, _allowedMatcher, filledAmount, block.timestamp, path, 0); // Change fee only after order validation if(blockchainFee < order.matcherFee) order.matcherFee = blockchainFee; (int112 amountQuoteBaseUnits, int112 filledAmountBaseUnits) = ( LibUnitConverter.decimalToBaseUnit(path[0], filledAmount), LibUnitConverter.decimalToBaseUnit(path[path.length-1], _amountQuote) ); _safeIncreaseAllowance(order.baseAsset); if(order.baseAsset == address(0)) exec_data.tx_value = uint(amountQuoteBaseUnits); try IOrionPoolV2Router02Ext(_orionpoolRouter).swapExactTokensForTokensAutoRoute{value: exec_data.tx_value}( uint(amountQuoteBaseUnits), uint(filledAmountBaseUnits), path, address(this)) // order.expiration/1000) returns (uint[] memory amounts) { exec_data.amountQuote = uint112(LibUnitConverter.baseUnitToDecimal( path[path.length-1], amounts[path.length-1] )); //require(_amountQuote<2**112-1, "E12G"); //TODO uint256 _filledPrice = exec_data.amountQuote*(10**8)/filledAmount; require(_filledPrice>= order.price, "EX"); //TODO exec_data.filledPrice = uint64(_filledPrice); // since _filledPrice<buyOrder.price it fits uint64 //uint112 amountQuote = uint112(_amountQuote); } catch(bytes memory) { filledAmount = 0; exec_data.filledPrice = order.price; } // Update User's balances updateOrderBalance(order, filledAmount, exec_data.amountQuote, kSell); require(checkPosition(order.senderAddress), "Incorrect margin position for seller"); } { // STack too deep workaround bytes32 orderHash = LibValidator.getTypeValueHash(order); uint192 total_amount = filledAmounts[orderHash]; // require(filledAmounts[orderHash]==0, "filledAmount already has some value"); // Old way total_amount += filledAmount; //it is safe to add ui112 to each other to get i192 require(total_amount >= filledAmount, "E12B_0"); require(total_amount <= order.amount, "E12B"); filledAmounts[orderHash] = total_amount; } emit NewTrade( order.senderAddress, address(1), //TODO //sellOrder.senderAddress, order.baseAsset, order.quoteAsset, exec_data.filledPrice, filledAmount, exec_data.amountQuote ); } /* BUY LIMIT ORN/USDT path[0] = USDT path[1] = ORN is_exact_spend = false; SELL LIMIT ORN/USDT path[0] = ORN path[1] = USDT is_exact_spend = true; */ event NewSwapOrionPool ( address user, address asset_spend, address asset_receive, int112 amount_spent, int112 amount_received ); function swapThroughOrionPool( uint112 amount_spend, uint112 amount_receive, address[] calldata path, bool is_exact_spend ) public nonReentrant initialized { (int112 amount_spend_base_units, int112 amount_receive_base_units) = ( LibUnitConverter.decimalToBaseUnit(path[0], amount_spend), LibUnitConverter.decimalToBaseUnit(path[path.length-1], amount_receive) ); // Checks require(getBalance(path[0], msg.sender) >= amount_spend, "NEGS1"); _safeIncreaseAllowance(path[0]); uint256 tx_value = path[0] == address(0) ? uint(amount_spend_base_units) : 0; uint[] memory amounts = is_exact_spend ? IOrionPoolV2Router02Ext(_orionpoolRouter).swapExactTokensForTokensAutoRoute {value: tx_value} ( uint(amount_spend_base_units), uint(amount_receive_base_units), path, address(this) ) : IOrionPoolV2Router02Ext(_orionpoolRouter).swapTokensForExactTokensAutoRoute {value: tx_value} ( uint(amount_receive_base_units), uint(amount_spend_base_units), path, address(this) ); // Anyway user gave amounts[0] and received amounts[len-1] int112 amount_actually_spent = LibUnitConverter.baseUnitToDecimal(path[0], amounts[0]); int112 amount_actually_received = LibUnitConverter.baseUnitToDecimal(path[path.length-1], amounts[path.length-1]); int192 balance_in_spent = assetBalances[msg.sender][path[0]]; require(amount_actually_spent >= 0 && balance_in_spent >= amount_actually_spent, "NEGS2_1"); balance_in_spent -= amount_actually_spent; assetBalances[msg.sender][path[0]] = balance_in_spent; require(checkPosition(msg.sender), "NEGS2_2"); address receiving_token = path[path.length - 1]; int192 balance_in_received = assetBalances[msg.sender][receiving_token]; bool is_need_update_liability = (balance_in_received < 0); balance_in_received += amount_actually_received; require(amount_actually_received >= 0 /* && balance_in_received >= amount_actually_received*/ , "NEGS2_3"); assetBalances[msg.sender][receiving_token] = balance_in_received; if(is_need_update_liability) MarginalFunctionality.updateLiability( msg.sender, receiving_token, liabilities, uint112(amount_actually_received), assetBalances[msg.sender][receiving_token] ); // TODO: remove emit NewSwapOrionPool ( msg.sender, path[0], receiving_token, amount_actually_spent, amount_actually_received ); } function increaseAllowance(address token) public { IERC20(token).safeIncreaseAllowance(_orionpoolRouter, 2**256-1); orionpoolAllowances[token] = true; } } pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "./utils/Ownable.sol"; import "./ExchangeStorage.sol"; abstract contract OrionVault is ExchangeStorage, OwnableUpgradeSafe { enum StakePhase{ NOTSTAKED, LOCKED, RELEASING, READYTORELEASE, FROZEN } struct Stake { uint64 amount; // 100m ORN in circulation fits uint64 StakePhase phase; uint64 lastActionTimestamp; } uint64 constant releasingDuration = 3600*24; mapping(address => Stake) private stakingData; /** * @dev Returns Stake with on-fly calculated StakePhase * @dev Note StakePhase may depend on time for some phases. * @param user address */ function getStake(address user) public view returns (Stake memory stake){ stake = stakingData[user]; if(stake.phase == StakePhase.RELEASING && (block.timestamp - stake.lastActionTimestamp) > releasingDuration) { stake.phase = StakePhase.READYTORELEASE; } } /** * @dev Returns stake balance * @dev Note, this balance may be already unlocked * @param user address */ function getStakeBalance(address user) public view returns (uint256) { return getStake(user).amount; } /** * @dev Returns stake phase * @param user address */ function getStakePhase(address user) public view returns (StakePhase) { return getStake(user).phase; } /** * @dev Returns locked or frozen stake balance only * @param user address */ function getLockedStakeBalance(address user) public view returns (uint256) { Stake memory stake = getStake(user); if(stake.phase == StakePhase.LOCKED || stake.phase == StakePhase.FROZEN) return stake.amount; return 0; } /** * @dev Change stake phase to frozen, blocking release * @param user address */ function postponeStakeRelease(address user) external onlyOwner{ Stake storage stake = stakingData[user]; stake.phase = StakePhase.FROZEN; } /** * @dev Change stake phase to READYTORELEASE * @param user address */ function allowStakeRelease(address user) external onlyOwner { Stake storage stake = stakingData[user]; stake.phase = StakePhase.READYTORELEASE; } /** * @dev Request stake unlock for msg.sender * @dev If stake phase is LOCKED, that changes phase to RELEASING * @dev If stake phase is READYTORELEASE, that withdraws stake to balance * @dev Note, both unlock and withdraw is impossible if user has liabilities */ function requestReleaseStake() public { address user = _msgSender(); Stake memory current = getStake(user); require(liabilities[user].length == 0, "Can not release stake: user has liabilities"); Stake storage stake = stakingData[_msgSender()]; if(current.phase == StakePhase.READYTORELEASE) { assetBalances[user][address(_orionToken)] += stake.amount; stake.amount = 0; stake.phase = StakePhase.NOTSTAKED; } else if (current.phase == StakePhase.LOCKED) { stake.phase = StakePhase.RELEASING; stake.lastActionTimestamp = uint64(block.timestamp); } else { revert("Can not release funds from this phase"); } } /** * @dev Lock some orions from exchange balance sheet * @param amount orions in 1e-8 units to stake */ function lockStake(uint64 amount) public { address user = _msgSender(); require(assetBalances[user][address(_orionToken)]>amount, "E1S"); Stake storage stake = stakingData[user]; assetBalances[user][address(_orionToken)] -= amount; stake.amount += amount; if(stake.phase != StakePhase.FROZEN) { stake.phase = StakePhase.LOCKED; //what is frozen should stay frozen } stake.lastActionTimestamp = uint64(block.timestamp); } /** * @dev send some orion from user's stake to receiver balance * @dev This function is used during liquidations, to reimburse liquidator * with orions from stake for decreasing liabilities. * @dev Note, this function is used by MarginalFunctionality library, thus * it can not be made private, but at the same time this function * can only be called by contract itself. That way msg.sender check * is critical. * @param user - user whose stake will be decreased * @param receiver - user which get orions * @param amount - amount of withdrawn tokens */ function seizeFromStake(address user, address receiver, uint64 amount) public { require(msg.sender == address(this), "E14"); Stake storage stake = stakingData[user]; require(stake.amount >= amount, "UX"); //TODO stake.amount -= amount; assetBalances[receiver][address(_orionToken)] += amount; } } pragma solidity 0.7.4; interface OrionVaultInterface { /** * @dev Returns locked or frozen stake balance only * @param user address */ function getLockedStakeBalance(address user) external view returns (uint64); /** * @dev send some orion from user's stake to receiver balance * @dev This function is used during liquidations, to reimburse liquidator * with orions from stake for decreasing liabilities. * @param user - user whose stake will be decreased * @param receiver - user which get orions * @param amount - amount of withdrawn tokens */ function seizeFromStake(address user, address receiver, uint64 amount) external; } pragma solidity 0.7.4; pragma experimental ABIEncoderV2; interface PriceOracleDataTypes { struct PriceDataOut { uint64 price; uint64 timestamp; } } pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "./PriceOracleDataTypes.sol"; interface PriceOracleInterface is PriceOracleDataTypes { function assetPrices(address) external view returns (PriceDataOut memory); function givePrices(address[] calldata assetAddresses) external view returns (PriceDataOut[] memory); } pragma solidity 0.7.4; import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import '@openzeppelin/contracts/math/SafeMath.sol'; library LibUnitConverter { using SafeMath for uint; /** @notice convert asset amount from8 decimals (10^8) to its base unit */ function decimalToBaseUnit(address assetAddress, uint amount) public view returns(int112 baseValue){ uint256 result; if(assetAddress == address(0)){ result = amount.mul(1 ether).div(10**8); // 18 decimals } else { ERC20 asset = ERC20(assetAddress); uint decimals = asset.decimals(); result = amount.mul(10**decimals).div(10**8); } require(result < uint256(type(int112).max), "LibUnitConverter: Too big value"); baseValue = int112(result); } /** @notice convert asset amount from its base unit to 8 decimals (10^8) */ function baseUnitToDecimal(address assetAddress, uint amount) public view returns(int112 decimalValue){ uint256 result; if(assetAddress == address(0)){ result = amount.mul(10**8).div(1 ether); } else { ERC20 asset = ERC20(assetAddress); uint decimals = asset.decimals(); result = amount.mul(10**8).div(10**decimals); } require(result < uint256(type(int112).max), "LibUnitConverter: Too big value"); decimalValue = int112(result); } } pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/cryptography/ECDSA.sol"; library LibValidator { using ECDSA for bytes32; string public constant DOMAIN_NAME = "Orion Exchange"; string public constant DOMAIN_VERSION = "1"; uint256 public constant CHAIN_ID = 1; bytes32 public constant DOMAIN_SALT = 0xf2d857f4a3edcb9b78b4d503bfe733db1e3f6cdc2b7971ee739626c97e86a557; bytes32 public constant EIP712_DOMAIN_TYPEHASH = keccak256( abi.encodePacked( "EIP712Domain(string name,string version,uint256 chainId,bytes32 salt)" ) ); bytes32 public constant ORDER_TYPEHASH = keccak256( abi.encodePacked( "Order(address senderAddress,address matcherAddress,address baseAsset,address quoteAsset,address matcherFeeAsset,uint64 amount,uint64 price,uint64 matcherFee,uint64 nonce,uint64 expiration,uint8 buySide)" ) ); bytes32 public constant DOMAIN_SEPARATOR = keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(DOMAIN_NAME)), keccak256(bytes(DOMAIN_VERSION)), CHAIN_ID, DOMAIN_SALT ) ); struct Order { address senderAddress; address matcherAddress; address baseAsset; address quoteAsset; address matcherFeeAsset; uint64 amount; uint64 price; uint64 matcherFee; uint64 nonce; uint64 expiration; uint8 buySide; // buy or sell bool isPersonalSign; bytes signature; } /** * @dev validate order signature */ function validateV3(Order memory order) public pure returns (bool) { bytes32 domainSeparator = DOMAIN_SEPARATOR; bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, getTypeValueHash(order) ) ); return digest.recover(order.signature) == order.senderAddress; } /** * @return hash order */ function getTypeValueHash(Order memory _order) internal pure returns (bytes32) { bytes32 orderTypeHash = ORDER_TYPEHASH; return keccak256( abi.encode( orderTypeHash, _order.senderAddress, _order.matcherAddress, _order.baseAsset, _order.quoteAsset, _order.matcherFeeAsset, _order.amount, _order.price, _order.matcherFee, _order.nonce, _order.expiration, _order.buySide ) ); } /** * @dev basic checks of matching orders against each other */ function checkOrdersInfo( Order memory buyOrder, Order memory sellOrder, address sender, uint256 filledAmount, uint256 filledPrice, uint256 currentTime, address allowedMatcher ) public pure returns (bool success) { buyOrder.isPersonalSign ? require(validatePersonal(buyOrder), "E2BP") : require(validateV3(buyOrder), "E2B"); sellOrder.isPersonalSign ? require(validatePersonal(sellOrder), "E2SP") : require(validateV3(sellOrder), "E2S"); // Same matcher address require( buyOrder.matcherAddress == sender && sellOrder.matcherAddress == sender, "E3M" ); if(allowedMatcher != address(0)) { require(buyOrder.matcherAddress == allowedMatcher, "E3M2"); } // Check matching assets require( buyOrder.baseAsset == sellOrder.baseAsset && buyOrder.quoteAsset == sellOrder.quoteAsset, "E3As" ); // Check order amounts require(filledAmount <= buyOrder.amount, "E3AmB"); require(filledAmount <= sellOrder.amount, "E3AmS"); // Check Price values require(filledPrice <= buyOrder.price, "E3"); require(filledPrice >= sellOrder.price, "E3"); // Check Expiration Time. Convert to seconds first require(buyOrder.expiration/1000 >= currentTime, "E4B"); require(sellOrder.expiration/1000 >= currentTime, "E4S"); require( buyOrder.buySide==1 && sellOrder.buySide==0, "E3D"); success = true; } function getEthSignedOrderHash(Order memory _order) public pure returns (bytes32) { return keccak256( abi.encodePacked( "order", _order.senderAddress, _order.matcherAddress, _order.baseAsset, _order.quoteAsset, _order.matcherFeeAsset, _order.amount, _order.price, _order.matcherFee, _order.nonce, _order.expiration, _order.buySide ) ).toEthSignedMessageHash(); } function validatePersonal(Order memory order) public pure returns (bool) { bytes32 digest = getEthSignedOrderHash(order); return digest.recover(order.signature) == order.senderAddress; } function checkOrderSingleMatch( Order memory buyOrder, address sender, address allowedMatcher, uint112 filledAmount, uint256 currentTime, address[] memory path, uint8 isBuySide ) public pure returns (bool success) { buyOrder.isPersonalSign ? require(validatePersonal(buyOrder), "E2BP") : require(validateV3(buyOrder), "E2B"); require(buyOrder.matcherAddress == sender && buyOrder.matcherAddress == allowedMatcher, "E3M2"); if(buyOrder.buySide==1){ require( buyOrder.baseAsset == path[path.length-1] && buyOrder.quoteAsset == path[0], "E3As" ); }else{ require( buyOrder.quoteAsset == path[path.length-1] && buyOrder.baseAsset == path[0], "E3As" ); } require(filledAmount <= buyOrder.amount, "E3AmB"); require(buyOrder.expiration/1000 >= currentTime, "E4B"); require( buyOrder.buySide==isBuySide, "E3D"); } } pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "../PriceOracleInterface.sol"; import "../OrionVaultInterface.sol"; library MarginalFunctionality { // We have the following approach: when liability is created we store // timestamp and size of liability. If the subsequent trade will deepen // this liability or won't fully cover it timestamp will not change. // However once outstandingAmount is covered we check wether balance on // that asset is positive or not. If not, liability still in the place but // time counter is dropped and timestamp set to `now`. struct Liability { address asset; uint64 timestamp; uint192 outstandingAmount; } enum PositionState { POSITIVE, NEGATIVE, // weighted position below 0 OVERDUE, // liability is not returned for too long NOPRICE, // some assets has no price or expired INCORRECT // some of the basic requirements are not met: too many liabilities, no locked stake, etc } struct Position { PositionState state; int256 weightedPosition; // sum of weighted collateral minus liabilities int256 totalPosition; // sum of unweighted (total) collateral minus liabilities int256 totalLiabilities; // total liabilities value } // Constants from Exchange contract used for calculations struct UsedConstants { address user; address _oracleAddress; address _orionVaultContractAddress; address _orionTokenAddress; uint64 positionOverdue; uint64 priceOverdue; uint8 stakeRisk; uint8 liquidationPremium; } /** * @dev method to multiply numbers with uint8 based percent numbers */ function uint8Percent(int192 _a, uint8 b) internal pure returns (int192 c) { int a = int256(_a); int d = 255; c = int192((a>65536) ? (a/d)*b : a*b/d ); } /** * @dev method to calc weighted and absolute collateral value * @notice it only count for assets in collateralAssets list, all other assets will add 0 to position. * @return outdated wether any price is outdated * @return weightedPosition in ORN * @return totalPosition in ORN */ function calcAssets(address[] storage collateralAssets, mapping(address => mapping(address => int192)) storage assetBalances, mapping(address => uint8) storage assetRisks, UsedConstants memory constants) internal view returns (bool outdated, int192 weightedPosition, int192 totalPosition) { uint256 collateralAssetsLength = collateralAssets.length; for(uint256 i = 0; i < collateralAssetsLength; i++) { address asset = collateralAssets[i]; if(assetBalances[constants.user][asset]<0) continue; // will be calculated in calcLiabilities (uint64 price, uint64 timestamp) = (1e8, 0xfffffff000000000); if(asset != constants._orionTokenAddress) { PriceOracleInterface.PriceDataOut memory assetPriceData = PriceOracleInterface(constants._oracleAddress).assetPrices(asset);//TODO givePrices (price, timestamp) = (assetPriceData.price, assetPriceData.timestamp); } // balance: i192, price u64 => balance*price fits i256 // since generally balance <= N*maxInt112 (where N is number operations with it), // assetValue <= N*maxInt112*maxUInt64/1e8. // That is if N<= 2**17 *1e8 = 1.3e13 we can neglect overflows here int192 assetValue = int192(int256(assetBalances[constants.user][asset])*price/1e8); // Overflows logic holds here as well, except that N is the number of // operations for all assets if(assetValue>0) { weightedPosition += uint8Percent(assetValue, assetRisks[asset]); totalPosition += assetValue; // if assetValue == 0 ignore outdated price outdated = outdated || ((timestamp + constants.priceOverdue) < block.timestamp); } } return (outdated, weightedPosition, totalPosition); } /** * @dev method to calc liabilities * @return outdated wether any price is outdated * @return overdue wether any liability is overdue * @return weightedPosition weightedLiability == totalLiability in ORN * @return totalPosition totalLiability in ORN */ function calcLiabilities(mapping(address => Liability[]) storage liabilities, mapping(address => mapping(address => int192)) storage assetBalances, UsedConstants memory constants ) internal view returns (bool outdated, bool overdue, int192 weightedPosition, int192 totalPosition) { uint256 liabilitiesLength = liabilities[constants.user].length; for(uint256 i = 0; i < liabilitiesLength; i++) { Liability storage liability = liabilities[constants.user][i]; PriceOracleInterface.PriceDataOut memory assetPriceData = PriceOracleInterface(constants._oracleAddress).assetPrices(liability.asset);//TODO givePrices (uint64 price, uint64 timestamp) = (assetPriceData.price, assetPriceData.timestamp); // balance: i192, price u64 => balance*price fits i256 // since generally balance <= N*maxInt112 (where N is number operations with it), // assetValue <= N*maxInt112*maxUInt64/1e8. // That is if N<= 2**17 *1e8 = 1.3e13 we can neglect overflows here int192 liabilityValue = int192( int256(assetBalances[constants.user][liability.asset]) *price/1e8 ); weightedPosition += liabilityValue; //already negative since balance is negative totalPosition += liabilityValue; overdue = overdue || ((liability.timestamp + constants.positionOverdue) < block.timestamp); outdated = outdated || ((timestamp + constants.priceOverdue) < block.timestamp); } return (outdated, overdue, weightedPosition, totalPosition); } /** * @dev method to calc Position * @return result position structure */ function calcPosition( address[] storage collateralAssets, mapping(address => Liability[]) storage liabilities, mapping(address => mapping(address => int192)) storage assetBalances, mapping(address => uint8) storage assetRisks, UsedConstants memory constants ) public view returns (Position memory result) { (bool outdatedPrice, int192 weightedPosition, int192 totalPosition) = calcAssets(collateralAssets, assetBalances, assetRisks, constants); (bool _outdatedPrice, bool overdue, int192 _weightedPosition, int192 _totalPosition) = calcLiabilities(liabilities, assetBalances, constants ); uint64 lockedAmount = OrionVaultInterface(constants._orionVaultContractAddress) .getLockedStakeBalance(constants.user); int192 weightedStake = uint8Percent(int192(lockedAmount), constants.stakeRisk); weightedPosition += weightedStake; totalPosition += lockedAmount; weightedPosition += _weightedPosition; totalPosition += _totalPosition; outdatedPrice = outdatedPrice || _outdatedPrice; bool incorrect = (liabilities[constants.user].length>0) && (lockedAmount==0); if(_totalPosition<0) { result.totalLiabilities = _totalPosition; } if(weightedPosition<0) { result.state = PositionState.NEGATIVE; } if(outdatedPrice) { result.state = PositionState.NOPRICE; } if(overdue) { result.state = PositionState.OVERDUE; } if(incorrect) { result.state = PositionState.INCORRECT; } result.weightedPosition = weightedPosition; result.totalPosition = totalPosition; } /** * @dev method removes liability */ function removeLiability(address user, address asset, mapping(address => Liability[]) storage liabilities) public { uint256 length = liabilities[user].length; for (uint256 i = 0; i < length; i++) { if (liabilities[user][i].asset == asset) { if (length>1) { liabilities[user][i] = liabilities[user][length - 1]; } liabilities[user].pop(); break; } } } /** * @dev method update liability * @notice implement logic for outstandingAmount (see Liability description) */ function updateLiability(address user, address asset, mapping(address => Liability[]) storage liabilities, uint112 depositAmount, int192 currentBalance) public { if(currentBalance>=0) { removeLiability(user,asset,liabilities); } else { uint256 i; uint256 liabilitiesLength=liabilities[user].length; for(; i<liabilitiesLength-1; i++) { if(liabilities[user][i].asset == asset) break; } Liability storage liability = liabilities[user][i]; if(depositAmount>=liability.outstandingAmount) { liability.outstandingAmount = uint192(-currentBalance); liability.timestamp = uint64(block.timestamp); } else { liability.outstandingAmount -= depositAmount; } } } /** * @dev partially liquidate, that is cover some asset liability to get ORN from meisbehaviour broker */ function partiallyLiquidate(address[] storage collateralAssets, mapping(address => Liability[]) storage liabilities, mapping(address => mapping(address => int192)) storage assetBalances, mapping(address => uint8) storage assetRisks, UsedConstants memory constants, address redeemedAsset, uint112 amount) public { //Note: constants.user - is broker who will be liquidated Position memory initialPosition = calcPosition(collateralAssets, liabilities, assetBalances, assetRisks, constants); require(initialPosition.state == PositionState.NEGATIVE || initialPosition.state == PositionState.OVERDUE , "E7"); address liquidator = msg.sender; require(assetBalances[liquidator][redeemedAsset]>=amount,"E8"); require(assetBalances[constants.user][redeemedAsset]<0,"E15"); assetBalances[liquidator][redeemedAsset] -= amount; assetBalances[constants.user][redeemedAsset] += amount; if(assetBalances[constants.user][redeemedAsset] >= 0) removeLiability(constants.user, redeemedAsset, liabilities); PriceOracleInterface.PriceDataOut memory assetPriceData = PriceOracleInterface(constants._oracleAddress).assetPrices(redeemedAsset); (uint64 price, uint64 timestamp) = (assetPriceData.price, assetPriceData.timestamp); require((timestamp + constants.priceOverdue) > block.timestamp, "E9"); //Price is outdated reimburseLiquidator(amount, price, liquidator, assetBalances, constants); Position memory finalPosition = calcPosition(collateralAssets, liabilities, assetBalances, assetRisks, constants); require( int(finalPosition.state)<3 && //POSITIVE,NEGATIVE or OVERDUE (finalPosition.weightedPosition>initialPosition.weightedPosition), "E10");//Incorrect state position after liquidation if(finalPosition.state == PositionState.POSITIVE) require (finalPosition.weightedPosition<10e8,"Can not liquidate to very positive state"); } /** * @dev reimburse liquidator with ORN: first from stake, than from broker balance */ function reimburseLiquidator( uint112 amount, uint64 price, address liquidator, mapping(address => mapping(address => int192)) storage assetBalances, UsedConstants memory constants) internal { int192 _orionAmount = int192(int256(amount)*price/1e8); _orionAmount += uint8Percent(_orionAmount,constants.liquidationPremium); //Liquidation premium require(_orionAmount == int64(_orionAmount), "E11"); int64 orionAmount = int64(_orionAmount); // There is only 100m Orion tokens, fits i64 int64 onBalanceOrion = int64(assetBalances[constants.user][constants._orionTokenAddress]); (int64 fromBalance, int64 fromStake) = (onBalanceOrion>orionAmount)? (orionAmount, 0) : (onBalanceOrion>0)? (onBalanceOrion, orionAmount-onBalanceOrion) : (0, orionAmount); if(fromBalance>0) { assetBalances[constants.user][constants._orionTokenAddress] -= int192(fromBalance); assetBalances[liquidator][constants._orionTokenAddress] += int192(fromBalance); } if(fromStake>0) { OrionVaultInterface(constants._orionVaultContractAddress).seizeFromStake(constants.user, liquidator, uint64(fromStake)); } } } /** Copied from @openzeppelin/contracts-ethereum-package to update pragma statements */ pragma solidity ^0.7.0; import "./Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } /** Copied from @openzeppelin/contracts-ethereum-package to update pragma statements */ pragma solidity ^0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } /** Copied from @openzeppelin/contracts-ethereum-package to update pragma statements */ pragma solidity ^0.7.0; import "./Context.sol"; import "./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. */ contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.7.4; contract ReentrancyGuard { bytes32 private constant REENTRANCY_MUTEX_POSITION = 0xe855346402235fdd185c890e68d2c4ecad599b88587635ee285bce2fda58dacb; string private constant ERROR_REENTRANT = "REENTRANCY_REENTRANT_CALL"; function getStorageBool(bytes32 position) internal view returns (bool data) { assembly { data := sload(position) } } function setStorageBool(bytes32 position, bool data) internal { assembly { sstore(position, data) } } modifier nonReentrant() { // Ensure mutex is unlocked require(!getStorageBool(REENTRANCY_MUTEX_POSITION), ERROR_REENTRANT); // Lock mutex before function call setStorageBool(REENTRANCY_MUTEX_POSITION,true); // Perform function call _; // Unlock mutex after function call setStorageBool(REENTRANCY_MUTEX_POSITION, false); } } pragma solidity >=0.6.2; interface IOrionPoolV2Router02Ext { function swapExactTokensForTokensAutoRoute( uint amountIn, uint amountOutMin, address[] calldata path, address to ) external payable returns (uint[] memory amounts); function swapTokensForExactTokensAutoRoute( uint amountOut, uint amountInMax, address[] calldata path, address to ) external payable returns (uint[] memory amounts); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } }
* @notice update user balances and send matcher fee @param flags uint8, see constants for possible flags of order/ Stack too deep matcherFee: u64, filledAmount u128 => matcherFee*filledAmount fit u256 result matcherFee fit u64 'Stack too deep' correction WAS: bool firstInLiabilities = firstBalance<0; bool secondInLiabilities = secondBalance<0; NOW: ENDFIX 'Stack too deep' correction WAS: if(!firstInLiabilities && (temp<0)){ NOW: ENDFIX 'Stack too deep' correction WAS: if(secondInLiabilities) { NOW: ENDFIX
function updateOrderBalance( LibValidator.Order memory order, uint112 filledAmount, uint112 amountQuote, uint8 flags ) internal { address user = order.senderAddress; bool isBuyer = ((flags & kBuy) != 0); { bool isCorrectFee = ((flags & kCorrectMatcherFeeByOrderAmount) != 0); if(isCorrectFee) { } } if(filledAmount > 0) { if(!isBuyer) (filledAmount, amountQuote) = (amountQuote, filledAmount); (address firstAsset, address secondAsset) = isBuyer? (order.quoteAsset, order.baseAsset): (order.baseAsset, order.quoteAsset); int192 firstBalance = assetBalances[user][firstAsset]; int192 secondBalance = assetBalances[user][secondAsset]; temp = assetBalances[user][firstAsset] - amountQuote; assetBalances[user][firstAsset] = temp; assetBalances[user][secondAsset] += filledAmount; if(!(firstBalance<0) && (temp<0)){ setLiability(user, firstAsset, temp); } if(secondBalance<0) { MarginalFunctionality.updateLiability(user, secondAsset, liabilities, filledAmount, assetBalances[user][secondAsset]); } } temp = assetBalances[user][order.matcherFeeAsset] - order.matcherFee; assetBalances[user][order.matcherFeeAsset] = temp; if(!feeAssetInLiabilities && (temp<0)) { setLiability(user, order.matcherFeeAsset, temp); } assetBalances[order.matcherAddress][order.matcherFeeAsset] += order.matcherFee; }
13,685,856
[ 1, 2725, 729, 324, 26488, 471, 1366, 4546, 14036, 282, 2943, 2254, 28, 16, 2621, 6810, 364, 3323, 2943, 434, 1353, 19, 225, 7283, 4885, 4608, 4546, 14667, 30, 582, 1105, 16, 6300, 6275, 582, 10392, 516, 4546, 14667, 13968, 6275, 4845, 582, 5034, 563, 4546, 14667, 4845, 582, 1105, 225, 296, 2624, 4885, 4608, 11, 15104, 225, 678, 3033, 30, 225, 1426, 1122, 382, 28762, 5756, 273, 1122, 13937, 32, 20, 31, 225, 1426, 2205, 382, 28762, 5756, 225, 273, 2205, 13937, 32, 20, 31, 225, 3741, 59, 30, 225, 7273, 4563, 225, 296, 2624, 4885, 4608, 11, 15104, 225, 678, 3033, 30, 225, 309, 12, 5, 3645, 382, 28762, 5756, 597, 261, 5814, 32, 20, 3719, 95, 225, 3741, 59, 30, 225, 7273, 4563, 225, 296, 2624, 4885, 4608, 11, 15104, 225, 678, 3033, 30, 225, 309, 12, 8538, 382, 28762, 5756, 13, 288, 225, 3741, 59, 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, 1089, 2448, 13937, 12, 203, 3639, 10560, 5126, 18, 2448, 3778, 1353, 16, 203, 3639, 2254, 17666, 6300, 6275, 16, 203, 3639, 2254, 17666, 3844, 10257, 16, 203, 3639, 2254, 28, 2943, 203, 565, 262, 2713, 288, 203, 3639, 1758, 729, 273, 1353, 18, 15330, 1887, 31, 203, 3639, 1426, 27057, 16213, 273, 14015, 7133, 473, 417, 38, 9835, 13, 480, 374, 1769, 203, 203, 203, 3639, 288, 203, 203, 5411, 1426, 353, 16147, 14667, 273, 14015, 7133, 473, 417, 16147, 6286, 14667, 858, 2448, 6275, 13, 480, 374, 1769, 203, 203, 5411, 309, 12, 291, 16147, 14667, 13, 203, 5411, 288, 203, 5411, 289, 203, 3639, 289, 203, 203, 3639, 309, 12, 13968, 6275, 405, 374, 13, 203, 3639, 288, 203, 203, 5411, 309, 12, 5, 291, 38, 16213, 13, 203, 2868, 261, 13968, 6275, 16, 3844, 10257, 13, 273, 261, 8949, 10257, 16, 6300, 6275, 1769, 203, 203, 5411, 261, 2867, 1122, 6672, 16, 1758, 2205, 6672, 13, 273, 27057, 16213, 35, 203, 4766, 7682, 261, 1019, 18, 6889, 6672, 16, 1353, 18, 1969, 6672, 4672, 203, 4766, 7682, 261, 1019, 18, 1969, 6672, 16, 1353, 18, 6889, 6672, 1769, 203, 5411, 509, 15561, 1122, 13937, 273, 3310, 38, 26488, 63, 1355, 6362, 3645, 6672, 15533, 203, 5411, 509, 15561, 2205, 13937, 273, 3310, 38, 26488, 63, 1355, 6362, 8538, 6672, 15533, 203, 203, 203, 5411, 1906, 273, 3310, 38, 26488, 63, 1355, 6362, 3645, 6672, 65, 300, 3844, 10257, 31, 203, 5411, 3310, 38, 26488, 63, 1355, 6362, 3645, 2 ]
./partial_match/3/0x0C5A7A2e4e62e9439bc6648fec75E344bB3d2d66/sources/Bond.sol
* @notice Constructs the Fat Bond ERC-20 contract./
constructor() public ERC20('FAB', 'FAB') {}
5,237,831
[ 1, 13262, 326, 478, 270, 605, 1434, 4232, 39, 17, 3462, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3885, 1435, 1071, 4232, 39, 3462, 2668, 2046, 38, 2187, 296, 2046, 38, 6134, 2618, 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 ]
./full_match/80001/0xeC23733e5a26a9d80EA3E1254072C1E46b3Ce326/sources/contracts/CareerBuild.sol
stores number of account woners in the block
uint256 public accountCounter;
856,497
[ 1, 19632, 1300, 434, 2236, 8462, 414, 316, 326, 1203, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 2236, 4789, 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 ]
pragma solidity ^0.4.21; /* Project: XPA Exchange - https://xpa.exchange Author : Luphia Chang - <span class="__cf_email__" data-cfemail="9bf7eeebf3f2fab5f8f3faf5fcdbf2e8eef5f8f7f4eeffb5f8f4f6">[email&#160;protected]</span> */ interface Token { function totalSupply() constant external returns (uint256 ts); function balanceOf(address _owner) constant external returns (uint256 balance); function transfer(address _to, uint256 _value) external returns (bool success); function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); function approve(address _spender, uint256 _value) external returns (bool success); function allowance(address _owner, address _spender) constant external returns (uint256 remaining); } contract SafeMath { function safeAdd(uint x, uint y) internal pure returns(uint) { uint256 z = x + y; require((z >= x) && (z >= y)); return z; } function safeSub(uint x, uint y) internal pure returns(uint) { require(x >= y); uint256 z = x - y; return z; } function safeMul(uint x, uint y) internal pure returns(uint) { uint z = x * y; require((x == 0) || (z / x == y)); return z; } function safeDiv(uint x, uint y) internal pure returns(uint) { require(y > 0); return x / y; } function random(uint N, uint salt) internal view returns(uint) { bytes32 hash = keccak256(block.number, msg.sender, salt); return uint(hash) % N; } } contract Authorization { mapping(address => address) public agentBooks; address public owner; address public operator; address public bank; bool public powerStatus = true; function Authorization() public { owner = msg.sender; operator = msg.sender; bank = msg.sender; } modifier onlyOwner { assert(msg.sender == owner); _; } modifier onlyOperator { assert(msg.sender == operator || msg.sender == owner); _; } modifier onlyActive { assert(powerStatus); _; } function powerSwitch( bool onOff_ ) public onlyOperator { powerStatus = onOff_; } function transferOwnership(address newOwner_) onlyOwner public { owner = newOwner_; } function assignOperator(address user_) public onlyOwner { operator = user_; agentBooks[bank] = user_; } function assignBank(address bank_) public onlyOwner { bank = bank_; } function assignAgent( address agent_ ) public { agentBooks[msg.sender] = agent_; } function isRepresentor( address representor_ ) public view returns(bool) { return agentBooks[representor_] == msg.sender; } function getUser( address representor_ ) internal view returns(address) { return isRepresentor(representor_) ? representor_ : msg.sender; } } /* Error Code 0: insufficient funds (user) 1: insufficient funds (contract) 2: invalid amount 3: invalid price */ /* 1. 檢驗是否指定代理用戶,若是且為合法代理人則將操作角色轉換為被代理人,否則操作角色不變 2. 檢驗此操作是否有存入 ETH,有則暫時紀錄存入額度 A,若掛單指定 fromToken 不是 ETH 則直接更新用戶 ETH 帳戶餘額 3. 檢驗此操作是否有存入 fromToken,有則暫時紀錄存入額度 A 4. 檢驗用戶 fromToken 帳戶餘額 + 存入額度 A 是否 >= Amount,若是送出 makeOrder 掛單事件,否則結束操作 5. 依照 fromToken、toToken 尋找可匹配的交易對 P 6. 找出 P 的最低價格單進行匹配,記錄匹配數量,送出 fillOrder 成交事件,並結算 maker 交易結果,若成交完還有掛單數量有剩且未達迴圈次數上限則重複此步驟 7. 統計步驟 6 總成交量、交易價差利潤、交易手續費 8. 若扣除總成交量後 Taker 掛單尚未撮合完,則將剩餘額度轉換為 Maker 單 9. 結算交易所手續費 10. 結算 Taker 交易結果 */ contract Baliv is SafeMath, Authorization { /* struct for exchange data */ struct linkedBook { uint256 amount; address nextUser; } /* business options */ mapping(address => uint256) public minAmount; uint256[3] public feerate = [0, 1 * (10 ** 15), 1 * (10 ** 15)]; uint256 public autoMatch = 10; uint256 public maxAmount = 10 ** 27; uint256 public maxPrice = 10 ** 36; address public XPAToken = 0x0090528aeb3a2b736b780fd1b6c478bb7e1d643170; /* exchange data */ mapping(address => mapping(address => mapping(uint256 => mapping(address => linkedBook)))) public orderBooks; mapping(address => mapping(address => mapping(uint256 => uint256))) public nextOrderPrice; mapping(address => mapping(address => uint256)) public priceBooks; /* user data */ mapping(address => mapping(address => uint256)) public balances; mapping(address => bool) internal manualWithdraw; /* event */ event eDeposit(address user,address token, uint256 amount); event eWithdraw(address user,address token, uint256 amount); event eMakeOrder(address fromToken, address toToken, uint256 price, address user, uint256 amount); event eFillOrder(address fromToken, address toToken, uint256 price, address user, uint256 amount); event eCancelOrder(address fromToken, address toToken, uint256 price, address user, uint256 amount); event Error(uint256 code); /* constructor */ function Baliv() public { minAmount[0] = 10 ** 16; } /* Operator Function function setup(uint256 autoMatch, uint256 maxAmount, uint256 maxPrice) external; function setMinAmount(address token, uint256 amount) external; function setFeerate(uint256[3] [maker, taker, autoWithdraw]) external; */ /* External Function function () public payable; function deposit(address token, address representor) external payable; function withdraw(address token, uint256 amount, address representor) external returns(bool); function userTakeOrder(address fromToken, address toToken, uint256 price, uint256 amount, address representor) external payable returns(bool); function userCancelOrder(address fromToken, address toToken, uint256 price, uint256 amount, address representor) external returns(bool); function caculateFee(address user, uint256 amount, uint8 role) external returns(uint256 remaining, uint256 fee); function trade(address fromToken, address toToken) external; function setManualWithdraw(bool) external; function getMinAmount(address) external returns(uint256); function getPrice(address fromToken, address toToken) external returns(uint256); */ /* Internal Function function depositAndFreeze(address token, address user) internal payable returns(uint256 amount); function checkBalance(address user, address token, uint256 amount, uint256 depositAmount) internal returns(bool); function checkAmount(address token, uint256 amount) internal returns(bool); function checkPriceAmount(uint256 price) internal returns(bool); function makeOrder(address fromToken, address toToken, uint256 price, uint256 amount, address user, uint256 depositAmount) internal returns(uint256 amount); function findAndTrade(address fromToken, address toToken, uint256 price, uint256 amount) internal returns(uint256[2] totalMatchAmount[fromToken, toToken], uint256[2] profit[fromToken, toToken]); function makeTrade(address fromToken, address toToken, uint256 price, uint256 bestPrice, uint256 remainingAmount) internal returns(uint256[3] [fillTaker, fillMaker, makerFee]); function makeTradeDetail(address fromToken, address toToken, uint256 price, uint256 bestPrice, address maker, uint256 remainingAmount) internal returns(uint256[3] [fillTaker, fillMaker, makerFee], bool makerFullfill); function caculateFill(uint256 provide, uint256 require, uint256 price, uint256 pairProvide) internal pure returns(uint256 fillAmount); function checkPricePair(uint256 price, uint256 bestPrice) internal pure returns(bool matched); function fillOrder(address fromToken, address toToken, uint256 price, uint256 amount) internal returns(uint256 fee); function transferToken(address user, address token, uint256 amount) internal returns(bool); function updateBalance(address user, address token, uint256 amount, bool addOrSub) internal returns(bool); function connectOrderPrice(address fromToken, address toToken, uint256 price, uint256 prevPrice) internal; function connectOrderUser(address fromToken, address toToken, uint256 price, address user) internal; function disconnectOrderPrice(address fromToken, address toToken, uint256 price) internal; function disconnectOrderUser(address fromToken, address toToken, uint256 price, address user) internal; function getNextOrderPrice(address fromToken, address toToken, uint256 price) internal view returns(uint256 price); function updateNextOrderPrice(address fromToken, address toToken, uint256 price, uint256 nextPrice) internal; function getNexOrdertUser(address fromToken, address toToken, uint256 price, address user) internal view returns(address nextUser); function getOrderAmount(address fromToken, address toToken, uint256 price, address user) internal view returns(uint256 amount); function updateNextOrderUser(address fromToken, address toToken, uint256 price, address user, address nextUser) internal; function updateOrderAmount(address fromToken, address toToken, uint256 price, address user, uint256 amount, bool addOrSub) internal; function logPrice(address fromToken, address toToken, uint256 price) internal; */ /* Operator function */ function setup( uint256 autoMatch_, uint256 maxAmount_, uint256 maxPrice_ ) onlyOperator public { autoMatch = autoMatch_; maxAmount = maxAmount_; maxPrice = maxPrice_; } function setMinAmount( address token_, uint256 amount_ ) onlyOperator public { minAmount[token_] = amount_; } function getMinAmount( address token_ ) public view returns(uint256) { return minAmount[token_] > 0 ? minAmount[token_] : minAmount[0]; } function setFeerate( uint256[3] feerate_ ) onlyOperator public { require(feerate_[0] < 0.05 ether && feerate_[1] < 0.05 ether && feerate_[2] < 0.05 ether); feerate = feerate_; } /* External function */ // fallback function () public payable { deposit(0, 0); } // deposit all allowance function deposit( address token_, address representor_ ) public payable onlyActive { address user = getUser(representor_); uint256 amount = depositAndFreeze(token_, user); if(amount > 0) { updateBalance(msg.sender, token_, amount, true); } } function withdraw( address token_, uint256 amount_, address representor_ ) public returns(bool) { address user = getUser(representor_); if(updateBalance(user, token_, amount_, false)) { require(transferToken(user, token_, amount_)); return true; } } /* function userMakeOrder( address fromToken_, address toToken_, uint256 price_, uint256 amount_, address representor_ ) public payable returns(bool) { // depositToken => makeOrder => updateBalance uint256 depositAmount = depositAndFreeze(fromToken_, representor_); if( checkAmount(fromToken_, amount_) && checkPriceAmount(price_) ) { address user = getUser(representor_); uint256 costAmount = makeOrder(fromToken_, toToken_, price_, amount_, user, depositAmount); // log event: MakeOrder eMakeOrder(fromToken_, toToken_, price_, user, amount_); if(costAmount < depositAmount) { updateBalance(user, fromToken_, safeSub(depositAmount, costAmount), true); } else if(costAmount > depositAmount) { updateBalance(user, fromToken_, safeSub(costAmount, depositAmount), false); } return true; } } */ function userTakeOrder( address fromToken_, address toToken_, uint256 price_, uint256 amount_, address representor_ ) public payable onlyActive returns(bool) { // checkBalance => findAndTrade => userMakeOrder => updateBalance address user = getUser(representor_); uint256 depositAmount = depositAndFreeze(fromToken_, user); if( checkAmount(fromToken_, amount_) && checkPriceAmount(price_) && checkBalance(user, fromToken_, amount_, depositAmount) ) { // log event: MakeOrder emit eMakeOrder(fromToken_, toToken_, price_, user, amount_); uint256[2] memory fillAmount; uint256[2] memory profit; (fillAmount, profit) = findAndTrade(fromToken_, toToken_, price_, amount_); uint256 fee; uint256 toAmount; uint256 orderAmount; if(fillAmount[0] > 0) { // log event: makeTrade emit eFillOrder(fromToken_, toToken_, price_, user, fillAmount[0]); toAmount = safeDiv(safeMul(fillAmount[0], price_), 1 ether); if(amount_ > fillAmount[0]) { orderAmount = safeSub(amount_, fillAmount[0]); makeOrder(fromToken_, toToken_, price_, amount_, user, depositAmount); } if(toAmount > 0) { (toAmount, fee) = caculateFee(user, toAmount, 1); profit[1] = profit[1] + fee; // save profit updateBalance(bank, fromToken_, profit[0], true); updateBalance(bank, toToken_, profit[1], true); // transfer to Taker if(manualWithdraw[user]) { updateBalance(user, toToken_, toAmount, true); } else { transferToken(user, toToken_, toAmount); } } } else { orderAmount = amount_; makeOrder(fromToken_, toToken_, price_, orderAmount, user, depositAmount); } // update balance if(amount_ > depositAmount) { updateBalance(user, fromToken_, safeSub(amount_, depositAmount), false); } else if(amount_ < depositAmount) { updateBalance(user, fromToken_, safeSub(depositAmount, amount_), true); } return true; } } function userCancelOrder( address fromToken_, address toToken_, uint256 price_, uint256 amount_, address representor_ ) public returns(bool) { // updateOrderAmount => disconnectOrderUser => withdraw address user = getUser(representor_); uint256 amount = getOrderAmount(fromToken_, toToken_, price_, user); amount = amount > amount_ ? amount_ : amount; if(amount > 0) { // log event: CancelOrder emit eCancelOrder(fromToken_, toToken_, price_, user, amount); updateOrderAmount(fromToken_, toToken_, price_, user, amount, false); if(getOrderAmount(fromToken_, toToken_, price_, user) == 0) { disconnectOrderUser(fromToken_, toToken_, price_, user); } if(manualWithdraw[user]) { updateBalance(user, fromToken_, amount, true); } else { transferToken(user, fromToken_, amount); } return true; } } /* role - 0: maker 1: taker */ function caculateFee( address user_, uint256 amount_, uint8 role_ ) public view returns(uint256, uint256) { uint256 myXPABalance = Token(XPAToken).balanceOf(user_); uint256 myFeerate = manualWithdraw[user_] ? feerate[role_] : feerate[role_] + feerate[2]; myFeerate = myXPABalance > 1000000 ether ? myFeerate * 0.5 ether / 1 ether : myXPABalance > 100000 ether ? myFeerate * 0.6 ether / 1 ether : myXPABalance > 10000 ether ? myFeerate * 0.8 ether / 1 ether : myFeerate; uint256 fee = safeDiv(safeMul(amount_, myFeerate), 1 ether); uint256 toAmount = safeSub(amount_, fee); return(toAmount, fee); } function trade( address fromToken_, address toToken_ ) public onlyActive { // Don&#39;t worry, this takes maker feerate uint256 takerPrice = getNextOrderPrice(fromToken_, toToken_, 0); address taker = getNextOrderUser(fromToken_, toToken_, takerPrice, 0); uint256 takerAmount = getOrderAmount(fromToken_, toToken_, takerPrice, taker); /* fillAmount[0] = TakerFill fillAmount[1] = MakerFill profit[0] = fromTokenProfit profit[1] = toTokenProfit */ uint256[2] memory fillAmount; uint256[2] memory profit; (fillAmount, profit) = findAndTrade(fromToken_, toToken_, takerPrice, takerAmount); if(fillAmount[0] > 0) { profit[1] = profit[1] + fillOrder(fromToken_, toToken_, takerPrice, taker, fillAmount[0]); // save profit to operator updateBalance(msg.sender, fromToken_, profit[0], true); updateBalance(msg.sender, toToken_, profit[1], true); } } function setManualWithdraw( bool manual_ ) public { manualWithdraw[msg.sender] = manual_; } function getPrice( address fromToken_, address toToken_ ) public view returns(uint256) { if(uint256(fromToken_) >= uint256(toToken_)) { return priceBooks[fromToken_][toToken_]; } else { return priceBooks[toToken_][fromToken_] > 0 ? safeDiv(10 ** 36, priceBooks[toToken_][fromToken_]) : 0; } } /* Internal Function */ // deposit all allowance function depositAndFreeze( address token_, address user ) internal returns(uint256) { uint256 amount; if(token_ == address(0)) { // log event: Deposit emit eDeposit(user, address(0), msg.value); amount = msg.value; return amount; } else { if(msg.value > 0) { // log event: Deposit emit eDeposit(user, address(0), msg.value); updateBalance(user, address(0), msg.value, true); } amount = Token(token_).allowance(msg.sender, this); if( amount > 0 && Token(token_).transferFrom(msg.sender, this, amount) ) { // log event: Deposit emit eDeposit(user, token_, amount); return amount; } } } function checkBalance( address user_, address token_, uint256 amount_, uint256 depositAmount_ ) internal returns(bool) { if(safeAdd(balances[user_][token_], depositAmount_) >= amount_) { return true; } else { emit Error(0); return false; } } function checkAmount( address token_, uint256 amount_ ) internal returns(bool) { uint256 min = getMinAmount(token_); if(amount_ > maxAmount || amount_ < min) { emit Error(2); return false; } else { return true; } } function checkPriceAmount( uint256 price_ ) internal returns(bool) { if(price_ == 0 || price_ > maxPrice) { emit Error(3); return false; } else { return true; } } function makeOrder( address fromToken_, address toToken_, uint256 price_, uint256 amount_, address user_, uint256 depositAmount_ ) internal returns(uint256) { if(checkBalance(user_, fromToken_, amount_, depositAmount_)) { updateOrderAmount(fromToken_, toToken_, price_, user_, amount_, true); connectOrderPrice(fromToken_, toToken_, price_, 0); connectOrderUser(fromToken_, toToken_, price_, user_); return amount_; } else { return 0; } } function findAndTrade( address fromToken_, address toToken_, uint256 price_, uint256 amount_ ) internal returns(uint256[2], uint256[2]) { /* totalMatchAmount[0]: Taker total match amount totalMatchAmount[1]: Maker total match amount profit[0]: fromToken profit profit[1]: toToken profit matchAmount[0]: Taker match amount matchAmount[1]: Maker match amount */ uint256[2] memory totalMatchAmount; uint256[2] memory profit; uint256[3] memory matchAmount; uint256 toAmount; uint256 remaining = amount_; uint256 matches = 0; uint256 prevBestPrice = 0; uint256 bestPrice = getNextOrderPrice(toToken_, fromToken_, prevBestPrice); for(; matches < autoMatch && remaining > 0;) { matchAmount = makeTrade(fromToken_, toToken_, price_, bestPrice, remaining); if(matchAmount[0] > 0) { remaining = safeSub(remaining, matchAmount[0]); totalMatchAmount[0] = safeAdd(totalMatchAmount[0], matchAmount[0]); totalMatchAmount[1] = safeAdd(totalMatchAmount[1], matchAmount[1]); profit[0] = safeAdd(profit[0], matchAmount[2]); // for next loop matches++; prevBestPrice = bestPrice; bestPrice = getNextOrderPrice(toToken_, fromToken_, prevBestPrice); } else { break; } } if(totalMatchAmount[0] > 0) { // log price logPrice(toToken_, fromToken_, prevBestPrice); // calculating spread profit toAmount = safeDiv(safeMul(totalMatchAmount[0], price_), 1 ether); profit[1] = safeSub(totalMatchAmount[1], toAmount); if(totalMatchAmount[1] >= safeDiv(safeMul(amount_, price_), 1 ether)) { // fromProfit += amount_ - takerFill; profit[0] = profit[0] + amount_ - totalMatchAmount[0]; // fullfill Taker order totalMatchAmount[0] = amount_; } else { toAmount = totalMatchAmount[1]; // fromProfit += takerFill - (toAmount / price_ * 1 ether) profit[0] = profit[0] + totalMatchAmount[0] - (toAmount * 1 ether /price_); // (real) takerFill = toAmount / price_ * 1 ether totalMatchAmount[0] = safeDiv(safeMul(toAmount, 1 ether), price_); } } return (totalMatchAmount, profit); } function makeTrade( address fromToken_, address toToken_, uint256 price_, uint256 bestPrice_, uint256 remaining_ ) internal returns(uint256[3]) { if(checkPricePair(price_, bestPrice_)) { address prevMaker = address(0); address maker = getNextOrderUser(toToken_, fromToken_, bestPrice_, 0); uint256 remaining = remaining_; /* totalFill[0]: Total Taker fillAmount totalFill[1]: Total Maker fillAmount totalFill[2]: Total Maker fee */ uint256[3] memory totalFill; for(uint256 i = 0; i < autoMatch && remaining > 0 && maker != address(0); i++) { uint256[3] memory fill; bool fullfill; (fill, fullfill) = makeTradeDetail(fromToken_, toToken_, price_, bestPrice_, maker, remaining); if(fill[0] > 0) { if(fullfill) { disconnectOrderUser(toToken_, fromToken_, bestPrice_, maker); } remaining = safeSub(remaining, fill[0]); totalFill[0] = safeAdd(totalFill[0], fill[0]); totalFill[1] = safeAdd(totalFill[1], fill[1]); totalFill[2] = safeAdd(totalFill[2], fill[2]); prevMaker = maker; maker = getNextOrderUser(toToken_, fromToken_, bestPrice_, prevMaker); if(maker == address(0)) { break; } } else { break; } } } return totalFill; } function makeTradeDetail( address fromToken_, address toToken_, uint256 price_, uint256 bestPrice_, address maker_, uint256 remaining_ ) internal returns(uint256[3], bool) { /* fillAmount[0]: Taker fillAmount fillAmount[1]: Maker fillAmount fillAmount[2]: Maker fee */ uint256[3] memory fillAmount; uint256 takerProvide = remaining_; uint256 takerRequire = safeDiv(safeMul(takerProvide, price_), 1 ether); uint256 makerProvide = getOrderAmount(toToken_, fromToken_, bestPrice_, maker_); uint256 makerRequire = safeDiv(safeMul(makerProvide, bestPrice_), 1 ether); fillAmount[0] = caculateFill(takerProvide, takerRequire, price_, makerProvide); fillAmount[1] = caculateFill(makerProvide, makerRequire, bestPrice_, takerProvide); fillAmount[2] = fillOrder(toToken_, fromToken_, bestPrice_, maker_, fillAmount[1]); return (fillAmount, (makerRequire <= takerProvide)); } function caculateFill( uint256 provide_, uint256 require_, uint256 price_, uint256 pairProvide_ ) internal pure returns(uint256) { return require_ > pairProvide_ ? safeDiv(safeMul(pairProvide_, 1 ether), price_) : provide_; } function checkPricePair( uint256 price_, uint256 bestPrice_ ) internal pure returns(bool) { if(bestPrice_ < price_) { return checkPricePair(bestPrice_, price_); } else if(bestPrice_ < 1 ether) { return true; } else if(price_ > 1 ether) { return false; } else { return price_ * bestPrice_ <= 1 ether * 1 ether; } } function fillOrder( address fromToken_, address toToken_, uint256 price_, address user_, uint256 amount_ ) internal returns(uint256) { // log event: fillOrder emit eFillOrder(fromToken_, toToken_, price_, user_, amount_); uint256 toAmount = safeDiv(safeMul(amount_, price_), 1 ether); uint256 fee; updateOrderAmount(fromToken_, toToken_, price_, user_, amount_, false); (toAmount, fee) = caculateFee(user_, toAmount, 0); if(manualWithdraw[user_]) { updateBalance(user_, toToken_, toAmount, true); } else { transferToken(user_, toToken_, toAmount); } return fee; } function transferToken( address user_, address token_, uint256 amount_ ) internal returns(bool) { if(token_ == address(0)) { if(address(this).balance < amount_) { emit Error(1); return false; } else { // log event: Withdraw emit eWithdraw(user_, token_, amount_); user_.transfer(amount_); return true; } } else if(Token(token_).transfer(user_, amount_)) { // log event: Withdraw emit eWithdraw(user_, token_, amount_); return true; } else { emit Error(1); return false; } } function updateBalance( address user_, address token_, uint256 amount_, bool addOrSub_ ) internal returns(bool) { if(addOrSub_) { balances[user_][token_] = safeAdd(balances[user_][token_], amount_); } else { if(checkBalance(user_, token_, amount_, 0)){ balances[user_][token_] = safeSub(balances[user_][token_], amount_); return true; } else { return false; } } } function connectOrderPrice( address fromToken_, address toToken_, uint256 price_, uint256 prev_ ) internal { if(checkPriceAmount(price_)) { uint256 prevPrice = getNextOrderPrice(fromToken_, toToken_, prev_); uint256 nextPrice = getNextOrderPrice(fromToken_, toToken_, prevPrice); if(prev_ != price_ && prevPrice != price_ && nextPrice != price_) { if(price_ < prevPrice) { updateNextOrderPrice(fromToken_, toToken_, prev_, price_); updateNextOrderPrice(fromToken_, toToken_, price_, prevPrice); } else if(nextPrice == 0) { updateNextOrderPrice(fromToken_, toToken_, prevPrice, price_); } else { connectOrderPrice(fromToken_, toToken_, price_, prevPrice); } } } } function connectOrderUser( address fromToken_, address toToken_, uint256 price_, address user_ ) internal { address firstUser = getNextOrderUser(fromToken_, toToken_, price_, 0); if(user_ != address(0) && user_ != firstUser) { updateNextOrderUser(fromToken_, toToken_, price_, 0, user_); if(firstUser != address(0)) { updateNextOrderUser(fromToken_, toToken_, price_, user_, firstUser); } } } function disconnectOrderPrice( address fromToken_, address toToken_, uint256 price_ ) internal { uint256 currPrice = getNextOrderPrice(fromToken_, toToken_, 0); uint256 nextPrice = getNextOrderPrice(fromToken_, toToken_, currPrice); if(price_ == currPrice) { updateNextOrderPrice(fromToken_, toToken_, 0, nextPrice); } } function disconnectOrderUser( address fromToken_, address toToken_, uint256 price_, address user_ ) internal { if(user_ == address(0)) { return; } address currUser = getNextOrderUser(fromToken_, toToken_, price_, address(0)); address nextUser = getNextOrderUser(fromToken_, toToken_, price_, currUser); if(currUser == user_) { updateNextOrderUser(fromToken_, toToken_, price_, address(0), nextUser); if(nextUser == address(0)) { disconnectOrderPrice(fromToken_, toToken_, price_); } } } function getNextOrderPrice( address fromToken_, address toToken_, uint256 price_ ) internal view returns(uint256) { return nextOrderPrice[fromToken_][toToken_][price_]; } function updateNextOrderPrice( address fromToken_, address toToken_, uint256 price_, uint256 nextPrice_ ) internal { nextOrderPrice[fromToken_][toToken_][price_] = nextPrice_; } function getNextOrderUser( address fromToken_, address toToken_, uint256 price_, address user_ ) internal view returns(address) { return orderBooks[fromToken_][toToken_][price_][user_].nextUser; } function getOrderAmount( address fromToken_, address toToken_, uint256 price_, address user_ ) internal view returns(uint256) { return orderBooks[fromToken_][toToken_][price_][user_].amount; } function updateNextOrderUser( address fromToken_, address toToken_, uint256 price_, address user_, address nextUser_ ) internal { orderBooks[fromToken_][toToken_][price_][user_].nextUser = nextUser_; } function updateOrderAmount( address fromToken_, address toToken_, uint256 price_, address user_, uint256 amount_, bool addOrSub_ ) internal { if(addOrSub_) { orderBooks[fromToken_][toToken_][price_][user_].amount = safeAdd(orderBooks[fromToken_][toToken_][price_][user_].amount, amount_); } else { orderBooks[fromToken_][toToken_][price_][user_].amount = safeSub(orderBooks[fromToken_][toToken_][price_][user_].amount, amount_); } } function logPrice( address fromToken_, address toToken_, uint256 price_ ) internal { if(price_ > 0) { if(uint256(fromToken_) >= uint256(toToken_)) { priceBooks[fromToken_][toToken_] = price_; } else { priceBooks[toToken_][fromToken_] = safeDiv(10 ** 36, price_); } } } }
/ for next loop log price calculating spread profit fromProfit += amount_ - takerFill; fullfill Taker order fromProfit += takerFill - (toAmount / price_ * 1 ether) (real) takerFill = toAmount / price_ * 1 ether
function findAndTrade( address fromToken_, address toToken_, uint256 price_, uint256 amount_ ) internal returns(uint256[2], uint256[2]) { totalMatchAmount[0]: Taker total match amount totalMatchAmount[1]: Maker total match amount profit[0]: fromToken profit profit[1]: toToken profit matchAmount[0]: Taker match amount matchAmount[1]: Maker match amount uint256[2] memory totalMatchAmount; uint256[2] memory profit; uint256[3] memory matchAmount; uint256 toAmount; uint256 remaining = amount_; uint256 matches = 0; uint256 prevBestPrice = 0; uint256 bestPrice = getNextOrderPrice(toToken_, fromToken_, prevBestPrice); for(; matches < autoMatch && remaining > 0;) { matchAmount = makeTrade(fromToken_, toToken_, price_, bestPrice, remaining); if(matchAmount[0] > 0) { remaining = safeSub(remaining, matchAmount[0]); totalMatchAmount[0] = safeAdd(totalMatchAmount[0], matchAmount[0]); totalMatchAmount[1] = safeAdd(totalMatchAmount[1], matchAmount[1]); profit[0] = safeAdd(profit[0], matchAmount[2]); matches++; prevBestPrice = bestPrice; bestPrice = getNextOrderPrice(toToken_, fromToken_, prevBestPrice); break; } } if(totalMatchAmount[0] > 0) { logPrice(toToken_, fromToken_, prevBestPrice); toAmount = safeDiv(safeMul(totalMatchAmount[0], price_), 1 ether); profit[1] = safeSub(totalMatchAmount[1], toAmount); if(totalMatchAmount[1] >= safeDiv(safeMul(amount_, price_), 1 ether)) { profit[0] = profit[0] + amount_ - totalMatchAmount[0]; totalMatchAmount[0] = amount_; toAmount = totalMatchAmount[1]; profit[0] = profit[0] + totalMatchAmount[0] - (toAmount * 1 ether /price_); totalMatchAmount[0] = safeDiv(safeMul(toAmount, 1 ether), price_); } } return (totalMatchAmount, profit); }
10,634,995
[ 1, 19, 364, 1024, 2798, 613, 6205, 21046, 15103, 450, 7216, 628, 626, 7216, 1011, 3844, 67, 300, 268, 6388, 8026, 31, 1983, 5935, 399, 6388, 1353, 628, 626, 7216, 1011, 268, 6388, 8026, 300, 261, 869, 6275, 342, 6205, 67, 225, 404, 225, 2437, 13, 261, 7688, 13, 268, 6388, 8026, 273, 358, 6275, 342, 6205, 67, 225, 404, 225, 2437, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1104, 1876, 22583, 12, 203, 3639, 1758, 628, 1345, 67, 16, 203, 3639, 1758, 358, 1345, 67, 16, 203, 3639, 2254, 5034, 6205, 67, 16, 203, 3639, 2254, 5034, 3844, 67, 203, 565, 262, 203, 3639, 2713, 203, 565, 1135, 12, 11890, 5034, 63, 22, 6487, 2254, 5034, 63, 22, 5717, 288, 203, 5411, 2078, 2060, 6275, 63, 20, 14542, 399, 6388, 2078, 845, 3844, 203, 5411, 2078, 2060, 6275, 63, 21, 14542, 490, 6388, 2078, 845, 3844, 203, 5411, 450, 7216, 63, 20, 14542, 628, 1345, 450, 7216, 203, 5411, 450, 7216, 63, 21, 14542, 358, 1345, 450, 7216, 203, 5411, 845, 6275, 63, 20, 14542, 399, 6388, 845, 3844, 203, 5411, 845, 6275, 63, 21, 14542, 490, 6388, 845, 3844, 203, 3639, 2254, 5034, 63, 22, 65, 3778, 2078, 2060, 6275, 31, 203, 3639, 2254, 5034, 63, 22, 65, 3778, 450, 7216, 31, 203, 3639, 2254, 5034, 63, 23, 65, 3778, 845, 6275, 31, 203, 3639, 2254, 5034, 358, 6275, 31, 203, 3639, 2254, 5034, 4463, 273, 3844, 67, 31, 203, 3639, 2254, 5034, 1885, 273, 374, 31, 203, 3639, 2254, 5034, 2807, 14173, 5147, 273, 374, 31, 203, 3639, 2254, 5034, 3796, 5147, 273, 6927, 2448, 5147, 12, 869, 1345, 67, 16, 628, 1345, 67, 16, 2807, 14173, 5147, 1769, 203, 3639, 364, 12, 31, 1885, 411, 3656, 2060, 597, 4463, 405, 374, 30943, 288, 203, 5411, 845, 6275, 273, 1221, 22583, 12, 2080, 1345, 67, 16, 358, 1345, 67, 16, 6205, 67, 16, 3796, 5147, 16, 4463, 1769, 2 ]
pragma solidity ^0.4.15; /** * @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 SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); 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[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @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) { // 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 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title SimpleToken * @dev Very simple ERC20 Token example, where all tokens are pre-assigned to the creator. * Note they can later distribute these tokens as they wish using `transfer` and other * `StandardToken` functions. */ contract OpportyToken is StandardToken { string public constant name = "OpportyToken"; string public constant symbol = "OPP"; uint8 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 1000000000 * (10 ** uint256(decimals)); /** * @dev Contructor that gives msg.sender all of existing tokens. */ function OpportyToken() public { totalSupply = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; } } contract Escrow is Ownable { // status of the project enum Status { NEW, PAYED, WORKDONE, CLAIMED, CLOSED } // status of the current work enum WorkStatus {NEW, STARTED, FULLYDONE, PARTIALLYDONE } // token address address tokenHolder = 0x08990456DC3020C93593DF3CaE79E27935dd69b9; // execute funciton only by token holders modifier onlyShareholders { require (token.balanceOf(msg.sender) > 0); _; } // transaction only after deadline modifier afterDeadline(uint idProject) { Project storage project = projects[idProject]; require (now > project.deadline) ; _; } // transaction can be executed by project client modifier onlyClient(uint idProject) { Project storage project = projects[idProject]; require (project.client == msg.sender); _; } // transaction can be executed only by performer modifier onlyPerformer(uint idProject) { Project storage project = projects[idProject]; require (project.performer == msg.sender); _; } // project in Opporty system // TODO: decrease size of struct struct Project { uint id; string name; address client; address performer; uint deadline; uint sum; Status status; string report; WorkStatus wstatus; uint votingDeadline; uint numberOfVotes; uint totalVotesNeeded; bool withdrawed; Vote[] votes; mapping (address => bool) voted; } // one vote - one element of struct struct Vote { bool inSupport; address voter; } // event - project was added event ProjectAdded(uint idExternal, uint projectID, address performer, string name, uint sum); // event - fund was transferred event FundTransfered(address recipient, uint amount); // work was done event WorkDone(uint projectId, address performer, WorkStatus status, string link); // already voted event Voted(uint projectID, bool position, address voter); // status of project changed event ChangedProjectStatus(uint projectID, Status status); event log(string val); event loga(address addr); event logi(uint i); // token for payments OpportyToken token; // all projects Project[] projects; // number or projects uint public numProjects; function Escrow(address tokenUsed) public { token = OpportyToken(tokenUsed); } function getNumberOfProjects() public constant returns(uint) { return numProjects; } // Add a project to blockchain // idExternal - id in opporty // name // performer // duration // sum function addProject(uint idExternal, string name, address performer, uint durationInMinutes, uint sum) public returns (uint projectId) { projectId = projects.length++; Project storage p = projects[projectId]; p.id = idExternal; p.name = name; p.client = msg.sender; p.performer = performer; p.deadline = now + durationInMinutes * 1 minutes; p.sum = sum * 1 ether; p.status = Status.NEW; ProjectAdded(idExternal, projectId, performer, name, sum); return projectId; } function getProjectReport(uint idProject) public constant returns (string t) { Project storage p = projects[idProject]; return p.report; } function getJudgeVoted(uint idProject, address judge) public constant returns (bool voted) { Project storage p = projects[idProject]; if (p.voted[judge]) return true; else return false; } // get status of project function getStatus(uint idProject) public constant returns (uint t) { Project storage p = projects[idProject]; return uint(p.status); } // is deadline function isDeadline(uint idProject) public constant returns (bool f) { Project storage p = projects[idProject]; if (now >= p.deadline) { return true; } else { return false; } } // pay for project by client function payFor(uint idProject) payable onlyClient(idProject) public returns (bool) { Project storage project = projects[idProject]; uint price = project.sum; require (project.status == Status.NEW); if (msg.value >= price) { project.status = Status.PAYED; FundTransfered(this, msg.value); ChangedProjectStatus(idProject, Status.PAYED); return true; } else { revert(); } } // pay by project in tokens function payByTokens(uint idProject) onlyClient(idProject) onlyShareholders public { Project storage project = projects[idProject]; require (project.sum <= token.balanceOf(project.client)); require (token.transferFrom(project.client, tokenHolder, project.sum)); ChangedProjectStatus(idProject, Status.PAYED); } // change status of project - done // and provide report function workDone(uint idProject, string report, WorkStatus status) onlyPerformer(idProject) afterDeadline(idProject) public { Project storage project = projects[idProject]; require (project.status == Status.PAYED); project.status = Status.WORKDONE; project.report = report; project.wstatus = status; WorkDone(idProject, project.performer, project.wstatus, project.report); ChangedProjectStatus(idProject, Status.WORKDONE); } // work is done - execured by client function acceptWork(uint idProject) onlyClient(idProject) afterDeadline(idProject) public { Project storage project = projects[idProject]; require (project.status == Status.WORKDONE); project.status = Status.CLOSED; ChangedProjectStatus(idProject, Status.CLOSED); } // claim - project was undone (?) // numberOfVoters // debatePeriod - time for voting function claimWork(uint idProject, uint numberOfVoters, uint debatePeriod) afterDeadline(idProject) public { Project storage project = projects[idProject]; require (project.status == Status.WORKDONE); project.status = Status.CLAIMED; project.votingDeadline = now + debatePeriod * 1 minutes; project.totalVotesNeeded = numberOfVoters; ChangedProjectStatus(idProject, Status.CLAIMED); } // voting process function vote(uint idProject, bool supportsProject) public returns (uint voteID) { Project storage p = projects[idProject]; require(p.voted[msg.sender] != true); require(p.status == Status.CLAIMED); require(p.numberOfVotes < p.totalVotesNeeded); require(now >= p.votingDeadline ); voteID = p.votes.length++; p.votes[voteID] = Vote({inSupport: supportsProject, voter: msg.sender}); p.voted[msg.sender] = true; p.numberOfVotes = voteID + 1; Voted(idProject, supportsProject, msg.sender); return voteID; } // safeWithdrawal - get money by performer / return money for client function safeWithdrawal(uint idProject) afterDeadline(idProject) public { Project storage p = projects[idProject]; // if status closed and was not withdrawed require(p.status == Status.CLAIMED || p.status == Status.CLOSED && !p.withdrawed); // if project closed if (p.status == Status.CLOSED) { if (msg.sender == p.performer && !p.withdrawed && msg.sender.send(p.sum) ) { FundTransfered(msg.sender, p.sum); p.withdrawed = true; } else { revert(); } } else { // claim uint yea = 0; uint nay = 0; // calculating votes for (uint i = 0; i < p.votes.length; ++i) { Vote storage v = p.votes[i]; if (v.inSupport) { yea += 1; } else { nay += 1; } } // если уже время голосования закончилось if (now >= p.votingDeadline) { if (msg.sender == p.performer && p.numberOfVotes >= p.totalVotesNeeded ) { if (yea>nay && !p.withdrawed && msg.sender.send(p.sum)) { FundTransfered(msg.sender, p.sum); p.withdrawed = true; p.status = Status.CLOSED; ChangedProjectStatus(idProject, Status.CLOSED); } } if (msg.sender == p.client) { if (nay>=yea && !p.withdrawed && msg.sender.send(p.sum)) { FundTransfered(msg.sender, p.sum); p.withdrawed = true; p.status = Status.CLOSED; // меняем статус проекта ChangedProjectStatus(idProject, Status.CLOSED); } } } else { revert(); } } } // get tokens function safeWithdrawalTokens(uint idProject) afterDeadline(idProject) public { Project storage p = projects[idProject]; require(p.status == Status.CLAIMED || p.status == Status.CLOSED && !p.withdrawed); if (p.status == Status.CLOSED) { if (msg.sender == p.performer && token.transfer(p.performer, p.sum) && !p.withdrawed) { FundTransfered(msg.sender, p.sum); p.withdrawed = true; } else { revert(); } } } }
event - project was added
event ProjectAdded(uint idExternal, uint projectID, address performer, string name, uint sum);
1,160,970
[ 1, 2575, 300, 1984, 1703, 3096, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 225, 871, 5420, 8602, 12, 11890, 612, 6841, 16, 2254, 1984, 734, 16, 1758, 3073, 264, 16, 533, 508, 16, 2254, 2142, 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 ]
./partial_match/1/0x45c1085f2a8ce7c71B24d4130C2dAf9A95D2B196/sources/AshbieMoon.sol
File contracts/AshbieMoon.sol
contract AshbieMoon is Ownable, ERC20 { bool public limited; uint256 public maxHoldingAmount; uint256 public minHoldingAmount; address public uniswapV2Pair; mapping(address => bool) public blacklists; function _beforeTokenTransfer( address from, address to, uint256 amount function _afterTokenTransfer( address from, address to, uint256 amount } pragma solidity ^0.8.0; constructor(uint256 _totalSupply) ERC20("AshbieMoon", "ASH") { _mint(msg.sender, _totalSupply); } function blacklist(address _address, bool _isBlacklisting) external onlyOwner { blacklists[_address] = _isBlacklisting; } function setRule(bool _limited, address _uniswapV2Pair, uint256 _maxHoldingAmount, uint256 _minHoldingAmount) external onlyOwner { limited = _limited; uniswapV2Pair = _uniswapV2Pair; maxHoldingAmount = _maxHoldingAmount; minHoldingAmount = _minHoldingAmount; } function _beforeTokenTransfer( address from, address to, uint256 amount ) override internal virtual { require(!blacklists[to] && !blacklists[from], "Blacklisted"); if (uniswapV2Pair == address(0)) { require(from == owner() || to == owner(), "trading is not started"); return; } if (limited && from == uniswapV2Pair) { require(super.balanceOf(to) + amount <= maxHoldingAmount && super.balanceOf(to) + amount >= minHoldingAmount, "Forbid"); } } function _beforeTokenTransfer( address from, address to, uint256 amount ) override internal virtual { require(!blacklists[to] && !blacklists[from], "Blacklisted"); if (uniswapV2Pair == address(0)) { require(from == owner() || to == owner(), "trading is not started"); return; } if (limited && from == uniswapV2Pair) { require(super.balanceOf(to) + amount <= maxHoldingAmount && super.balanceOf(to) + amount >= minHoldingAmount, "Forbid"); } } function _beforeTokenTransfer( address from, address to, uint256 amount ) override internal virtual { require(!blacklists[to] && !blacklists[from], "Blacklisted"); if (uniswapV2Pair == address(0)) { require(from == owner() || to == owner(), "trading is not started"); return; } if (limited && from == uniswapV2Pair) { require(super.balanceOf(to) + amount <= maxHoldingAmount && super.balanceOf(to) + amount >= minHoldingAmount, "Forbid"); } } function burn(uint256 value) external { _burn(msg.sender, value); } }
2,876,083
[ 1, 812, 20092, 19, 37, 674, 70, 1385, 16727, 265, 18, 18281, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 432, 674, 70, 1385, 16727, 265, 353, 14223, 6914, 16, 4232, 39, 3462, 288, 203, 565, 1426, 1071, 13594, 31, 203, 565, 2254, 5034, 1071, 943, 20586, 310, 6275, 31, 203, 565, 2254, 5034, 1071, 1131, 20586, 310, 6275, 31, 203, 565, 1758, 1071, 640, 291, 91, 438, 58, 22, 4154, 31, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 7721, 9772, 31, 203, 203, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 203, 565, 445, 389, 5205, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 97, 203, 203, 203, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 203, 203, 565, 3885, 12, 11890, 5034, 389, 4963, 3088, 1283, 13, 4232, 39, 3462, 2932, 37, 674, 70, 1385, 16727, 265, 3113, 315, 10793, 7923, 288, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 203, 565, 445, 11709, 12, 2867, 389, 2867, 16, 1426, 389, 291, 13155, 21228, 13, 3903, 1338, 5541, 288, 203, 3639, 7721, 9772, 63, 67, 2867, 65, 273, 389, 291, 13155, 21228, 31, 203, 565, 289, 203, 203, 565, 445, 444, 2175, 12, 6430, 389, 21325, 16, 1758, 389, 318, 291, 91, 438, 58, 22, 4154, 16, 2254, 5034, 389, 1896, 20586, 310, 6275, 16, 2254, 5034, 389, 1154, 20586, 310, 6275, 13, 3903, 1338, 2 ]
pragma solidity 0.5.16; // INTERFACE interface IERC20Mintable { function transfer(address _to, uint256 _value) external returns (bool); function transferFrom( address _from, address _to, uint256 _value ) external returns (bool); function mint(address _to, uint256 _value) external returns (bool); function balanceOf(address _account) external view returns (uint256); function totalSupply() external view returns (uint256); } /** * @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); } // LIB /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev 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"); } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub( value, "SafeERC20: decreased allowance below zero" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } /** * Smart contract library of mathematical functions operating with signed * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is * basically a simple fraction whose numerator is signed 128-bit integer and * denominator is 2^64. As long as denominator is always the same, there is no * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are * represented by int128 type holding only the numerator. */ library ABDKMath64x64 { /* * Minimum value signed 64.64-bit fixed point number may have. */ int128 private constant MIN_64x64 = -0x80000000000000000000000000000000; /* * Maximum value signed 64.64-bit fixed point number may have. */ int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Convert signed 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromInt(int256 x) internal pure returns (int128) { require(x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF); return int128(x << 64); } /** * Convert signed 64.64 fixed point number into signed 64-bit integer number * rounding down. * * @param x signed 64.64-bit fixed point number * @return signed 64-bit integer number */ function toInt(int128 x) internal pure returns (int64) { return int64(x >> 64); } /** * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromUInt(uint256 x) internal pure returns (int128) { require(x <= 0x7FFFFFFFFFFFFFFF); return int128(x << 64); } /** * Convert signed 64.64 fixed point number into unsigned 64-bit integer * number rounding down. Revert on underflow. * * @param x signed 64.64-bit fixed point number * @return unsigned 64-bit integer number */ function toUInt(int128 x) internal pure returns (uint64) { require(x >= 0); return uint64(x >> 64); } /** * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point * number rounding down. Revert on overflow. * * @param x signed 128.128-bin fixed point number * @return signed 64.64-bit fixed point number */ function from128x128(int256 x) internal pure returns (int128) { int256 result = x >> 64; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } /** * Convert signed 64.64 fixed point number into signed 128.128 fixed point * number. * * @param x signed 64.64-bit fixed point number * @return signed 128.128 fixed point number */ function to128x128(int128 x) internal pure returns (int256) { return int256(x) << 64; } /** * Calculate x + y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function add(int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) + y; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } /** * Calculate x - y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sub(int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) - y; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } /** * Calculate x * y rounding down. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function mul(int128 x, int128 y) internal pure returns (int128) { int256 result = (int256(x) * y) >> 64; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } /** * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point * number and y is signed 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y signed 256-bit integer number * @return signed 256-bit integer number */ function muli(int128 x, int256 y) internal pure returns (int256) { if (x == MIN_64x64) { require( y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF && y <= 0x1000000000000000000000000000000000000000000000000 ); return -y << 63; } else { bool negativeResult = false; if (x < 0) { x = -x; negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint256 absoluteResult = mulu(x, uint256(y)); if (negativeResult) { require(absoluteResult <= 0x8000000000000000000000000000000000000000000000000000000000000000); return -int256(absoluteResult); // We rely on overflow behavior here } else { require(absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int256(absoluteResult); } } } /** * Calculate x * y rounding down, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y unsigned 256-bit integer number * @return unsigned 256-bit integer number */ function mulu(int128 x, uint256 y) internal pure returns (uint256) { if (y == 0) return 0; require(x >= 0); uint256 lo = (uint256(x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64; uint256 hi = uint256(x) * (y >> 128); require(hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); hi <<= 64; require(hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo); return hi + lo; } /** * Calculate x / y rounding towards zero. Revert on overflow or when y is * zero. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function div(int128 x, int128 y) internal pure returns (int128) { require(y != 0); int256 result = (int256(x) << 64) / y; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } /** * Calculate x / y rounding towards zero, where x and y are signed 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x signed 256-bit integer number * @param y signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function divi(int256 x, int256 y) internal pure returns (int128) { require(y != 0); bool negativeResult = false; if (x < 0) { x = -x; // We rely on overflow behavior here negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint128 absoluteResult = divuu(uint256(x), uint256(y)); if (negativeResult) { require(absoluteResult <= 0x80000000000000000000000000000000); return -int128(absoluteResult); // We rely on overflow behavior here } else { require(absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128(absoluteResult); // We rely on overflow behavior here } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function divu(uint256 x, uint256 y) internal pure returns (int128) { require(y != 0); uint128 result = divuu(x, y); require(result <= uint128(MAX_64x64)); return int128(result); } /** * Calculate -x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function neg(int128 x) internal pure returns (int128) { require(x != MIN_64x64); return -x; } /** * Calculate |x|. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function abs(int128 x) internal pure returns (int128) { require(x != MIN_64x64); return x < 0 ? -x : x; } /** * Calculate 1 / x rounding towards zero. Revert on overflow or when x is * zero. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function inv(int128 x) internal pure returns (int128) { require(x != 0); int256 result = int256(0x100000000000000000000000000000000) / x; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } /** * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function avg(int128 x, int128 y) internal pure returns (int128) { return int128((int256(x) + int256(y)) >> 1); } /** * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down. * Revert on overflow or in case x * y is negative. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function gavg(int128 x, int128 y) internal pure returns (int128) { int256 m = int256(x) * int256(y); require(m >= 0); require(m < 0x4000000000000000000000000000000000000000000000000000000000000000); return int128(sqrtu(uint256(m))); } /** * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y uint256 value * @return signed 64.64-bit fixed point number */ function pow(int128 x, uint256 y) internal pure returns (int128) { bool negative = x < 0 && y & 1 == 1; uint256 absX = uint128(x < 0 ? -x : x); uint256 absResult; absResult = 0x100000000000000000000000000000000; if (absX <= 0x10000000000000000) { absX <<= 63; while (y != 0) { if (y & 0x1 != 0) { absResult = (absResult * absX) >> 127; } absX = (absX * absX) >> 127; if (y & 0x2 != 0) { absResult = (absResult * absX) >> 127; } absX = (absX * absX) >> 127; if (y & 0x4 != 0) { absResult = (absResult * absX) >> 127; } absX = (absX * absX) >> 127; if (y & 0x8 != 0) { absResult = (absResult * absX) >> 127; } absX = (absX * absX) >> 127; y >>= 4; } absResult >>= 64; } else { uint256 absXShift = 63; if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; } if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; } if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; } if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; } if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; } if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; } uint256 resultShift = 0; while (y != 0) { require(absXShift < 64); if (y & 0x1 != 0) { absResult = (absResult * absX) >> 127; resultShift += absXShift; if (absResult > 0x100000000000000000000000000000000) { absResult >>= 1; resultShift += 1; } } absX = (absX * absX) >> 127; absXShift <<= 1; if (absX >= 0x100000000000000000000000000000000) { absX >>= 1; absXShift += 1; } y >>= 1; } require(resultShift < 64); absResult >>= 64 - resultShift; } int256 result = negative ? -int256(absResult) : int256(absResult); require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } /** * Calculate sqrt (x) rounding down. Revert if x < 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sqrt(int128 x) internal pure returns (int128) { require(x >= 0); return int128(sqrtu(uint256(x) << 64)); } /** * Calculate binary logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function log_2(int128 x) internal pure returns (int128) { require(x > 0); int256 msb = 0; int256 xc = x; if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 result = (msb - 64) << 64; uint256 ux = uint256(x) << uint256(127 - msb); for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) { ux *= ux; uint256 b = ux >> 255; ux >>= 127 + b; result += bit * int256(b); } return int128(result); } /** * Calculate natural logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function ln(int128 x) internal pure returns (int128) { require(x > 0); return int128((uint256(log_2(x)) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF) >> 128); } /** * Calculate binary exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp_2(int128 x) internal pure returns (int128) { require(x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow uint256 result = 0x80000000000000000000000000000000; if (x & 0x8000000000000000 > 0) result = (result * 0x16A09E667F3BCC908B2FB1366EA957D3E) >> 128; if (x & 0x4000000000000000 > 0) result = (result * 0x1306FE0A31B7152DE8D5A46305C85EDEC) >> 128; if (x & 0x2000000000000000 > 0) result = (result * 0x1172B83C7D517ADCDF7C8C50EB14A791F) >> 128; if (x & 0x1000000000000000 > 0) result = (result * 0x10B5586CF9890F6298B92B71842A98363) >> 128; if (x & 0x800000000000000 > 0) result = (result * 0x1059B0D31585743AE7C548EB68CA417FD) >> 128; if (x & 0x400000000000000 > 0) result = (result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8) >> 128; if (x & 0x200000000000000 > 0) result = (result * 0x10163DA9FB33356D84A66AE336DCDFA3F) >> 128; if (x & 0x100000000000000 > 0) result = (result * 0x100B1AFA5ABCBED6129AB13EC11DC9543) >> 128; if (x & 0x80000000000000 > 0) result = (result * 0x10058C86DA1C09EA1FF19D294CF2F679B) >> 128; if (x & 0x40000000000000 > 0) result = (result * 0x1002C605E2E8CEC506D21BFC89A23A00F) >> 128; if (x & 0x20000000000000 > 0) result = (result * 0x100162F3904051FA128BCA9C55C31E5DF) >> 128; if (x & 0x10000000000000 > 0) result = (result * 0x1000B175EFFDC76BA38E31671CA939725) >> 128; if (x & 0x8000000000000 > 0) result = (result * 0x100058BA01FB9F96D6CACD4B180917C3D) >> 128; if (x & 0x4000000000000 > 0) result = (result * 0x10002C5CC37DA9491D0985C348C68E7B3) >> 128; if (x & 0x2000000000000 > 0) result = (result * 0x1000162E525EE054754457D5995292026) >> 128; if (x & 0x1000000000000 > 0) result = (result * 0x10000B17255775C040618BF4A4ADE83FC) >> 128; if (x & 0x800000000000 > 0) result = (result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB) >> 128; if (x & 0x400000000000 > 0) result = (result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9) >> 128; if (x & 0x200000000000 > 0) result = (result * 0x10000162E43F4F831060E02D839A9D16D) >> 128; if (x & 0x100000000000 > 0) result = (result * 0x100000B1721BCFC99D9F890EA06911763) >> 128; if (x & 0x80000000000 > 0) result = (result * 0x10000058B90CF1E6D97F9CA14DBCC1628) >> 128; if (x & 0x40000000000 > 0) result = (result * 0x1000002C5C863B73F016468F6BAC5CA2B) >> 128; if (x & 0x20000000000 > 0) result = (result * 0x100000162E430E5A18F6119E3C02282A5) >> 128; if (x & 0x10000000000 > 0) result = (result * 0x1000000B1721835514B86E6D96EFD1BFE) >> 128; if (x & 0x8000000000 > 0) result = (result * 0x100000058B90C0B48C6BE5DF846C5B2EF) >> 128; if (x & 0x4000000000 > 0) result = (result * 0x10000002C5C8601CC6B9E94213C72737A) >> 128; if (x & 0x2000000000 > 0) result = (result * 0x1000000162E42FFF037DF38AA2B219F06) >> 128; if (x & 0x1000000000 > 0) result = (result * 0x10000000B17217FBA9C739AA5819F44F9) >> 128; if (x & 0x800000000 > 0) result = (result * 0x1000000058B90BFCDEE5ACD3C1CEDC823) >> 128; if (x & 0x400000000 > 0) result = (result * 0x100000002C5C85FE31F35A6A30DA1BE50) >> 128; if (x & 0x200000000 > 0) result = (result * 0x10000000162E42FF0999CE3541B9FFFCF) >> 128; if (x & 0x100000000 > 0) result = (result * 0x100000000B17217F80F4EF5AADDA45554) >> 128; if (x & 0x80000000 > 0) result = (result * 0x10000000058B90BFBF8479BD5A81B51AD) >> 128; if (x & 0x40000000 > 0) result = (result * 0x1000000002C5C85FDF84BD62AE30A74CC) >> 128; if (x & 0x20000000 > 0) result = (result * 0x100000000162E42FEFB2FED257559BDAA) >> 128; if (x & 0x10000000 > 0) result = (result * 0x1000000000B17217F7D5A7716BBA4A9AE) >> 128; if (x & 0x8000000 > 0) result = (result * 0x100000000058B90BFBE9DDBAC5E109CCE) >> 128; if (x & 0x4000000 > 0) result = (result * 0x10000000002C5C85FDF4B15DE6F17EB0D) >> 128; if (x & 0x2000000 > 0) result = (result * 0x1000000000162E42FEFA494F1478FDE05) >> 128; if (x & 0x1000000 > 0) result = (result * 0x10000000000B17217F7D20CF927C8E94C) >> 128; if (x & 0x800000 > 0) result = (result * 0x1000000000058B90BFBE8F71CB4E4B33D) >> 128; if (x & 0x400000 > 0) result = (result * 0x100000000002C5C85FDF477B662B26945) >> 128; if (x & 0x200000 > 0) result = (result * 0x10000000000162E42FEFA3AE53369388C) >> 128; if (x & 0x100000 > 0) result = (result * 0x100000000000B17217F7D1D351A389D40) >> 128; if (x & 0x80000 > 0) result = (result * 0x10000000000058B90BFBE8E8B2D3D4EDE) >> 128; if (x & 0x40000 > 0) result = (result * 0x1000000000002C5C85FDF4741BEA6E77E) >> 128; if (x & 0x20000 > 0) result = (result * 0x100000000000162E42FEFA39FE95583C2) >> 128; if (x & 0x10000 > 0) result = (result * 0x1000000000000B17217F7D1CFB72B45E1) >> 128; if (x & 0x8000 > 0) result = (result * 0x100000000000058B90BFBE8E7CC35C3F0) >> 128; if (x & 0x4000 > 0) result = (result * 0x10000000000002C5C85FDF473E242EA38) >> 128; if (x & 0x2000 > 0) result = (result * 0x1000000000000162E42FEFA39F02B772C) >> 128; if (x & 0x1000 > 0) result = (result * 0x10000000000000B17217F7D1CF7D83C1A) >> 128; if (x & 0x800 > 0) result = (result * 0x1000000000000058B90BFBE8E7BDCBE2E) >> 128; if (x & 0x400 > 0) result = (result * 0x100000000000002C5C85FDF473DEA871F) >> 128; if (x & 0x200 > 0) result = (result * 0x10000000000000162E42FEFA39EF44D91) >> 128; if (x & 0x100 > 0) result = (result * 0x100000000000000B17217F7D1CF79E949) >> 128; if (x & 0x80 > 0) result = (result * 0x10000000000000058B90BFBE8E7BCE544) >> 128; if (x & 0x40 > 0) result = (result * 0x1000000000000002C5C85FDF473DE6ECA) >> 128; if (x & 0x20 > 0) result = (result * 0x100000000000000162E42FEFA39EF366F) >> 128; if (x & 0x10 > 0) result = (result * 0x1000000000000000B17217F7D1CF79AFA) >> 128; if (x & 0x8 > 0) result = (result * 0x100000000000000058B90BFBE8E7BCD6D) >> 128; if (x & 0x4 > 0) result = (result * 0x10000000000000002C5C85FDF473DE6B2) >> 128; if (x & 0x2 > 0) result = (result * 0x1000000000000000162E42FEFA39EF358) >> 128; if (x & 0x1 > 0) result = (result * 0x10000000000000000B17217F7D1CF79AB) >> 128; result >>= uint256(63 - (x >> 64)); require(result <= uint256(MAX_64x64)); return int128(result); } /** * Calculate natural exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp(int128 x) internal pure returns (int128) { require(x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow return exp_2(int128((int256(x) * 0x171547652B82FE1777D0FFDA0D23A7D12) >> 128)); } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return unsigned 64.64-bit fixed point number */ function divuu(uint256 x, uint256 y) private pure returns (uint128) { require(y != 0); uint256 result; if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y; else { uint256 msb = 192; uint256 xc = x >> 192; if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore result = (x << (255 - msb)) / (((y - 1) >> (msb - 191)) + 1); require(result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 hi = result * (y >> 128); uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 xh = x >> 192; uint256 xl = x << 64; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here lo = hi << 128; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here assert(xh == hi >> 128); result += xl / y; } require(result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return uint128(result); } /** * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer * number. * * @param x unsigned 256-bit integer number * @return unsigned 128-bit integer number */ function sqrtu(uint256 x) private pure returns (uint128) { if (x == 0) return 0; else { 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 uint128(r < r1 ? r : r1); } } } /** * Smart contract library of mathematical functions operating with IEEE 754 * quadruple-precision binary floating-point numbers (quadruple precision * numbers). As long as quadruple precision numbers are 16-bytes long, they are * represented by bytes16 type. */ library ABDKMathQuad { /* * 0. */ bytes16 private constant POSITIVE_ZERO = 0x00000000000000000000000000000000; /* * -0. */ bytes16 private constant NEGATIVE_ZERO = 0x80000000000000000000000000000000; /* * +Infinity. */ bytes16 private constant POSITIVE_INFINITY = 0x7FFF0000000000000000000000000000; /* * -Infinity. */ bytes16 private constant NEGATIVE_INFINITY = 0xFFFF0000000000000000000000000000; /* * Canonical NaN value. */ bytes16 private constant NaN = 0x7FFF8000000000000000000000000000; /** * Convert signed 256-bit integer number into quadruple precision number. * * @param x signed 256-bit integer number * @return quadruple precision number */ function fromInt(int256 x) internal pure returns (bytes16) { if (x == 0) return bytes16(0); else { // We rely on overflow behavior here uint256 result = uint256(x > 0 ? x : -x); uint256 msb = msb(result); if (msb < 112) result <<= 112 - msb; else if (msb > 112) result >>= msb - 112; result = (result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) | ((16383 + msb) << 112); if (x < 0) result |= 0x80000000000000000000000000000000; return bytes16(uint128(result)); } } /** * Convert quadruple precision number into signed 256-bit integer number * rounding towards zero. Revert on overflow. * * @param x quadruple precision number * @return signed 256-bit integer number */ function toInt(bytes16 x) internal pure returns (int256) { uint256 exponent = (uint128(x) >> 112) & 0x7FFF; require(exponent <= 16638); // Overflow if (exponent < 16383) return 0; // Underflow uint256 result = (uint256(uint128(x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) | 0x10000000000000000000000000000; if (exponent < 16495) result >>= 16495 - exponent; else if (exponent > 16495) result <<= exponent - 16495; if (uint128(x) >= 0x80000000000000000000000000000000) { // Negative require(result <= 0x8000000000000000000000000000000000000000000000000000000000000000); return -int256(result); // We rely on overflow behavior here } else { require(result <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int256(result); } } /** * Convert unsigned 256-bit integer number into quadruple precision number. * * @param x unsigned 256-bit integer number * @return quadruple precision number */ function fromUInt(uint256 x) internal pure returns (bytes16) { if (x == 0) return bytes16(0); else { uint256 result = x; uint256 msb = msb(result); if (msb < 112) result <<= 112 - msb; else if (msb > 112) result >>= msb - 112; result = (result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) | ((16383 + msb) << 112); return bytes16(uint128(result)); } } /** * Convert quadruple precision number into unsigned 256-bit integer number * rounding towards zero. Revert on underflow. Note, that negative floating * point numbers in range (-1.0 .. 0.0) may be converted to unsigned integer * without error, because they are rounded to zero. * * @param x quadruple precision number * @return unsigned 256-bit integer number */ function toUInt(bytes16 x) internal pure returns (uint256) { uint256 exponent = (uint128(x) >> 112) & 0x7FFF; if (exponent < 16383) return 0; // Underflow require(uint128(x) < 0x80000000000000000000000000000000); // Negative require(exponent <= 16638); // Overflow uint256 result = (uint256(uint128(x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) | 0x10000000000000000000000000000; if (exponent < 16495) result >>= 16495 - exponent; else if (exponent > 16495) result <<= exponent - 16495; return result; } /** * Convert signed 128.128 bit fixed point number into quadruple precision * number. * * @param x signed 128.128 bit fixed point number * @return quadruple precision number */ function from128x128(int256 x) internal pure returns (bytes16) { if (x == 0) return bytes16(0); else { // We rely on overflow behavior here uint256 result = uint256(x > 0 ? x : -x); uint256 msb = msb(result); if (msb < 112) result <<= 112 - msb; else if (msb > 112) result >>= msb - 112; result = (result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) | ((16255 + msb) << 112); if (x < 0) result |= 0x80000000000000000000000000000000; return bytes16(uint128(result)); } } /** * Convert quadruple precision number into signed 128.128 bit fixed point * number. Revert on overflow. * * @param x quadruple precision number * @return signed 128.128 bit fixed point number */ function to128x128(bytes16 x) internal pure returns (int256) { uint256 exponent = (uint128(x) >> 112) & 0x7FFF; require(exponent <= 16510); // Overflow if (exponent < 16255) return 0; // Underflow uint256 result = (uint256(uint128(x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) | 0x10000000000000000000000000000; if (exponent < 16367) result >>= 16367 - exponent; else if (exponent > 16367) result <<= exponent - 16367; if (uint128(x) >= 0x80000000000000000000000000000000) { // Negative require(result <= 0x8000000000000000000000000000000000000000000000000000000000000000); return -int256(result); // We rely on overflow behavior here } else { require(result <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int256(result); } } /** * Convert signed 64.64 bit fixed point number into quadruple precision * number. * * @param x signed 64.64 bit fixed point number * @return quadruple precision number */ function from64x64(int128 x) internal pure returns (bytes16) { if (x == 0) return bytes16(0); else { // We rely on overflow behavior here uint256 result = uint128(x > 0 ? x : -x); uint256 msb = msb(result); if (msb < 112) result <<= 112 - msb; else if (msb > 112) result >>= msb - 112; result = (result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) | ((16319 + msb) << 112); if (x < 0) result |= 0x80000000000000000000000000000000; return bytes16(uint128(result)); } } /** * Convert quadruple precision number into signed 64.64 bit fixed point * number. Revert on overflow. * * @param x quadruple precision number * @return signed 64.64 bit fixed point number */ function to64x64(bytes16 x) internal pure returns (int128) { uint256 exponent = (uint128(x) >> 112) & 0x7FFF; require(exponent <= 16446); // Overflow if (exponent < 16319) return 0; // Underflow uint256 result = (uint256(uint128(x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) | 0x10000000000000000000000000000; if (exponent < 16431) result >>= 16431 - exponent; else if (exponent > 16431) result <<= exponent - 16431; if (uint128(x) >= 0x80000000000000000000000000000000) { // Negative require(result <= 0x80000000000000000000000000000000); return -int128(result); // We rely on overflow behavior here } else { require(result <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128(result); } } /** * Convert octuple precision number into quadruple precision number. * * @param x octuple precision number * @return quadruple precision number */ function fromOctuple(bytes32 x) internal pure returns (bytes16) { bool negative = x & 0x8000000000000000000000000000000000000000000000000000000000000000 > 0; uint256 exponent = (uint256(x) >> 236) & 0x7FFFF; uint256 significand = uint256(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; if (exponent == 0x7FFFF) { if (significand > 0) return NaN; else return negative ? NEGATIVE_INFINITY : POSITIVE_INFINITY; } if (exponent > 278526) return negative ? NEGATIVE_INFINITY : POSITIVE_INFINITY; else if (exponent < 245649) return negative ? NEGATIVE_ZERO : POSITIVE_ZERO; else if (exponent < 245761) { significand = (significand | 0x100000000000000000000000000000000000000000000000000000000000) >> (245885 - exponent); exponent = 0; } else { significand >>= 124; exponent -= 245760; } uint128 result = uint128(significand | (exponent << 112)); if (negative) result |= 0x80000000000000000000000000000000; return bytes16(result); } /** * Convert quadruple precision number into octuple precision number. * * @param x quadruple precision number * @return octuple precision number */ function toOctuple(bytes16 x) internal pure returns (bytes32) { uint256 exponent = (uint128(x) >> 112) & 0x7FFF; uint256 result = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF; if (exponent == 0x7FFF) exponent = 0x7FFFF; // Infinity or NaN else if (exponent == 0) { if (result > 0) { uint256 msb = msb(result); result = (result << (236 - msb)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; exponent = 245649 + msb; } } else { result <<= 124; exponent += 245760; } result |= exponent << 236; if (uint128(x) >= 0x80000000000000000000000000000000) result |= 0x8000000000000000000000000000000000000000000000000000000000000000; return bytes32(result); } /** * Convert double precision number into quadruple precision number. * * @param x double precision number * @return quadruple precision number */ function fromDouble(bytes8 x) internal pure returns (bytes16) { uint256 exponent = (uint64(x) >> 52) & 0x7FF; uint256 result = uint64(x) & 0xFFFFFFFFFFFFF; if (exponent == 0x7FF) exponent = 0x7FFF; // Infinity or NaN else if (exponent == 0) { if (result > 0) { uint256 msb = msb(result); result = (result << (112 - msb)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF; exponent = 15309 + msb; } } else { result <<= 60; exponent += 15360; } result |= exponent << 112; if (x & 0x8000000000000000 > 0) result |= 0x80000000000000000000000000000000; return bytes16(uint128(result)); } /** * Convert quadruple precision number into double precision number. * * @param x quadruple precision number * @return double precision number */ function toDouble(bytes16 x) internal pure returns (bytes8) { bool negative = uint128(x) >= 0x80000000000000000000000000000000; uint256 exponent = (uint128(x) >> 112) & 0x7FFF; uint256 significand = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF; if (exponent == 0x7FFF) { if (significand > 0) return 0x7FF8000000000000; // NaN else return negative ? bytes8(0xFFF0000000000000) // -Infinity : bytes8(0x7FF0000000000000); // Infinity } if (exponent > 17406) return negative ? bytes8(0xFFF0000000000000) // -Infinity : bytes8(0x7FF0000000000000); // Infinity else if (exponent < 15309) return negative ? bytes8(0x8000000000000000) // -0 : bytes8(0x0000000000000000); // 0 else if (exponent < 15361) { significand = (significand | 0x10000000000000000000000000000) >> (15421 - exponent); exponent = 0; } else { significand >>= 60; exponent -= 15360; } uint64 result = uint64(significand | (exponent << 52)); if (negative) result |= 0x8000000000000000; return bytes8(result); } /** * Test whether given quadruple precision number is NaN. * * @param x quadruple precision number * @return true if x is NaN, false otherwise */ function isNaN(bytes16 x) internal pure returns (bool) { return uint128(x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF > 0x7FFF0000000000000000000000000000; } /** * Test whether given quadruple precision number is positive or negative * infinity. * * @param x quadruple precision number * @return true if x is positive or negative infinity, false otherwise */ function isInfinity(bytes16 x) internal pure returns (bool) { return uint128(x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0x7FFF0000000000000000000000000000; } /** * Calculate sign of x, i.e. -1 if x is negative, 0 if x if zero, and 1 if x * is positive. Note that sign (-0) is zero. Revert if x is NaN. * * @param x quadruple precision number * @return sign of x */ function sign(bytes16 x) internal pure returns (int8) { uint128 absoluteX = uint128(x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; require(absoluteX <= 0x7FFF0000000000000000000000000000); // Not NaN if (absoluteX == 0) return 0; else if (uint128(x) >= 0x80000000000000000000000000000000) return -1; else return 1; } /** * Calculate sign (x - y). Revert if either argument is NaN, or both * arguments are infinities of the same sign. * * @param x quadruple precision number * @param y quadruple precision number * @return sign (x - y) */ function cmp(bytes16 x, bytes16 y) internal pure returns (int8) { uint128 absoluteX = uint128(x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; require(absoluteX <= 0x7FFF0000000000000000000000000000); // Not NaN uint128 absoluteY = uint128(y) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; require(absoluteY <= 0x7FFF0000000000000000000000000000); // Not NaN // Not infinities of the same sign require(x != y || absoluteX < 0x7FFF0000000000000000000000000000); if (x == y) return 0; else { bool negativeX = uint128(x) >= 0x80000000000000000000000000000000; bool negativeY = uint128(y) >= 0x80000000000000000000000000000000; if (negativeX) { if (negativeY) return absoluteX > absoluteY ? -1 : int8(1); else return -1; } else { if (negativeY) return 1; else return absoluteX > absoluteY ? int8(1) : -1; } } } /** * Test whether x equals y. NaN, infinity, and -infinity are not equal to * anything. * * @param x quadruple precision number * @param y quadruple precision number * @return true if x equals to y, false otherwise */ function eq(bytes16 x, bytes16 y) internal pure returns (bool) { if (x == y) { return uint128(x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF < 0x7FFF0000000000000000000000000000; } else return false; } /** * Calculate x + y. Special values behave in the following way: * * NaN + x = NaN for any x. * Infinity + x = Infinity for any finite x. * -Infinity + x = -Infinity for any finite x. * Infinity + Infinity = Infinity. * -Infinity + -Infinity = -Infinity. * Infinity + -Infinity = -Infinity + Infinity = NaN. * * @param x quadruple precision number * @param y quadruple precision number * @return quadruple precision number */ function add(bytes16 x, bytes16 y) internal pure returns (bytes16) { uint256 xExponent = (uint128(x) >> 112) & 0x7FFF; uint256 yExponent = (uint128(y) >> 112) & 0x7FFF; if (xExponent == 0x7FFF) { if (yExponent == 0x7FFF) { if (x == y) return x; else return NaN; } else return x; } else if (yExponent == 0x7FFF) return y; else { bool xSign = uint128(x) >= 0x80000000000000000000000000000000; uint256 xSignifier = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF; if (xExponent == 0) xExponent = 1; else xSignifier |= 0x10000000000000000000000000000; bool ySign = uint128(y) >= 0x80000000000000000000000000000000; uint256 ySignifier = uint128(y) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF; if (yExponent == 0) yExponent = 1; else ySignifier |= 0x10000000000000000000000000000; if (xSignifier == 0) return y == NEGATIVE_ZERO ? POSITIVE_ZERO : y; else if (ySignifier == 0) return x == NEGATIVE_ZERO ? POSITIVE_ZERO : x; else { int256 delta = int256(xExponent) - int256(yExponent); if (xSign == ySign) { if (delta > 112) return x; else if (delta > 0) ySignifier >>= uint256(delta); else if (delta < -112) return y; else if (delta < 0) { xSignifier >>= uint256(-delta); xExponent = yExponent; } xSignifier += ySignifier; if (xSignifier >= 0x20000000000000000000000000000) { xSignifier >>= 1; xExponent += 1; } if (xExponent == 0x7FFF) return xSign ? NEGATIVE_INFINITY : POSITIVE_INFINITY; else { if (xSignifier < 0x10000000000000000000000000000) xExponent = 0; else xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF; return bytes16( uint128( (xSign ? 0x80000000000000000000000000000000 : 0) | (xExponent << 112) | xSignifier ) ); } } else { if (delta > 0) { xSignifier <<= 1; xExponent -= 1; } else if (delta < 0) { ySignifier <<= 1; xExponent = yExponent - 1; } if (delta > 112) ySignifier = 1; else if (delta > 1) ySignifier = ((ySignifier - 1) >> uint256(delta - 1)) + 1; else if (delta < -112) xSignifier = 1; else if (delta < -1) xSignifier = ((xSignifier - 1) >> uint256(-delta - 1)) + 1; if (xSignifier >= ySignifier) xSignifier -= ySignifier; else { xSignifier = ySignifier - xSignifier; xSign = ySign; } if (xSignifier == 0) return POSITIVE_ZERO; uint256 msb = msb(xSignifier); if (msb == 113) { xSignifier = (xSignifier >> 1) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF; xExponent += 1; } else if (msb < 112) { uint256 shift = 112 - msb; if (xExponent > shift) { xSignifier = (xSignifier << shift) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF; xExponent -= shift; } else { xSignifier <<= xExponent - 1; xExponent = 0; } } else xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF; if (xExponent == 0x7FFF) return xSign ? NEGATIVE_INFINITY : POSITIVE_INFINITY; else return bytes16( uint128( (xSign ? 0x80000000000000000000000000000000 : 0) | (xExponent << 112) | xSignifier ) ); } } } } /** * Calculate x - y. Special values behave in the following way: * * NaN - x = NaN for any x. * Infinity - x = Infinity for any finite x. * -Infinity - x = -Infinity for any finite x. * Infinity - -Infinity = Infinity. * -Infinity - Infinity = -Infinity. * Infinity - Infinity = -Infinity - -Infinity = NaN. * * @param x quadruple precision number * @param y quadruple precision number * @return quadruple precision number */ function sub(bytes16 x, bytes16 y) internal pure returns (bytes16) { return add(x, y ^ 0x80000000000000000000000000000000); } /** * Calculate x * y. Special values behave in the following way: * * NaN * x = NaN for any x. * Infinity * x = Infinity for any finite positive x. * Infinity * x = -Infinity for any finite negative x. * -Infinity * x = -Infinity for any finite positive x. * -Infinity * x = Infinity for any finite negative x. * Infinity * 0 = NaN. * -Infinity * 0 = NaN. * Infinity * Infinity = Infinity. * Infinity * -Infinity = -Infinity. * -Infinity * Infinity = -Infinity. * -Infinity * -Infinity = Infinity. * * @param x quadruple precision number * @param y quadruple precision number * @return quadruple precision number */ function mul(bytes16 x, bytes16 y) internal pure returns (bytes16) { uint256 xExponent = (uint128(x) >> 112) & 0x7FFF; uint256 yExponent = (uint128(y) >> 112) & 0x7FFF; if (xExponent == 0x7FFF) { if (yExponent == 0x7FFF) { if (x == y) return x ^ (y & 0x80000000000000000000000000000000); else if (x ^ y == 0x80000000000000000000000000000000) return x | y; else return NaN; } else { if (y & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0) return NaN; else return x ^ (y & 0x80000000000000000000000000000000); } } else if (yExponent == 0x7FFF) { if (x & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0) return NaN; else return y ^ (x & 0x80000000000000000000000000000000); } else { uint256 xSignifier = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF; if (xExponent == 0) xExponent = 1; else xSignifier |= 0x10000000000000000000000000000; uint256 ySignifier = uint128(y) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF; if (yExponent == 0) yExponent = 1; else ySignifier |= 0x10000000000000000000000000000; xSignifier *= ySignifier; if (xSignifier == 0) return (x ^ y) & 0x80000000000000000000000000000000 > 0 ? NEGATIVE_ZERO : POSITIVE_ZERO; xExponent += yExponent; uint256 msb = xSignifier >= 0x200000000000000000000000000000000000000000000000000000000 ? 225 : xSignifier >= 0x100000000000000000000000000000000000000000000000000000000 ? 224 : msb(xSignifier); if (xExponent + msb < 16496) { // Underflow xExponent = 0; xSignifier = 0; } else if (xExponent + msb < 16608) { // Subnormal if (xExponent < 16496) xSignifier >>= 16496 - xExponent; else if (xExponent > 16496) xSignifier <<= xExponent - 16496; xExponent = 0; } else if (xExponent + msb > 49373) { xExponent = 0x7FFF; xSignifier = 0; } else { if (msb > 112) xSignifier >>= msb - 112; else if (msb < 112) xSignifier <<= 112 - msb; xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF; xExponent = xExponent + msb - 16607; } return bytes16( uint128(uint128((x ^ y) & 0x80000000000000000000000000000000) | (xExponent << 112) | xSignifier) ); } } /** * Calculate x / y. Special values behave in the following way: * * NaN / x = NaN for any x. * x / NaN = NaN for any x. * Infinity / x = Infinity for any finite non-negative x. * Infinity / x = -Infinity for any finite negative x including -0. * -Infinity / x = -Infinity for any finite non-negative x. * -Infinity / x = Infinity for any finite negative x including -0. * x / Infinity = 0 for any finite non-negative x. * x / -Infinity = -0 for any finite non-negative x. * x / Infinity = -0 for any finite non-negative x including -0. * x / -Infinity = 0 for any finite non-negative x including -0. * * Infinity / Infinity = NaN. * Infinity / -Infinity = -NaN. * -Infinity / Infinity = -NaN. * -Infinity / -Infinity = NaN. * * Division by zero behaves in the following way: * * x / 0 = Infinity for any finite positive x. * x / -0 = -Infinity for any finite positive x. * x / 0 = -Infinity for any finite negative x. * x / -0 = Infinity for any finite negative x. * 0 / 0 = NaN. * 0 / -0 = NaN. * -0 / 0 = NaN. * -0 / -0 = NaN. * * @param x quadruple precision number * @param y quadruple precision number * @return quadruple precision number */ function div(bytes16 x, bytes16 y) internal pure returns (bytes16) { uint256 xExponent = (uint128(x) >> 112) & 0x7FFF; uint256 yExponent = (uint128(y) >> 112) & 0x7FFF; if (xExponent == 0x7FFF) { if (yExponent == 0x7FFF) return NaN; else return x ^ (y & 0x80000000000000000000000000000000); } else if (yExponent == 0x7FFF) { if (y & 0x0000FFFFFFFFFFFFFFFFFFFFFFFFFFFF != 0) return NaN; else return POSITIVE_ZERO | ((x ^ y) & 0x80000000000000000000000000000000); } else if (y & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0) { if (x & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0) return NaN; else return POSITIVE_INFINITY | ((x ^ y) & 0x80000000000000000000000000000000); } else { uint256 ySignifier = uint128(y) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF; if (yExponent == 0) yExponent = 1; else ySignifier |= 0x10000000000000000000000000000; uint256 xSignifier = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF; if (xExponent == 0) { if (xSignifier != 0) { uint256 shift = 226 - msb(xSignifier); xSignifier <<= shift; xExponent = 1; yExponent += shift - 114; } } else { xSignifier = (xSignifier | 0x10000000000000000000000000000) << 114; } xSignifier = xSignifier / ySignifier; if (xSignifier == 0) return (x ^ y) & 0x80000000000000000000000000000000 > 0 ? NEGATIVE_ZERO : POSITIVE_ZERO; assert(xSignifier >= 0x1000000000000000000000000000); uint256 msb = xSignifier >= 0x80000000000000000000000000000 ? msb(xSignifier) : xSignifier >= 0x40000000000000000000000000000 ? 114 : xSignifier >= 0x20000000000000000000000000000 ? 113 : 112; if (xExponent + msb > yExponent + 16497) { // Overflow xExponent = 0x7FFF; xSignifier = 0; } else if (xExponent + msb + 16380 < yExponent) { // Underflow xExponent = 0; xSignifier = 0; } else if (xExponent + msb + 16268 < yExponent) { // Subnormal if (xExponent + 16380 > yExponent) xSignifier <<= xExponent + 16380 - yExponent; else if (xExponent + 16380 < yExponent) xSignifier >>= yExponent - xExponent - 16380; xExponent = 0; } else { // Normal if (msb > 112) xSignifier >>= msb - 112; xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF; xExponent = xExponent + msb + 16269 - yExponent; } return bytes16( uint128(uint128((x ^ y) & 0x80000000000000000000000000000000) | (xExponent << 112) | xSignifier) ); } } /** * Calculate -x. * * @param x quadruple precision number * @return quadruple precision number */ function neg(bytes16 x) internal pure returns (bytes16) { return x ^ 0x80000000000000000000000000000000; } /** * Calculate |x|. * * @param x quadruple precision number * @return quadruple precision number */ function abs(bytes16 x) internal pure returns (bytes16) { return x & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; } /** * Calculate square root of x. Return NaN on negative x excluding -0. * * @param x quadruple precision number * @return quadruple precision number */ function sqrt(bytes16 x) internal pure returns (bytes16) { if (uint128(x) > 0x80000000000000000000000000000000) return NaN; else { uint256 xExponent = (uint128(x) >> 112) & 0x7FFF; if (xExponent == 0x7FFF) return x; else { uint256 xSignifier = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF; if (xExponent == 0) xExponent = 1; else xSignifier |= 0x10000000000000000000000000000; if (xSignifier == 0) return POSITIVE_ZERO; bool oddExponent = xExponent & 0x1 == 0; xExponent = (xExponent + 16383) >> 1; if (oddExponent) { if (xSignifier >= 0x10000000000000000000000000000) xSignifier <<= 113; else { uint256 msb = msb(xSignifier); uint256 shift = (226 - msb) & 0xFE; xSignifier <<= shift; xExponent -= (shift - 112) >> 1; } } else { if (xSignifier >= 0x10000000000000000000000000000) xSignifier <<= 112; else { uint256 msb = msb(xSignifier); uint256 shift = (225 - msb) & 0xFE; xSignifier <<= shift; xExponent -= (shift - 112) >> 1; } } uint256 r = 0x10000000000000000000000000000; r = (r + xSignifier / r) >> 1; r = (r + xSignifier / r) >> 1; r = (r + xSignifier / r) >> 1; r = (r + xSignifier / r) >> 1; r = (r + xSignifier / r) >> 1; r = (r + xSignifier / r) >> 1; r = (r + xSignifier / r) >> 1; // Seven iterations should be enough uint256 r1 = xSignifier / r; if (r1 < r) r = r1; return bytes16(uint128((xExponent << 112) | (r & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF))); } } } /** * Calculate binary logarithm of x. Return NaN on negative x excluding -0. * * @param x quadruple precision number * @return quadruple precision number */ function log_2(bytes16 x) internal pure returns (bytes16) { if (uint128(x) > 0x80000000000000000000000000000000) return NaN; else if (x == 0x3FFF0000000000000000000000000000) return POSITIVE_ZERO; else { uint256 xExponent = (uint128(x) >> 112) & 0x7FFF; if (xExponent == 0x7FFF) return x; else { uint256 xSignifier = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF; if (xExponent == 0) xExponent = 1; else xSignifier |= 0x10000000000000000000000000000; if (xSignifier == 0) return NEGATIVE_INFINITY; bool resultNegative; uint256 resultExponent = 16495; uint256 resultSignifier; if (xExponent >= 0x3FFF) { resultNegative = false; resultSignifier = xExponent - 0x3FFF; xSignifier <<= 15; } else { resultNegative = true; if (xSignifier >= 0x10000000000000000000000000000) { resultSignifier = 0x3FFE - xExponent; xSignifier <<= 15; } else { uint256 msb = msb(xSignifier); resultSignifier = 16493 - msb; xSignifier <<= 127 - msb; } } if (xSignifier == 0x80000000000000000000000000000000) { if (resultNegative) resultSignifier += 1; uint256 shift = 112 - msb(resultSignifier); resultSignifier <<= shift; resultExponent -= shift; } else { uint256 bb = resultNegative ? 1 : 0; while (resultSignifier < 0x10000000000000000000000000000) { resultSignifier <<= 1; resultExponent -= 1; xSignifier *= xSignifier; uint256 b = xSignifier >> 255; resultSignifier += b ^ bb; xSignifier >>= 127 + b; } } return bytes16( uint128( (resultNegative ? 0x80000000000000000000000000000000 : 0) | (resultExponent << 112) | (resultSignifier & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) ) ); } } } /** * Calculate natural logarithm of x. Return NaN on negative x excluding -0. * * @param x quadruple precision number * @return quadruple precision number */ function ln(bytes16 x) internal pure returns (bytes16) { return mul(log_2(x), 0x3FFE62E42FEFA39EF35793C7673007E5); } /** * Calculate 2^x. * * @param x quadruple precision number * @return quadruple precision number */ function pow_2(bytes16 x) internal pure returns (bytes16) { bool xNegative = uint128(x) > 0x80000000000000000000000000000000; uint256 xExponent = (uint128(x) >> 112) & 0x7FFF; uint256 xSignifier = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF; if (xExponent == 0x7FFF && xSignifier != 0) return NaN; else if (xExponent > 16397) return xNegative ? POSITIVE_ZERO : POSITIVE_INFINITY; else if (xExponent < 16255) return 0x3FFF0000000000000000000000000000; else { if (xExponent == 0) xExponent = 1; else xSignifier |= 0x10000000000000000000000000000; if (xExponent > 16367) xSignifier <<= xExponent - 16367; else if (xExponent < 16367) xSignifier >>= 16367 - xExponent; if (xNegative && xSignifier > 0x406E00000000000000000000000000000000) return POSITIVE_ZERO; if (!xNegative && xSignifier > 0x3FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) return POSITIVE_INFINITY; uint256 resultExponent = xSignifier >> 128; xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; if (xNegative && xSignifier != 0) { xSignifier = ~xSignifier; resultExponent += 1; } uint256 resultSignifier = 0x80000000000000000000000000000000; if (xSignifier & 0x80000000000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x16A09E667F3BCC908B2FB1366EA957D3E) >> 128; if (xSignifier & 0x40000000000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x1306FE0A31B7152DE8D5A46305C85EDEC) >> 128; if (xSignifier & 0x20000000000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x1172B83C7D517ADCDF7C8C50EB14A791F) >> 128; if (xSignifier & 0x10000000000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x10B5586CF9890F6298B92B71842A98363) >> 128; if (xSignifier & 0x8000000000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x1059B0D31585743AE7C548EB68CA417FD) >> 128; if (xSignifier & 0x4000000000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x102C9A3E778060EE6F7CACA4F7A29BDE8) >> 128; if (xSignifier & 0x2000000000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x10163DA9FB33356D84A66AE336DCDFA3F) >> 128; if (xSignifier & 0x1000000000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x100B1AFA5ABCBED6129AB13EC11DC9543) >> 128; if (xSignifier & 0x800000000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x10058C86DA1C09EA1FF19D294CF2F679B) >> 128; if (xSignifier & 0x400000000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x1002C605E2E8CEC506D21BFC89A23A00F) >> 128; if (xSignifier & 0x200000000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x100162F3904051FA128BCA9C55C31E5DF) >> 128; if (xSignifier & 0x100000000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x1000B175EFFDC76BA38E31671CA939725) >> 128; if (xSignifier & 0x80000000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x100058BA01FB9F96D6CACD4B180917C3D) >> 128; if (xSignifier & 0x40000000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x10002C5CC37DA9491D0985C348C68E7B3) >> 128; if (xSignifier & 0x20000000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x1000162E525EE054754457D5995292026) >> 128; if (xSignifier & 0x10000000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x10000B17255775C040618BF4A4ADE83FC) >> 128; if (xSignifier & 0x8000000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB) >> 128; if (xSignifier & 0x4000000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9) >> 128; if (xSignifier & 0x2000000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x10000162E43F4F831060E02D839A9D16D) >> 128; if (xSignifier & 0x1000000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x100000B1721BCFC99D9F890EA06911763) >> 128; if (xSignifier & 0x800000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x10000058B90CF1E6D97F9CA14DBCC1628) >> 128; if (xSignifier & 0x400000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x1000002C5C863B73F016468F6BAC5CA2B) >> 128; if (xSignifier & 0x200000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x100000162E430E5A18F6119E3C02282A5) >> 128; if (xSignifier & 0x100000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x1000000B1721835514B86E6D96EFD1BFE) >> 128; if (xSignifier & 0x80000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x100000058B90C0B48C6BE5DF846C5B2EF) >> 128; if (xSignifier & 0x40000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x10000002C5C8601CC6B9E94213C72737A) >> 128; if (xSignifier & 0x20000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x1000000162E42FFF037DF38AA2B219F06) >> 128; if (xSignifier & 0x10000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x10000000B17217FBA9C739AA5819F44F9) >> 128; if (xSignifier & 0x8000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x1000000058B90BFCDEE5ACD3C1CEDC823) >> 128; if (xSignifier & 0x4000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x100000002C5C85FE31F35A6A30DA1BE50) >> 128; if (xSignifier & 0x2000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x10000000162E42FF0999CE3541B9FFFCF) >> 128; if (xSignifier & 0x1000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x100000000B17217F80F4EF5AADDA45554) >> 128; if (xSignifier & 0x800000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x10000000058B90BFBF8479BD5A81B51AD) >> 128; if (xSignifier & 0x400000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x1000000002C5C85FDF84BD62AE30A74CC) >> 128; if (xSignifier & 0x200000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x100000000162E42FEFB2FED257559BDAA) >> 128; if (xSignifier & 0x100000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x1000000000B17217F7D5A7716BBA4A9AE) >> 128; if (xSignifier & 0x80000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x100000000058B90BFBE9DDBAC5E109CCE) >> 128; if (xSignifier & 0x40000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x10000000002C5C85FDF4B15DE6F17EB0D) >> 128; if (xSignifier & 0x20000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x1000000000162E42FEFA494F1478FDE05) >> 128; if (xSignifier & 0x10000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x10000000000B17217F7D20CF927C8E94C) >> 128; if (xSignifier & 0x8000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x1000000000058B90BFBE8F71CB4E4B33D) >> 128; if (xSignifier & 0x4000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x100000000002C5C85FDF477B662B26945) >> 128; if (xSignifier & 0x2000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x10000000000162E42FEFA3AE53369388C) >> 128; if (xSignifier & 0x1000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x100000000000B17217F7D1D351A389D40) >> 128; if (xSignifier & 0x800000000000000000000 > 0) resultSignifier = (resultSignifier * 0x10000000000058B90BFBE8E8B2D3D4EDE) >> 128; if (xSignifier & 0x400000000000000000000 > 0) resultSignifier = (resultSignifier * 0x1000000000002C5C85FDF4741BEA6E77E) >> 128; if (xSignifier & 0x200000000000000000000 > 0) resultSignifier = (resultSignifier * 0x100000000000162E42FEFA39FE95583C2) >> 128; if (xSignifier & 0x100000000000000000000 > 0) resultSignifier = (resultSignifier * 0x1000000000000B17217F7D1CFB72B45E1) >> 128; if (xSignifier & 0x80000000000000000000 > 0) resultSignifier = (resultSignifier * 0x100000000000058B90BFBE8E7CC35C3F0) >> 128; if (xSignifier & 0x40000000000000000000 > 0) resultSignifier = (resultSignifier * 0x10000000000002C5C85FDF473E242EA38) >> 128; if (xSignifier & 0x20000000000000000000 > 0) resultSignifier = (resultSignifier * 0x1000000000000162E42FEFA39F02B772C) >> 128; if (xSignifier & 0x10000000000000000000 > 0) resultSignifier = (resultSignifier * 0x10000000000000B17217F7D1CF7D83C1A) >> 128; if (xSignifier & 0x8000000000000000000 > 0) resultSignifier = (resultSignifier * 0x1000000000000058B90BFBE8E7BDCBE2E) >> 128; if (xSignifier & 0x4000000000000000000 > 0) resultSignifier = (resultSignifier * 0x100000000000002C5C85FDF473DEA871F) >> 128; if (xSignifier & 0x2000000000000000000 > 0) resultSignifier = (resultSignifier * 0x10000000000000162E42FEFA39EF44D91) >> 128; if (xSignifier & 0x1000000000000000000 > 0) resultSignifier = (resultSignifier * 0x100000000000000B17217F7D1CF79E949) >> 128; if (xSignifier & 0x800000000000000000 > 0) resultSignifier = (resultSignifier * 0x10000000000000058B90BFBE8E7BCE544) >> 128; if (xSignifier & 0x400000000000000000 > 0) resultSignifier = (resultSignifier * 0x1000000000000002C5C85FDF473DE6ECA) >> 128; if (xSignifier & 0x200000000000000000 > 0) resultSignifier = (resultSignifier * 0x100000000000000162E42FEFA39EF366F) >> 128; if (xSignifier & 0x100000000000000000 > 0) resultSignifier = (resultSignifier * 0x1000000000000000B17217F7D1CF79AFA) >> 128; if (xSignifier & 0x80000000000000000 > 0) resultSignifier = (resultSignifier * 0x100000000000000058B90BFBE8E7BCD6D) >> 128; if (xSignifier & 0x40000000000000000 > 0) resultSignifier = (resultSignifier * 0x10000000000000002C5C85FDF473DE6B2) >> 128; if (xSignifier & 0x20000000000000000 > 0) resultSignifier = (resultSignifier * 0x1000000000000000162E42FEFA39EF358) >> 128; if (xSignifier & 0x10000000000000000 > 0) resultSignifier = (resultSignifier * 0x10000000000000000B17217F7D1CF79AB) >> 128; if (xSignifier & 0x8000000000000000 > 0) resultSignifier = (resultSignifier * 0x1000000000000000058B90BFBE8E7BCD5) >> 128; if (xSignifier & 0x4000000000000000 > 0) resultSignifier = (resultSignifier * 0x100000000000000002C5C85FDF473DE6A) >> 128; if (xSignifier & 0x2000000000000000 > 0) resultSignifier = (resultSignifier * 0x10000000000000000162E42FEFA39EF34) >> 128; if (xSignifier & 0x1000000000000000 > 0) resultSignifier = (resultSignifier * 0x100000000000000000B17217F7D1CF799) >> 128; if (xSignifier & 0x800000000000000 > 0) resultSignifier = (resultSignifier * 0x10000000000000000058B90BFBE8E7BCC) >> 128; if (xSignifier & 0x400000000000000 > 0) resultSignifier = (resultSignifier * 0x1000000000000000002C5C85FDF473DE5) >> 128; if (xSignifier & 0x200000000000000 > 0) resultSignifier = (resultSignifier * 0x100000000000000000162E42FEFA39EF2) >> 128; if (xSignifier & 0x100000000000000 > 0) resultSignifier = (resultSignifier * 0x1000000000000000000B17217F7D1CF78) >> 128; if (xSignifier & 0x80000000000000 > 0) resultSignifier = (resultSignifier * 0x100000000000000000058B90BFBE8E7BB) >> 128; if (xSignifier & 0x40000000000000 > 0) resultSignifier = (resultSignifier * 0x10000000000000000002C5C85FDF473DD) >> 128; if (xSignifier & 0x20000000000000 > 0) resultSignifier = (resultSignifier * 0x1000000000000000000162E42FEFA39EE) >> 128; if (xSignifier & 0x10000000000000 > 0) resultSignifier = (resultSignifier * 0x10000000000000000000B17217F7D1CF6) >> 128; if (xSignifier & 0x8000000000000 > 0) resultSignifier = (resultSignifier * 0x1000000000000000000058B90BFBE8E7A) >> 128; if (xSignifier & 0x4000000000000 > 0) resultSignifier = (resultSignifier * 0x100000000000000000002C5C85FDF473C) >> 128; if (xSignifier & 0x2000000000000 > 0) resultSignifier = (resultSignifier * 0x10000000000000000000162E42FEFA39D) >> 128; if (xSignifier & 0x1000000000000 > 0) resultSignifier = (resultSignifier * 0x100000000000000000000B17217F7D1CE) >> 128; if (xSignifier & 0x800000000000 > 0) resultSignifier = (resultSignifier * 0x10000000000000000000058B90BFBE8E6) >> 128; if (xSignifier & 0x400000000000 > 0) resultSignifier = (resultSignifier * 0x1000000000000000000002C5C85FDF472) >> 128; if (xSignifier & 0x200000000000 > 0) resultSignifier = (resultSignifier * 0x100000000000000000000162E42FEFA38) >> 128; if (xSignifier & 0x100000000000 > 0) resultSignifier = (resultSignifier * 0x1000000000000000000000B17217F7D1B) >> 128; if (xSignifier & 0x80000000000 > 0) resultSignifier = (resultSignifier * 0x100000000000000000000058B90BFBE8D) >> 128; if (xSignifier & 0x40000000000 > 0) resultSignifier = (resultSignifier * 0x10000000000000000000002C5C85FDF46) >> 128; if (xSignifier & 0x20000000000 > 0) resultSignifier = (resultSignifier * 0x1000000000000000000000162E42FEFA2) >> 128; if (xSignifier & 0x10000000000 > 0) resultSignifier = (resultSignifier * 0x10000000000000000000000B17217F7D0) >> 128; if (xSignifier & 0x8000000000 > 0) resultSignifier = (resultSignifier * 0x1000000000000000000000058B90BFBE7) >> 128; if (xSignifier & 0x4000000000 > 0) resultSignifier = (resultSignifier * 0x100000000000000000000002C5C85FDF3) >> 128; if (xSignifier & 0x2000000000 > 0) resultSignifier = (resultSignifier * 0x10000000000000000000000162E42FEF9) >> 128; if (xSignifier & 0x1000000000 > 0) resultSignifier = (resultSignifier * 0x100000000000000000000000B17217F7C) >> 128; if (xSignifier & 0x800000000 > 0) resultSignifier = (resultSignifier * 0x10000000000000000000000058B90BFBD) >> 128; if (xSignifier & 0x400000000 > 0) resultSignifier = (resultSignifier * 0x1000000000000000000000002C5C85FDE) >> 128; if (xSignifier & 0x200000000 > 0) resultSignifier = (resultSignifier * 0x100000000000000000000000162E42FEE) >> 128; if (xSignifier & 0x100000000 > 0) resultSignifier = (resultSignifier * 0x1000000000000000000000000B17217F6) >> 128; if (xSignifier & 0x80000000 > 0) resultSignifier = (resultSignifier * 0x100000000000000000000000058B90BFA) >> 128; if (xSignifier & 0x40000000 > 0) resultSignifier = (resultSignifier * 0x10000000000000000000000002C5C85FC) >> 128; if (xSignifier & 0x20000000 > 0) resultSignifier = (resultSignifier * 0x1000000000000000000000000162E42FD) >> 128; if (xSignifier & 0x10000000 > 0) resultSignifier = (resultSignifier * 0x10000000000000000000000000B17217E) >> 128; if (xSignifier & 0x8000000 > 0) resultSignifier = (resultSignifier * 0x1000000000000000000000000058B90BE) >> 128; if (xSignifier & 0x4000000 > 0) resultSignifier = (resultSignifier * 0x100000000000000000000000002C5C85E) >> 128; if (xSignifier & 0x2000000 > 0) resultSignifier = (resultSignifier * 0x10000000000000000000000000162E42E) >> 128; if (xSignifier & 0x1000000 > 0) resultSignifier = (resultSignifier * 0x100000000000000000000000000B17216) >> 128; if (xSignifier & 0x800000 > 0) resultSignifier = (resultSignifier * 0x10000000000000000000000000058B90A) >> 128; if (xSignifier & 0x400000 > 0) resultSignifier = (resultSignifier * 0x1000000000000000000000000002C5C84) >> 128; if (xSignifier & 0x200000 > 0) resultSignifier = (resultSignifier * 0x100000000000000000000000000162E41) >> 128; if (xSignifier & 0x100000 > 0) resultSignifier = (resultSignifier * 0x1000000000000000000000000000B1720) >> 128; if (xSignifier & 0x80000 > 0) resultSignifier = (resultSignifier * 0x100000000000000000000000000058B8F) >> 128; if (xSignifier & 0x40000 > 0) resultSignifier = (resultSignifier * 0x10000000000000000000000000002C5C7) >> 128; if (xSignifier & 0x20000 > 0) resultSignifier = (resultSignifier * 0x1000000000000000000000000000162E3) >> 128; if (xSignifier & 0x10000 > 0) resultSignifier = (resultSignifier * 0x10000000000000000000000000000B171) >> 128; if (xSignifier & 0x8000 > 0) resultSignifier = (resultSignifier * 0x1000000000000000000000000000058B8) >> 128; if (xSignifier & 0x4000 > 0) resultSignifier = (resultSignifier * 0x100000000000000000000000000002C5B) >> 128; if (xSignifier & 0x2000 > 0) resultSignifier = (resultSignifier * 0x10000000000000000000000000000162D) >> 128; if (xSignifier & 0x1000 > 0) resultSignifier = (resultSignifier * 0x100000000000000000000000000000B16) >> 128; if (xSignifier & 0x800 > 0) resultSignifier = (resultSignifier * 0x10000000000000000000000000000058A) >> 128; if (xSignifier & 0x400 > 0) resultSignifier = (resultSignifier * 0x1000000000000000000000000000002C4) >> 128; if (xSignifier & 0x200 > 0) resultSignifier = (resultSignifier * 0x100000000000000000000000000000161) >> 128; if (xSignifier & 0x100 > 0) resultSignifier = (resultSignifier * 0x1000000000000000000000000000000B0) >> 128; if (xSignifier & 0x80 > 0) resultSignifier = (resultSignifier * 0x100000000000000000000000000000057) >> 128; if (xSignifier & 0x40 > 0) resultSignifier = (resultSignifier * 0x10000000000000000000000000000002B) >> 128; if (xSignifier & 0x20 > 0) resultSignifier = (resultSignifier * 0x100000000000000000000000000000015) >> 128; if (xSignifier & 0x10 > 0) resultSignifier = (resultSignifier * 0x10000000000000000000000000000000A) >> 128; if (xSignifier & 0x8 > 0) resultSignifier = (resultSignifier * 0x100000000000000000000000000000004) >> 128; if (xSignifier & 0x4 > 0) resultSignifier = (resultSignifier * 0x100000000000000000000000000000001) >> 128; if (!xNegative) { resultSignifier = (resultSignifier >> 15) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF; resultExponent += 0x3FFF; } else if (resultExponent <= 0x3FFE) { resultSignifier = (resultSignifier >> 15) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF; resultExponent = 0x3FFF - resultExponent; } else { resultSignifier = resultSignifier >> (resultExponent - 16367); resultExponent = 0; } return bytes16(uint128((resultExponent << 112) | resultSignifier)); } } /** * Calculate e^x. * * @param x quadruple precision number * @return quadruple precision number */ function exp(bytes16 x) internal pure returns (bytes16) { return pow_2(mul(x, 0x3FFF71547652B82FE1777D0FFDA0D23A)); } /** * Get index of the most significant non-zero bit in binary representation of * x. Reverts if x is zero. * * @return index of the most significant non-zero bit in binary representation * of x */ function msb(uint256 x) private pure returns (uint256) { require(x > 0); uint256 result = 0; if (x >= 0x100000000000000000000000000000000) { x >>= 128; result += 128; } if (x >= 0x10000000000000000) { x >>= 64; result += 64; } if (x >= 0x100000000) { x >>= 32; result += 32; } if (x >= 0x10000) { x >>= 16; result += 16; } if (x >= 0x100) { x >>= 8; result += 8; } if (x >= 0x10) { x >>= 4; result += 4; } if (x >= 0x4) { x >>= 2; result += 2; } if (x >= 0x2) result += 1; // No need to shift x anymore return result; } } // CONTRACTS /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require( initializing || isConstructor() || !initialized, "Contract instance has already been initialized" ); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } contract Sacrifice { constructor(address payable _recipient) public payable { selfdestruct(_recipient); } } /** * @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. */ contract ReentrancyGuard is Initializable { // counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; function initialize() public initializer { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call"); } uint256[50] private ______gap; } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public view returns (uint256); function balanceOf(address tokenOwner) public view returns (uint256 balance); function allowance(address tokenOwner, address spender) public view returns (uint256 remaining); function transfer(address to, uint256 tokens) public returns (bool success); function approve(address spender, uint256 tokens) public returns (bool success); function transferFrom( address from, address to, uint256 tokens ) public returns (bool success); event Transfer(address indexed from, address indexed to, uint256 tokens); event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens); } // ---------------------------------------------------------------------------- // Safe Math Library // ---------------------------------------------------------------------------- contract SafeMathERC20 { function safeAdd(uint256 a, uint256 b) public pure returns (uint256 c) { c = a + b; require(c >= a); } function safeSub(uint256 a, uint256 b) public pure returns (uint256 c) { require(b <= a); c = a - b; } function safeMul(uint256 a, uint256 b) public pure returns (uint256 c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint256 a, uint256 b) public pure returns (uint256 c) { require(b > 0); c = a / b; } } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with 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 is Initializable { // 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 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. */ /** * @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 Initializable, Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function initialize(address sender) public initializer { _owner = 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 _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; } uint256[50] private ______gap; } contract StakingV2 is Ownable, ReentrancyGuard { using Address for address; using SafeMath for uint256; using SafeERC20 for IERC20; // EVENTS /** * @dev Emitted when a user deposits tokens. * @param sender User address. * @param id User's unique deposit ID. * @param amount The amount of deposited tokens. * @param currentBalance Current user balance. * @param timestamp Operation date */ event Deposited( address indexed sender, uint256 indexed id, uint256 amount, uint256 currentBalance, uint256 timestamp ); /** * @dev Emitted when a user withdraws tokens. * @param sender User address. * @param id User's unique deposit ID. * @param totalWithdrawalAmount The total amount of withdrawn tokens. * @param currentBalance Balance before withdrawal * @param timestamp Operation date */ event WithdrawnAll( address indexed sender, uint256 indexed id, uint256 totalWithdrawalAmount, uint256 currentBalance, uint256 timestamp ); /** * @dev Emitted when a user extends lockup. * @param sender User address. * @param id User's unique deposit ID. * @param currentBalance Balance before lockup extension * @param finalBalance Final balance * @param timestamp The instant when the lockup is extended. */ event ExtendedLockup( address indexed sender, uint256 indexed id, uint256 currentBalance, uint256 finalBalance, uint256 timestamp ); /** * @dev Emitted when a new Liquidity Provider address value is set. * @param value A new address value. * @param sender The owner address at the moment of address changing. */ event LiquidityProviderAddressSet(address value, address sender); struct AddressParam { address oldValue; address newValue; uint256 timestamp; } // The deposit user balaces mapping(address => mapping(uint256 => uint256)) public balances; // The dates of users deposits/withdraws/extendLockups mapping(address => mapping(uint256 => uint256)) public depositDates; // Variable that prevents _deposit method from being called 2 times TODO CHECK bool private locked; // Variable to pause all operations bool private contractPaused = false; bool private pausedDepositsAndLockupExtensions = false; // STAKE token IERC20Mintable public token; // Reward Token IERC20Mintable public tokenReward; // The address for the Liquidity Providers AddressParam public liquidityProviderAddressParam; uint256 private constant DAY = 1 days; uint256 private constant MONTH = 30 days; uint256 private constant YEAR = 365 days; // The period after which the new value of the parameter is set uint256 public constant PARAM_UPDATE_DELAY = 7 days; // MODIFIERS /* * 1 | 2 | 3 | 4 | 5 * 0 Months | 3 Months | 6 Months | 9 Months | 12 Months */ modifier validDepositId(uint256 _depositId) { require(_depositId >= 1 && _depositId <= 5, "Invalid depositId"); _; } // Impossible to withdrawAll if you have never deposited. modifier balanceExists(uint256 _depositId) { require(balances[msg.sender][_depositId] > 0, "Your deposit is zero"); _; } modifier isNotLocked() { require(locked == false, "Locked, try again later"); _; } modifier isNotPaused() { require(contractPaused == false, "Paused"); _; } modifier isNotPausedOperations() { require(contractPaused == false, "Paused"); _; } modifier isNotPausedDepositAndLockupExtensions() { require(pausedDepositsAndLockupExtensions == false, "Paused Deposits and Extensions"); _; } /** * @dev Pause Deposits, Withdraw, Lockup Extension */ function pauseContract(bool value) public onlyOwner { contractPaused = value; } /** * @dev Pause Deposits and Lockup Extension */ function pauseDepositAndLockupExtensions(bool value) public onlyOwner { pausedDepositsAndLockupExtensions = value; } /** * @dev Initializes the contract. _tokenAddress _tokenReward will have the same address * @param _owner The owner of the contract. * @param _tokenAddress The address of the STAKE token contract. * @param _tokenReward The address of token rewards. * @param _liquidityProviderAddress The address for the Liquidity Providers reward. */ function initializeStaking( address _owner, address _tokenAddress, address _tokenReward, address _liquidityProviderAddress ) external initializer { require(_owner != address(0), "Zero address"); require(_tokenAddress.isContract(), "Not a contract address"); Ownable.initialize(msg.sender); ReentrancyGuard.initialize(); token = IERC20Mintable(_tokenAddress); tokenReward = IERC20Mintable(_tokenReward); setLiquidityProviderAddress(_liquidityProviderAddress); Ownable.transferOwnership(_owner); } /** * @dev Sets the address for the Liquidity Providers reward. * Can only be called by owner. * @param _address The new address. */ function setLiquidityProviderAddress(address _address) public onlyOwner { require(_address != address(0), "Zero address"); require(_address != address(this), "Wrong address"); AddressParam memory param = liquidityProviderAddressParam; if (param.timestamp == 0) { param.oldValue = _address; } else if (_paramUpdateDelayElapsed(param.timestamp)) { param.oldValue = param.newValue; } param.newValue = _address; param.timestamp = _now(); liquidityProviderAddressParam = param; emit LiquidityProviderAddressSet(_address, msg.sender); } /** * @return Returns true if param update delay elapsed. */ function _paramUpdateDelayElapsed(uint256 _paramTimestamp) internal view returns (bool) { return _now() > _paramTimestamp.add(PARAM_UPDATE_DELAY); } /** * @dev This method is used to deposit tokens to the deposit opened before. * It calls the internal "_deposit" method and transfers tokens from sender to contract. * Sender must approve tokens first. * * Instead this, user can use the simple "transferFrom" method of OVR token contract to make a deposit. * * @param _depositId User's unique deposit ID. * @param _amount The amount to deposit. */ function deposit(uint256 _depositId, uint256 _amount) public validDepositId(_depositId) isNotLocked isNotPaused isNotPausedDepositAndLockupExtensions { require(_amount > 0, "Amount should be more than 0"); _deposit(msg.sender, _depositId, _amount); _setLocked(true); require(token.transferFrom(msg.sender, address(this), _amount), "Transfer failed"); _setLocked(false); } /** * @param _sender The address of the sender. * @param _depositId User's deposit ID. * @param _amount The amount to deposit. */ function _deposit( address _sender, uint256 _depositId, uint256 _amount ) internal nonReentrant { uint256 currentBalance = getCurrentBalance(_depositId, _sender); uint256 finalBalance = calcRewards(_sender, _depositId); uint256 timestamp = _now(); balances[_sender][_depositId] = _amount.add(finalBalance); depositDates[_sender][_depositId] = _now(); emit Deposited(_sender, _depositId, _amount, currentBalance, timestamp); } /** * @dev This method is used to withdraw rewards and balance. * It calls the internal "_withdrawAll" method. * @param _depositId User's unique deposit ID */ function withdrawAll(uint256 _depositId) external balanceExists(_depositId) validDepositId(_depositId) isNotPaused { require(isLockupPeriodExpired(_depositId), "Too early, Lockup period"); _withdrawAll(msg.sender, _depositId); } function _withdrawAll(address _sender, uint256 _depositId) internal balanceExists(_depositId) validDepositId(_depositId) nonReentrant { uint256 currentBalance = getCurrentBalance(_depositId, _sender); uint256 finalBalance = calcRewards(_sender, _depositId); require(finalBalance > 0, "Nothing to withdraw"); balances[_sender][_depositId] = 0; _setLocked(true); require(tokenReward.transfer(_sender, finalBalance), "Liquidity pool transfer failed"); _setLocked(false); emit WithdrawnAll(_sender, _depositId, finalBalance, currentBalance, _now()); } /** * This method is used to extend lockup. It is available if your lockup period is expired and if depositId != 1 * It calls the internal "_extendLockup" method. * @param _depositId User's unique deposit ID */ function extendLockup(uint256 _depositId) external balanceExists(_depositId) validDepositId(_depositId) isNotPaused isNotPausedDepositAndLockupExtensions { require(_depositId != 1, "No lockup is set up"); _extendLockup(msg.sender, _depositId); } function _extendLockup(address _sender, uint256 _depositId) internal nonReentrant { uint256 timestamp = _now(); uint256 currentBalance = getCurrentBalance(_depositId, _sender); uint256 finalBalance = calcRewards(_sender, _depositId); balances[_sender][_depositId] = finalBalance; depositDates[_sender][_depositId] = timestamp; emit ExtendedLockup(_sender, _depositId, currentBalance, finalBalance, timestamp); } function isLockupPeriodExpired(uint256 _depositId) public view validDepositId(_depositId) returns (bool) { uint256 lockPeriod; if (_depositId == 1) { lockPeriod = 0; } else if (_depositId == 2) { lockPeriod = MONTH * 3; // 3 months } else if (_depositId == 3) { lockPeriod = MONTH * 6; // 6 months } else if (_depositId == 4) { lockPeriod = MONTH * 9; // 9 months } else if (_depositId == 5) { lockPeriod = MONTH * 12; // 12 months } if (_now() > depositDates[msg.sender][_depositId].add(lockPeriod)) { return true; } else { return false; } } function pow(int128 _x, uint256 _n) public pure returns (int128 r) { r = ABDKMath64x64.fromUInt(1); while (_n > 0) { if (_n % 2 == 1) { r = ABDKMath64x64.mul(r, _x); _n -= 1; } else { _x = ABDKMath64x64.mul(_x, _x); _n /= 2; } } } /** * This method is calcuate final compouded capital. * @param _principal User's balance * @param _ratio Interest rate * @param _n Periods is timestamp * @return finalBalance The final compounded capital * * A = C ( 1 + rate )^t */ function compound( uint256 _principal, uint256 _ratio, uint256 _n ) public view returns (uint256) { uint256 daysCount = _n.div(DAY); return ABDKMath64x64.mulu( pow(ABDKMath64x64.add(ABDKMath64x64.fromUInt(1), ABDKMath64x64.divu(_ratio, 10**18)), daysCount), _principal ); } /** * This moethod is used to calculate final compounded balance and is based on deposit duration and deposit id. * Each deposit mode is characterized by the lockup period and interest rate. * At the expiration of the lockup period the final compounded capital * will use minimum interest rate. * * This function can be called at any time to get the current total reward. * @param _sender Sender Address. * @param _depositId The depositId * @return finalBalance The final compounded capital */ function calcRewards(address _sender, uint256 _depositId) public view validDepositId(_depositId) returns (uint256) { uint256 timePassed = _now().sub(depositDates[_sender][_depositId]); uint256 currentBalance = getCurrentBalance(_depositId, _sender); uint256 finalBalance; uint256 ratio; uint256 lockPeriod; if (_depositId == 1) { ratio = 100000000000000; // APY 3.7% InterestRate = 0.01 lockPeriod = 0; } else if (_depositId == 2) { ratio = 300000000000000; // APY 11.6% InterestRate = 0.03 lockPeriod = MONTH * 3; // 3 months } else if (_depositId == 3) { ratio = 400000000000000; // APY 15.7% InterestRate = 0.04 lockPeriod = MONTH * 6; // 6 months } else if (_depositId == 4) { ratio = 600000000000000; // APY 25.5% InterestRate = 0.06 lockPeriod = MONTH * 9; // 9 months } else if (_depositId == 5) { ratio = 800000000000000; // APY 33.9% InterestRate = 0.08 lockPeriod = YEAR; // 12 months } // You can't have earnings without balance if (currentBalance == 0) { return finalBalance = 0; } // No lockup if (_depositId == 1) { finalBalance = compound(currentBalance, ratio, timePassed); return finalBalance; } // If you have an uncovered period from lockup, you still get rewards at the minimum rate if (timePassed > lockPeriod) { uint256 rewardsWithLockup = compound(currentBalance, ratio, lockPeriod).sub(currentBalance); finalBalance = compound(rewardsWithLockup.add(currentBalance), 100000000000000, timePassed.sub(lockPeriod)); return finalBalance; } finalBalance = compound(currentBalance, ratio, timePassed); return finalBalance; } function getCurrentBalance(uint256 _depositId, address _address) public view returns (uint256 addressBalance) { addressBalance = balances[_address][_depositId]; } /** * @return Returns current liquidity providers reward address. */ function liquidityProviderAddress() public view returns (address) { AddressParam memory param = liquidityProviderAddressParam; return param.newValue; } /** * @dev Sets lock to prevent reentrance. */ function _setLocked(bool _locked) internal { locked = _locked; } function senderCurrentBalance() public view returns (uint256) { return msg.sender.balance; } /** * @return Returns current timestamp. */ function _now() internal view returns (uint256) { // Note that the timestamp can have a 900-second error: // https://github.com/ethereum/wiki/blob/c02254611f218f43cbb07517ca8e5d00fd6d6d75/Block-Protocol-2.0.md // return now; // solium-disable-line security/no-block-members return block.timestamp; } }
0./ -0./ +Infinity./ -Infinity./ Canonical NaN value./* Convert signed 256-bit integer number into quadruple precision number. @param x signed 256-bit integer number @return quadruple precision number/ We rely on overflow behavior here
function fromInt(int256 x) internal pure returns (bytes16) { if (x == 0) return bytes16(0); else { uint256 result = uint256(x > 0 ? x : -x); uint256 msb = msb(result); if (msb < 112) result <<= 112 - msb; else if (msb > 112) result >>= msb - 112; result = (result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) | ((16383 + msb) << 112); if (x < 0) result |= 0x80000000000000000000000000000000; return bytes16(uint128(result)); } }
6,261,437
[ 1, 20, 18, 19, 300, 20, 18, 19, 397, 382, 7850, 18, 19, 300, 382, 7850, 18, 19, 19413, 10180, 460, 18, 19, 4037, 6726, 8303, 17, 3682, 3571, 1300, 1368, 9474, 86, 2268, 6039, 1300, 18, 225, 619, 6726, 8303, 17, 3682, 3571, 1300, 327, 9474, 86, 2268, 6039, 1300, 19, 1660, 21187, 603, 9391, 6885, 2674, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 628, 1702, 12, 474, 5034, 619, 13, 2713, 16618, 1135, 261, 3890, 2313, 13, 288, 203, 3639, 309, 261, 92, 422, 374, 13, 327, 1731, 2313, 12, 20, 1769, 203, 3639, 469, 288, 203, 5411, 2254, 5034, 563, 273, 2254, 5034, 12, 92, 405, 374, 692, 619, 294, 300, 92, 1769, 203, 203, 5411, 2254, 5034, 4086, 70, 273, 4086, 70, 12, 2088, 1769, 203, 5411, 309, 261, 959, 70, 411, 23543, 13, 563, 22789, 23543, 300, 4086, 70, 31, 203, 5411, 469, 309, 261, 959, 70, 405, 23543, 13, 563, 23359, 4086, 70, 300, 23543, 31, 203, 203, 5411, 563, 273, 261, 2088, 473, 374, 6356, 8998, 8998, 8998, 8998, 8998, 18343, 13, 571, 14015, 2313, 7414, 23, 397, 4086, 70, 13, 2296, 23543, 1769, 203, 5411, 309, 261, 92, 411, 374, 13, 563, 5626, 374, 92, 28, 12648, 12648, 12648, 17877, 31, 203, 203, 5411, 327, 1731, 2313, 12, 11890, 10392, 12, 2088, 10019, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.7.0; contract Owned { modifier onlyOwner() { require(msg.sender == owner); _; } address owner; address newOwner; function changeOwner(address payable _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { if (msg.sender == newOwner) { owner = newOwner; } } } contract ERC20 { string public symbol; string public name; uint8 public decimals; uint256 public totalSupply; mapping (address=>uint256) balances; mapping (address=>mapping (address=>uint256)) allowed; event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); function balanceOf(address _owner) view public returns (uint256 balance) {return balances[_owner];} function transfer(address _to, uint256 _amount) public returns (bool success) { require (balances[msg.sender]>=_amount&&_amount>0&&balances[_to]+_amount>balances[_to]); balances[msg.sender]-=_amount; balances[_to]+=_amount; emit Transfer(msg.sender,_to,_amount); return true; } function transferFrom(address _from,address _to,uint256 _amount) public returns (bool success) { require (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; emit Transfer(_from, _to, _amount); return true; } function approve(address _spender, uint256 _amount) public returns (bool success) { allowed[msg.sender][_spender]=_amount; emit Approval(msg.sender, _spender, _amount); return true; } function allowance(address _owner, address _spender) view public returns (uint256 remaining) { return allowed[_owner][_spender]; } } contract DOG is Owned,ERC20{ uint256 public maxSupply; constructor(address _owner) { symbol = "DOG"; name = "DogeCoin Cash"; decimals = 18; // 18 Decimals are Best for Liquidity totalSupply = 128275738389000000000000000000; // 128,275,738,389 is Total Supply ; Rest 18 Zeros are Decimals maxSupply = 128275738389000000000000000000; // 128,275,738,389 is Total Supply ; Rest 18 Zeros are Decimals owner = _owner; balances[owner] = totalSupply; } receive() external payable { revert(); } }
128,275,738,389 is Total Supply ; Rest 18 Zeros are Decimals
totalSupply = 128275738389000000000000000000;
601,913
[ 1, 10392, 16, 5324, 25, 16, 27, 7414, 16, 23, 6675, 353, 10710, 3425, 1283, 274, 6320, 6549, 2285, 4345, 854, 3416, 11366, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3639, 2078, 3088, 1283, 273, 8038, 5324, 10321, 7414, 23, 6675, 12648, 2787, 9449, 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 ]
/* Borther of Mongoose - $BOM https://t.me/brotherofmongoose */ // SPDX-License-Identifier: MIT pragma solidity 0.8.9; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; //event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); //function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface 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 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); } contract ERC20 is Context, IERC20, IERC20Metadata { 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; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _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: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @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 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 {} } 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; } } 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) { 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; } } library SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); /** * @dev Multiplies two int256 variables and fails on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; // Detect overflow when multiplying MIN_INT256 with -1 require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256)); require((b == 0) || (c / b == a)); return c; } /** * @dev Division of two int256 variables and fails on overflow. */ function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing MIN_INT256 by -1 require(b != -1 || a != MIN_INT256); // Solidity already throws when dividing by 0. return a / b; } /** * @dev Subtracts two int256 variables and fails on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two int256 variables and fails on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } /** * @dev Converts to absolute value, and fails on overflow. (easter egg from the genius dev @nomessages9.) */ function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } function toUint256Safe(int256 a) internal pure returns (uint256) { require(a >= 0); return uint256(a); } } library SafeMathUint { function toInt256Safe(uint256 a) internal pure returns (int256) { int256 b = int256(a); require(b >= 0); return b; } } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract BrotherofMongoose is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address public constant deadAddress = address(0xdead); bool private swapping; address payable private dev1Wallet; address payable private dev2Wallet; address payable private dev3Wallet; address payable private dev4Wallet; address payable private dev5Wallet; address payable public marketingWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; bool public limitsInEffect = false; bool public tradingActive = false; bool public swapEnabled = false; bool private gasLimitActive = true; uint256 private gasPriceLimit = 561 * 1 gwei; // do not allow over x gwei for launch // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch bool public transferDelayEnabled = true; uint256 public buyTotalDevFees; uint256 public sellTotalDevFees; uint256 private buyDev1Fee; uint256 private buyDev2Fee; uint256 private buyDev3Fee; uint256 private buyDev4Fee; uint256 private buyDev5Fee; uint256 public marketingFee; uint256 private sellDev1Fee; uint256 private sellDev2Fee; uint256 private sellDev3Fee; uint256 private sellDev4Fee; uint256 private sellDev5Fee; uint256 private tokensForDev1; uint256 private tokensForDev2; uint256 private tokensForDev3; uint256 private tokensForDev4; uint256 private tokensForDev5; uint256 private tokensForMarketing; /******************/ // exlcude from fees and max transaction amount mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event BuyBackTriggered(uint256 amount); event OwnerForcedSwapBack(uint256 timestamp); constructor() ERC20("Brother of Mongoose", "BOM") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyDev1Fee = 4; //main dev uint256 _buyDev2Fee = 3; //nft+p2e uint256 _buyDev3Fee = 2; //website development uint256 _buyDev4Fee = 2; //mods uint256 _buyDev5Fee = 1; //buybacks uint256 _marketingFee =3; //marketing uint256 _sellDev1Fee = 7; //main dev uint256 _sellDev2Fee = 3; //nft+p2e uint256 _sellDev3Fee = 2; //website development uint256 _sellDev4Fee = 2; //mods uint256 _sellDev5Fee = 1; //buybacks uint256 totalSupply = 1 * 1e12 * 1e18; maxTransactionAmount = totalSupply * 5 / 1000; // 0.5% maxTransactionAmountTxn maxWallet = totalSupply * 2 / 100; // 2% maxWallet swapTokensAtAmount = totalSupply * 5 / 10000; // 0.05% swap wallet buyDev1Fee = _buyDev1Fee; buyDev2Fee = _buyDev2Fee; buyDev3Fee = _buyDev3Fee; buyDev4Fee = _buyDev4Fee; buyDev5Fee = _buyDev5Fee; marketingFee = _marketingFee; sellDev1Fee = _sellDev1Fee; sellDev2Fee = _sellDev2Fee; sellDev3Fee = _sellDev3Fee; sellDev4Fee = _sellDev4Fee; sellDev5Fee = _sellDev5Fee; buyTotalDevFees = _buyDev1Fee + _buyDev2Fee + _buyDev3Fee + _buyDev4Fee + _buyDev5Fee; buyTotalDevFees += _marketingFee; sellTotalDevFees = _sellDev1Fee + _sellDev2Fee + _sellDev3Fee + _sellDev4Fee + _sellDev5Fee; dev1Wallet = payable(0xB8A3429ccC381AbA700B7008F68BB21F0AcA3b8c); // set as dev1 wallet dev2Wallet = payable(0xB8A3429ccC381AbA700B7008F68BB21F0AcA3b8c); // set as dev2 wallet dev3Wallet = payable(0xB8A3429ccC381AbA700B7008F68BB21F0AcA3b8c); // set as dev3 wallet dev4Wallet = payable(0xB8A3429ccC381AbA700B7008F68BB21F0AcA3b8c); // set as dev4 wallet dev5Wallet = payable(0xB8A3429ccC381AbA700B7008F68BB21F0AcA3b8c); // set as dev5 wallet marketingWallet = payable(0xB8A3429ccC381AbA700B7008F68BB21F0AcA3b8c); //marketing wallet // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromFees(marketingWallet, true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); excludeFromMaxTransaction(marketingWallet, true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(msg.sender, totalSupply); } receive() external payable { } // turn on trading function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; } // only for use in emergencies /*function disableTrading() external onlyOwner { tradingActive = false; swapEnabled = false; } */ //commenting out because we not beta // remove limits after token is stable function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; gasLimitActive = false; transferDelayEnabled = false; return true; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){ require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply."); swapTokensAtAmount = newAmount; return true; } function updateMaxAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.5%"); maxTransactionAmount = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } // only use to disable contract sales if absolutely necessary (emergency use only) function updateSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } // only use to prevent sniper buys in the first blocks. if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } //when buy if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } //when sell else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else { require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; // only take fees on buys/sells, do not take on wallet transfers if(takeFee){ // on sell if (automatedMarketMakerPairs[to] && sellTotalDevFees > 0){ fees = amount.mul(sellTotalDevFees).div(100); tokensForDev1 += fees * sellDev1Fee / sellTotalDevFees; tokensForDev2 += fees * sellDev2Fee / sellTotalDevFees; tokensForDev3 += fees * sellDev3Fee / sellTotalDevFees; tokensForDev4 += fees * sellDev4Fee / sellTotalDevFees; tokensForDev5 += fees * sellDev5Fee / sellTotalDevFees; } // on buy else if(automatedMarketMakerPairs[from] && buyTotalDevFees > 0) { fees = amount.mul(buyTotalDevFees).div(100); tokensForDev1 += fees * buyDev1Fee / buyTotalDevFees; tokensForDev2 += fees * buyDev2Fee / buyTotalDevFees; tokensForDev3 += fees * buyDev3Fee / buyTotalDevFees; tokensForDev4 += fees * buyDev4Fee / buyTotalDevFees; tokensForDev5 += fees * buyDev5Fee / buyTotalDevFees; tokensForMarketing += fees * marketingFee / buyTotalDevFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; //swapTokensForEth(fees); } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, 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 deadAddress, block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForDev1 + tokensForDev2 + tokensForDev3 + tokensForDev4 + tokensForDev5 + tokensForMarketing; if(contractBalance == 0 || totalTokensToSwap == 0) {return;} //uint256 initialETHBalance = address(this).balance; swapTokensForEth(totalTokensToSwap); uint256 ethBalance = address(this).balance; uint256 ethForDev1 = ethBalance.mul(tokensForDev1).div(totalTokensToSwap); uint256 ethForDev2 = ethBalance.mul(tokensForDev2).div(totalTokensToSwap); uint256 ethForDev3 = ethBalance.mul(tokensForDev3).div(totalTokensToSwap); uint256 ethForDev4 = ethBalance.mul(tokensForDev4).div(totalTokensToSwap); uint256 ethForDev5 = ethBalance.mul(tokensForDev5).div(totalTokensToSwap); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); tokensForDev1 = 0; tokensForDev2 = 0; tokensForDev3 = 0; tokensForDev4 = 0; tokensForDev5 = 0; tokensForMarketing = 0; (bool success,) = dev1Wallet.call{value: ethForDev1}(""); (success,) = dev2Wallet.call{value: ethForDev2}(""); (success,) = dev3Wallet.call{value: ethForDev3}(""); (success,) = dev4Wallet.call{value: ethForDev4}(""); (success,) = dev5Wallet.call{value: ethForDev5}(""); (success,) = marketingWallet.call{value: ethForMarketing}(""); } // force Swap back if slippage above 49% for launch. function forceSwapBack() external onlyOwner { uint256 contractBalance = balanceOf(address(this)); require(contractBalance >= totalSupply() / 100, "Can only swap back if more than 1% of tokens stuck on contract"); swapBack(); emit OwnerForcedSwapBack(block.timestamp); } // useful for buybacks or to reclaim any ETH on the contract in a way that helps holders. function buyBackTokens(uint256 ethAmountInWei) external onlyOwner { // generate the uniswap pair path of weth -> eth address[] memory path = new address[](2); path[0] = uniswapV2Router.WETH(); path[1] = address(this); // make the swap uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: ethAmountInWei}( 0, // accept any amount of Ethereum path, address(0xdead), block.timestamp ); emit BuyBackTriggered(ethAmountInWei); } }
set as dev5 wallet
dev5Wallet = payable(0xB8A3429ccC381AbA700B7008F68BB21F0AcA3b8c);
9,836,816
[ 1, 542, 487, 4461, 25, 9230, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 4461, 25, 16936, 273, 8843, 429, 12, 20, 20029, 28, 37, 5026, 5540, 952, 39, 7414, 21, 5895, 37, 26874, 38, 26874, 28, 42, 9470, 9676, 5340, 42, 20, 9988, 37, 23, 70, 28, 71, 1769, 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 ]
pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../HandlerBase.sol"; import "../weth/IWETH9.sol"; import "./ISwapRouter.sol"; import "./libraries/BytesLib.sol"; contract HUniswapV3 is HandlerBase { using SafeERC20 for IERC20; using SafeMath for uint256; using BytesLib for bytes; // prettier-ignore ISwapRouter public constant ROUTER = ISwapRouter(0xE592427A0AEce92De3Edee1F18E0157C05861564); // prettier-ignore IWETH9 public constant WETH = IWETH9(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); uint256 private constant PATH_SIZE = 43; // address + address + uint24 uint256 private constant ADDRESS_SIZE = 20; function getContractName() public pure override returns (string memory) { return "HUniswapV3"; } function exactInputSingleFromEther( address tokenOut, uint24 fee, uint256 amountIn, uint256 amountOutMinimum, uint160 sqrtPriceLimitX96 ) external payable returns (uint256 amountOut) { // Build params for router call ISwapRouter.ExactInputSingleParams memory params; params.tokenIn = address(WETH); params.tokenOut = tokenOut; params.fee = fee; params.amountIn = _getBalance(address(0), amountIn); params.amountOutMinimum = amountOutMinimum; params.sqrtPriceLimitX96 = sqrtPriceLimitX96; amountOut = _exactInputSingle(params.amountIn, params); _updateToken(tokenOut); } function exactInputSingleToEther( address tokenIn, uint24 fee, uint256 amountIn, uint256 amountOutMinimum, uint160 sqrtPriceLimitX96 ) external payable returns (uint256 amountOut) { // Build params for router call ISwapRouter.ExactInputSingleParams memory params; params.tokenIn = tokenIn; params.tokenOut = address(WETH); params.fee = fee; params.amountIn = _getBalance(tokenIn, amountIn); params.amountOutMinimum = amountOutMinimum; params.sqrtPriceLimitX96 = sqrtPriceLimitX96; // Approve token _tokenApprove(tokenIn, address(ROUTER), params.amountIn); amountOut = _exactInputSingle(0, params); WETH.withdraw(amountOut); } function exactInputSingle( address tokenIn, address tokenOut, uint24 fee, uint256 amountIn, uint256 amountOutMinimum, uint160 sqrtPriceLimitX96 ) external payable returns (uint256 amountOut) { // Build params for router call ISwapRouter.ExactInputSingleParams memory params; params.tokenIn = tokenIn; params.tokenOut = tokenOut; params.fee = fee; params.amountIn = _getBalance(tokenIn, amountIn); params.amountOutMinimum = amountOutMinimum; params.sqrtPriceLimitX96 = sqrtPriceLimitX96; // Approve token _tokenApprove(tokenIn, address(ROUTER), params.amountIn); amountOut = _exactInputSingle(0, params); _updateToken(tokenOut); } function exactInputFromEther( bytes memory path, uint256 amountIn, uint256 amountOutMinimum ) external payable returns (uint256 amountOut) { // Extract tokenIn and tokenOut address tokenIn = _getFirstToken(path); address tokenOut = _getLastToken(path); // Input token must be WETH if (tokenIn != address(WETH)) _revertMsg("exactInputFromEther", "Input not WETH"); // Build params for router call ISwapRouter.ExactInputParams memory params; params.path = path; params.amountIn = _getBalance(address(0), amountIn); params.amountOutMinimum = amountOutMinimum; amountOut = _exactInput(params.amountIn, params); _updateToken(tokenOut); } function exactInputToEther( bytes memory path, uint256 amountIn, uint256 amountOutMinimum ) external payable returns (uint256 amountOut) { // Extract tokenIn and tokenOut address tokenIn = _getFirstToken(path); address tokenOut = _getLastToken(path); // Output token must be WETH if (tokenOut != address(WETH)) _revertMsg("exactInputToEther", "Output not WETH"); // Build params for router call ISwapRouter.ExactInputParams memory params; params.path = path; params.amountIn = _getBalance(tokenIn, amountIn); params.amountOutMinimum = amountOutMinimum; // Approve token _tokenApprove(tokenIn, address(ROUTER), params.amountIn); amountOut = _exactInput(0, params); WETH.withdraw(amountOut); } function exactInput( bytes memory path, uint256 amountIn, uint256 amountOutMinimum ) external payable returns (uint256 amountOut) { // Extract tokenIn and tokenOut address tokenIn = _getFirstToken(path); address tokenOut = _getLastToken(path); // Build params for router call ISwapRouter.ExactInputParams memory params; params.path = path; params.amountIn = _getBalance(tokenIn, amountIn); params.amountOutMinimum = amountOutMinimum; // Approve token _tokenApprove(tokenIn, address(ROUTER), params.amountIn); amountOut = _exactInput(0, params); _updateToken(tokenOut); } function exactOutputSingleFromEther( address tokenOut, uint24 fee, uint256 amountOut, uint256 amountInMaximum, uint160 sqrtPriceLimitX96 ) external payable returns (uint256 amountIn) { // Build params for router call ISwapRouter.ExactOutputSingleParams memory params; params.tokenIn = address(WETH); params.tokenOut = tokenOut; params.fee = fee; params.amountOut = amountOut; // if amount == uint256(-1) return balance of Proxy params.amountInMaximum = _getBalance(address(0), amountInMaximum); params.sqrtPriceLimitX96 = sqrtPriceLimitX96; amountIn = _exactOutputSingle(params.amountInMaximum, params); ROUTER.refundETH(); _updateToken(tokenOut); } function exactOutputSingleToEther( address tokenIn, uint24 fee, uint256 amountOut, uint256 amountInMaximum, uint160 sqrtPriceLimitX96 ) external payable returns (uint256 amountIn) { // Build params for router call ISwapRouter.ExactOutputSingleParams memory params; params.tokenIn = tokenIn; params.tokenOut = address(WETH); params.fee = fee; params.amountOut = amountOut; // if amount == uint256(-1) return balance of Proxy params.amountInMaximum = _getBalance(tokenIn, amountInMaximum); params.sqrtPriceLimitX96 = sqrtPriceLimitX96; // Approve token _tokenApprove(params.tokenIn, address(ROUTER), params.amountInMaximum); amountIn = _exactOutputSingle(0, params); WETH.withdraw(params.amountOut); } function exactOutputSingle( address tokenIn, address tokenOut, uint24 fee, uint256 amountOut, uint256 amountInMaximum, uint160 sqrtPriceLimitX96 ) external payable returns (uint256 amountIn) { // Build params for router call ISwapRouter.ExactOutputSingleParams memory params; params.tokenIn = tokenIn; params.tokenOut = tokenOut; params.fee = fee; params.amountOut = amountOut; // if amount == uint256(-1) return balance of Proxy params.amountInMaximum = _getBalance(tokenIn, amountInMaximum); params.sqrtPriceLimitX96 = sqrtPriceLimitX96; // Approve token _tokenApprove(params.tokenIn, address(ROUTER), params.amountInMaximum); amountIn = _exactOutputSingle(0, params); _updateToken(params.tokenOut); } function exactOutputFromEther( bytes memory path, uint256 amountOut, uint256 amountInMaximum ) external payable returns (uint256 amountIn) { // Extract tokenIn and tokenOut // Note that the first token is tokenOut in exactOutput functions, vice versa address tokenIn = _getLastToken(path); address tokenOut = _getFirstToken(path); // Input token must be WETH if (tokenIn != address(WETH)) _revertMsg("exactOutputFromEther", "Input not WETH"); // Build params for router call ISwapRouter.ExactOutputParams memory params; params.path = path; params.amountOut = amountOut; params.amountInMaximum = _getBalance(address(0), amountInMaximum); amountIn = _exactOutput(params.amountInMaximum, params); ROUTER.refundETH(); _updateToken(tokenOut); } function exactOutputToEther( bytes memory path, uint256 amountOut, uint256 amountInMaximum ) external payable returns (uint256 amountIn) { // Extract tokenIn and tokenOut // Note that the first token is tokenOut in exactOutput functions, vice versa address tokenIn = _getLastToken(path); address tokenOut = _getFirstToken(path); // Out token must be WETH if (tokenOut != address(WETH)) _revertMsg("exactOutputToEther", "Output not WETH"); // Build params for router call ISwapRouter.ExactOutputParams memory params; params.path = path; params.amountOut = amountOut; // if amount == uint256(-1) return balance of Proxy params.amountInMaximum = _getBalance(tokenIn, amountInMaximum); // Approve token _tokenApprove(tokenIn, address(ROUTER), params.amountInMaximum); amountIn = _exactOutput(0, params); WETH.withdraw(amountOut); } function exactOutput( bytes memory path, uint256 amountOut, uint256 amountInMaximum ) external payable returns (uint256 amountIn) { // Extract tokenIn and tokenOut // Note that the first token is tokenOut in exactOutput functions, vice versa address tokenIn = _getLastToken(path); address tokenOut = _getFirstToken(path); // Build params for router call ISwapRouter.ExactOutputParams memory params; params.path = path; params.amountOut = amountOut; // if amount == uint256(-1) return balance of Proxy params.amountInMaximum = _getBalance(tokenIn, amountInMaximum); // Approve token _tokenApprove(tokenIn, address(ROUTER), params.amountInMaximum); amountIn = _exactOutput(0, params); _updateToken(tokenOut); } function _getFirstToken(bytes memory path) internal pure returns (address) { return path.toAddress(0); } function _getLastToken(bytes memory path) internal view returns (address) { if (path.length < PATH_SIZE) _revertMsg("General", "Path size too small"); return path.toAddress(path.length - ADDRESS_SIZE); } function _exactInputSingle( uint256 value, ISwapRouter.ExactInputSingleParams memory params ) internal returns (uint256) { params.deadline = now; params.recipient = address(this); try ROUTER.exactInputSingle{value: value}(params) returns ( uint256 amountOut ) { return amountOut; } catch Error(string memory reason) { _revertMsg("exactInputSingle", reason); } catch { _revertMsg("exactInputSingle"); } } function _exactInput( uint256 value, ISwapRouter.ExactInputParams memory params ) internal returns (uint256) { params.deadline = now; params.recipient = address(this); try ROUTER.exactInput{value: value}(params) returns ( uint256 amountOut ) { return amountOut; } catch Error(string memory reason) { _revertMsg("exactInput", reason); } catch { _revertMsg("exactInput"); } } function _exactOutputSingle( uint256 value, ISwapRouter.ExactOutputSingleParams memory params ) internal returns (uint256) { params.deadline = now; params.recipient = address(this); try ROUTER.exactOutputSingle{value: value}(params) returns ( uint256 amountIn ) { return amountIn; } catch Error(string memory reason) { _revertMsg("exactOutputSingle", reason); } catch { _revertMsg("exactOutputSingle"); } } function _exactOutput( uint256 value, ISwapRouter.ExactOutputParams memory params ) internal returns (uint256) { params.deadline = now; params.recipient = address(this); try ROUTER.exactOutput{value: value}(params) returns ( uint256 amountIn ) { return amountIn; } catch Error(string memory reason) { _revertMsg("exactOutput", reason); } catch { _revertMsg("exactOutput"); } } }
Build params for router call if amount == uint256(-1) return balance of Proxy Approve token
function exactOutputSingleToEther( address tokenIn, uint24 fee, uint256 amountOut, uint256 amountInMaximum, uint160 sqrtPriceLimitX96 ) external payable returns (uint256 amountIn) { ISwapRouter.ExactOutputSingleParams memory params; params.tokenIn = tokenIn; params.tokenOut = address(WETH); params.fee = fee; params.amountOut = amountOut; params.amountInMaximum = _getBalance(tokenIn, amountInMaximum); params.sqrtPriceLimitX96 = sqrtPriceLimitX96; _tokenApprove(params.tokenIn, address(ROUTER), params.amountInMaximum); amountIn = _exactOutputSingle(0, params); WETH.withdraw(params.amountOut); }
935,409
[ 1, 3116, 859, 364, 4633, 745, 309, 3844, 422, 2254, 5034, 19236, 21, 13, 327, 11013, 434, 7659, 1716, 685, 537, 1147, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 5565, 1447, 5281, 774, 41, 1136, 12, 203, 3639, 1758, 1147, 382, 16, 203, 3639, 2254, 3247, 14036, 16, 203, 3639, 2254, 5034, 3844, 1182, 16, 203, 3639, 2254, 5034, 3844, 382, 13528, 16, 203, 3639, 2254, 16874, 5700, 5147, 3039, 60, 10525, 203, 565, 262, 3903, 8843, 429, 1135, 261, 11890, 5034, 3844, 382, 13, 288, 203, 3639, 4437, 91, 438, 8259, 18, 14332, 1447, 5281, 1370, 3778, 859, 31, 203, 3639, 859, 18, 2316, 382, 273, 1147, 382, 31, 203, 3639, 859, 18, 2316, 1182, 273, 1758, 12, 59, 1584, 44, 1769, 203, 3639, 859, 18, 21386, 273, 14036, 31, 203, 3639, 859, 18, 8949, 1182, 273, 3844, 1182, 31, 203, 3639, 859, 18, 8949, 382, 13528, 273, 389, 588, 13937, 12, 2316, 382, 16, 3844, 382, 13528, 1769, 203, 3639, 859, 18, 24492, 5147, 3039, 60, 10525, 273, 5700, 5147, 3039, 60, 10525, 31, 203, 203, 3639, 389, 2316, 12053, 537, 12, 2010, 18, 2316, 382, 16, 1758, 12, 1457, 1693, 654, 3631, 859, 18, 8949, 382, 13528, 1769, 203, 3639, 3844, 382, 273, 389, 17165, 1447, 5281, 12, 20, 16, 859, 1769, 203, 3639, 678, 1584, 44, 18, 1918, 9446, 12, 2010, 18, 8949, 1182, 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 ]
//SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; import "@openzeppelin/contracts/interfaces/IERC165.sol"; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "./Controllable.sol"; import "./ITokenSale.sol"; /// tokensale implementation contract TokenSale is ITokenSale, Controllable, Initializable { address private payee; address private soldToken; uint256 private salePrice_; uint256 private issueCount; uint256 private maxCount; uint256 private vipReserve; uint256 private vipIssued; TokenMinting[] private _purchasers; TokenMinting[] private _mintees; address private _partner; uint256 private _permill; bool private _openState; /// @notice Called to purchase some quantity of a token /// @param _soldToken - the erc721 address /// @param _salePrice - the sale price /// @param _maxCount - the max quantity /// @param _vipReserve - the vip reserve to set aside for minting directly constructor(address _soldToken, uint256 _salePrice, uint256 _maxCount, uint256 _vipReserve) { _addController(msg.sender); payee = msg.sender; soldToken = _soldToken; salePrice_ = _salePrice; issueCount = 0; maxCount = _maxCount; vipReserve = _vipReserve; vipIssued = 0; } /// @dev called after constructor once to init stuff function initialize(address partner, uint256 permill) public initializer { require(IMintable(soldToken).getMinter() == address(this), "soldToken must be controllable by this contract"); _partner = partner; _permill = permill; } /// @dev create a token hash using the address of this objcet, sender address and the current issue count function _createTokenHash() internal view returns (uint256) { return uint256(keccak256(abi.encodePacked(address(this), msg.sender, issueCount))); } /// @notice Called to purchase some quantity of a token /// @param receiver - the address of the account receiving the item /// @param quantity - the quantity to purchase. max 5. function purchase(address receiver, uint256 quantity) external payable override returns (TokenMinting[] memory mintings) { require(issueCount + quantity + vipReserve <= maxCount, "cannot purchase more than maxCount"); require(salePrice_ * quantity <= msg.value, "must attach funds to purchase items"); require(quantity > 0 && quantity <= 5, "cannot purchase more than 5 items"); require(_openState, "cannot mint when tokensale is closed"); // mint the desired tokens to the receiver mintings = new TokenMinting[](quantity); for(uint256 i = 0; i < quantity; i++) { TokenMinting memory _minting = TokenMinting(receiver, _createTokenHash()); // create a record of this new minting _purchasers.push(_minting); // and get a refence to it mintings[i] = _minting; issueCount = issueCount + 1; // mint the token IMintable(soldToken).mint(receiver, _minting.tokenHash); // emit an event to that respect emit TokenMinted(receiver, _minting.tokenHash, 0); } uint256 partnerShare = 0; // transfer to partner share if(_partner != address(0) && _permill > 0) { partnerShare = msg.value * _permill / 1000000; payable(_partner).transfer(partnerShare); } uint256 ourShare = msg.value - partnerShare; payable(payee).transfer(ourShare); } /// @notice returns the sale price in ETH for the given quantity. /// @param quantity - the quantity to purchase. max 5. /// @return price - the sale price for the given quantity function salePrice(uint256 quantity) external view override returns (uint256 price) { price = salePrice_ * quantity; } /// @notice Mint a specific tokenhash to a specific address ( up to har-cap limit) /// only for controller of token /// @param receiver - the address of the account receiving the item /// @param tokenHash - token hash to mint to the receiver function mint(address receiver, uint256 tokenHash) external override onlyController { require(vipIssued < vipReserve, "cannot mint more than the reserve"); require(issueCount < maxCount, "cannot mint more than maxCount"); vipIssued = vipIssued + 1; issueCount = issueCount + 1; _mintees.push(TokenMinting(receiver, _createTokenHash())); IMintable(soldToken).mint(receiver, tokenHash); // emit an event to that respect emit TokenMinted(receiver, tokenHash, 1); } /// @notice set the revenue partner on this tokensale. we split revenue with the partner /// only for controller of token /// @param partner - the address of the partner. will receive x%% of the revenue /// @param permill - permilliage of the revenue to be split. min 0 max 1000000 function setRevenuePartner(address partner, uint256 permill) external override onlyController { require(permill >= 0 && permill <= 1000000, "permill must be between 0 and 1000000"); _partner = partner; _permill = permill; emit RevenuePartnerChanged(partner, permill); } /// @notice get the revenue partner on this tokensale. we split revenue with the partner /// @return partner - the address of the partner. will receive x%% of the revenue /// @return permill - permilliage of the revenue to be split. permill = 1 / 1000000 function getRevenuePartner() external view override returns (address partner, uint256 permill) { return (_partner, _permill); } /// @notice open / close the tokensale /// only for controller of token /// @param openState - the open state of the tokensale function setOpenState(bool openState) external override onlyController { _openState = openState; } /// @notice get the token sale open state /// @return openState - the open state of the tokensale function getOpenState() external view override returns (bool openState) { openState = _openState; } /// @notice set the psale price /// only for controller of token /// @param _salePrice - the open state of the tokensale function setSalePrice(uint256 _salePrice) external override onlyController { require(salePrice_ > 0, "salePrice must be greater than 0"); salePrice_ = _salePrice; } /// @notice get the token sale price /// @return salePrice - the open state of the tokensale function getSalePrice() external view override returns (uint256) { return salePrice_; } /// @notice set the psale price /// only for controller of token /// @param _payee - the open state of the tokensale function setPayee(address _payee) external override onlyController { require(_payee != address(0), "payee cannoot be zero address"); payee = _payee; emit PayeeChanged(payee); } /// @notice get the token sale price /// @return salePrice - the open state of the tokensale function getPayee() external view override returns (address) { return payee; } /// @notice get the address of the sole token /// @return token - the address of the sole token function getSaleToken() external view override returns (address token) { return soldToken; } /// @notice get the total list of purchasers /// @return _list - total list of purchasers function purchaserList() external view override returns (TokenMinting[] memory _list) { _list = _purchasers; } /// @notice get the total list of minters /// @return _list - total list of purchasers function minterList() external view override returns (TokenMinting[] memory _list) { _list = _mintees; } }
@dev called after constructor once to init stuff
function initialize(address partner, uint256 permill) public initializer { require(IMintable(soldToken).getMinter() == address(this), "soldToken must be controllable by this contract"); _partner = partner; _permill = permill; }
15,835,798
[ 1, 11777, 1839, 3885, 3647, 358, 1208, 10769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4046, 12, 2867, 19170, 16, 2254, 5034, 4641, 737, 13, 1071, 12562, 288, 203, 3639, 2583, 12, 3445, 474, 429, 12, 87, 1673, 1345, 2934, 588, 49, 2761, 1435, 422, 1758, 12, 2211, 3631, 315, 87, 1673, 1345, 1297, 506, 466, 30453, 635, 333, 6835, 8863, 203, 3639, 389, 31993, 273, 19170, 31, 203, 3639, 389, 12160, 737, 273, 4641, 737, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.1; /** * @title Linked to ILV Marker Interface * * @notice Marks smart contracts which are linked to IlluviumERC20 token instance upon construction, * all these smart contracts share a common ilv() address getter * * @notice Implementing smart contracts MUST verify that they get linked to real IlluviumERC20 instance * and that ilv() getter returns this very same instance address * * @author Basil Gorin */ interface ILinkedToILV { /** * @notice Getter for a verified IlluviumERC20 instance address * * @return IlluviumERC20 token instance address smart contract is linked to */ function ilv() external view returns (address); } /** * @title Illuvium Pool * * @notice An abstraction representing a pool, see IlluviumPoolBase for details * * @author Pedro Bergamini, reviewed by Basil Gorin */ interface IPool is ILinkedToILV { /** * @dev Deposit is a key data structure used in staking, * it represents a unit of stake with its amount, weight and term (time interval) */ struct Deposit { // @dev token amount staked uint256 tokenAmount; // @dev stake weight uint256 weight; // @dev locking period - from uint64 lockedFrom; // @dev locking period - until uint64 lockedUntil; // @dev indicates if the stake was created as a yield reward bool isYield; } // for the rest of the functions see Soldoc in IlluviumPoolBase function silv() external view returns (address); function poolToken() external view returns (address); function isFlashPool() external view returns (bool); function weight() external view returns (uint32); function lastYieldDistribution() external view returns (uint64); function yieldRewardsPerWeight() external view returns (uint256); function usersLockingWeight() external view returns (uint256); function pendingYieldRewards(address _user) external view returns (uint256); function balanceOf(address _user) external view returns (uint256); function getDeposit(address _user, uint256 _depositId) external view returns (Deposit memory); function getDepositsLength(address _user) external view returns (uint256); function stake( uint256 _amount, uint64 _lockedUntil, bool useSILV ) external; function unstake( uint256 _depositId, uint256 _amount, bool useSILV ) external; function sync() external; function processRewards(bool useSILV) external; function setWeight(uint32 _weight) external; } interface ICorePool is IPool { function vaultRewardsPerToken() external view returns (uint256); function poolTokenReserve() external view returns (uint256); function stakeAsPool(address _staker, uint256 _amount) external; function receiveVaultRewards(uint256 _amount) external; } /** * @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; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { address msgSender = msg.sender; _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() == msg.sender, "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @title Address Utils * * @dev Utility library of inline functions on addresses * * @author Basil Gorin */ library AddressUtils { /** * @notice Checks if 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) { // a variable to load `extcodesize` to uint256 size = 0; // 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. // solium-disable-next-line security/no-inline-assembly assembly { // retrieve the size of the code at address `addr` size := extcodesize(addr) } // positive size indicates a smart contract address return size > 0; } } /** * @title ERC20 token receiver interface * * @dev Interface for any contract that wants to support safe transfers * from ERC20 token smart contracts. * @dev Inspired by ERC721 and ERC223 token standards * * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md * @dev See https://github.com/ethereum/EIPs/issues/223 * * @author Basil Gorin */ interface ERC20Receiver { /** * @notice Handle the receipt of a ERC20 token(s) * @dev The ERC20 smart contract calls this function on the recipient * after a successful transfer (`safeTransferFrom`). * This function MAY throw to revert and reject the transfer. * Return of other than the magic value MUST result in the transaction being reverted. * @notice The contract address is always the message sender. * A wallet/broker/auction application MUST implement the wallet interface * if it will accept safe transfers. * @param _operator The address which called `safeTransferFrom` function * @param _from The address which previously owned the token * @param _value amount of tokens which is being transferred * @param _data additional data with no specified format * @return `bytes4(keccak256("onERC20Received(address,address,uint256,bytes)"))` unless throwing */ function onERC20Received(address _operator, address _from, uint256 _value, bytes calldata _data) external returns(bytes4); } /** * @title Access Control List * * @notice Access control smart contract provides an API to check * if specific operation is permitted globally and/or * if particular user has a permission to execute it. * * @notice It deals with two main entities: features and roles. * * @notice Features are designed to be used to enable/disable specific * functions (public functions) of the smart contract for everyone. * @notice User roles are designed to restrict access to specific * functions (restricted functions) of the smart contract to some users. * * @notice Terms "role", "permissions" and "set of permissions" have equal meaning * in the documentation text and may be used interchangeably. * @notice Terms "permission", "single permission" implies only one permission bit set. * * @dev This smart contract is designed to be inherited by other * smart contracts which require access control management capabilities. * * @author Basil Gorin */ contract AccessControl { /** * @notice Access manager is responsible for assigning the roles to users, * enabling/disabling global features of the smart contract * @notice Access manager can add, remove and update user roles, * remove and update global features * * @dev Role ROLE_ACCESS_MANAGER allows modifying user roles and global features * @dev Role ROLE_ACCESS_MANAGER has single bit at position 255 enabled */ uint256 public constant ROLE_ACCESS_MANAGER = 0x8000000000000000000000000000000000000000000000000000000000000000; /** * @dev Bitmask representing all the possible permissions (super admin role) * @dev Has all the bits are enabled (2^256 - 1 value) */ uint256 private constant FULL_PRIVILEGES_MASK = type(uint256).max; // before 0.8.0: uint256(-1) overflows to 0xFFFF... /** * @notice Privileged addresses with defined roles/permissions * @notice In the context of ERC20/ERC721 tokens these can be permissions to * allow minting or burning tokens, transferring on behalf and so on * * @dev Maps user address to the permissions bitmask (role), where each bit * represents a permission * @dev Bitmask 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF * represents all possible permissions * @dev Zero address mapping represents global features of the smart contract */ mapping(address => uint256) public userRoles; /** * @dev Fired in updateRole() and updateFeatures() * * @param _by operator which called the function * @param _to address which was granted/revoked permissions * @param _requested permissions requested * @param _actual permissions effectively set */ event RoleUpdated(address indexed _by, address indexed _to, uint256 _requested, uint256 _actual); /** * @notice Creates an access control instance, * setting contract creator to have full privileges */ constructor() { // contract creator has full privileges userRoles[msg.sender] = FULL_PRIVILEGES_MASK; } /** * @notice Retrieves globally set of features enabled * * @dev Auxiliary getter function to maintain compatibility with previous * versions of the Access Control List smart contract, where * features was a separate uint256 public field * * @return 256-bit bitmask of the features enabled */ function features() public view returns(uint256) { // according to new design features are stored in zero address // mapping of `userRoles` structure return userRoles[address(0)]; } /** * @notice Updates set of the globally enabled features (`features`), * taking into account sender's permissions * * @dev Requires transaction sender to have `ROLE_ACCESS_MANAGER` permission * @dev Function is left for backward compatibility with older versions * * @param _mask bitmask representing a set of features to enable/disable */ function updateFeatures(uint256 _mask) public { // delegate call to `updateRole` updateRole(address(0), _mask); } /** * @notice Updates set of permissions (role) for a given user, * taking into account sender's permissions. * * @dev Setting role to zero is equivalent to removing an all permissions * @dev Setting role to `FULL_PRIVILEGES_MASK` is equivalent to * copying senders' permissions (role) to the user * @dev Requires transaction sender to have `ROLE_ACCESS_MANAGER` permission * * @param operator address of a user to alter permissions for or zero * to alter global features of the smart contract * @param role bitmask representing a set of permissions to * enable/disable for a user specified */ function updateRole(address operator, uint256 role) public { // caller must have a permission to update user roles require(isSenderInRole(ROLE_ACCESS_MANAGER), "insufficient privileges (ROLE_ACCESS_MANAGER required)"); // evaluate the role and reassign it userRoles[operator] = evaluateBy(msg.sender, userRoles[operator], role); // fire an event emit RoleUpdated(msg.sender, operator, role, userRoles[operator]); } /** * @notice Determines the permission bitmask an operator can set on the * target permission set * @notice Used to calculate the permission bitmask to be set when requested * in `updateRole` and `updateFeatures` functions * * @dev Calculated based on: * 1) operator's own permission set read from userRoles[operator] * 2) target permission set - what is already set on the target * 3) desired permission set - what do we want set target to * * @dev Corner cases: * 1) Operator is super admin and its permission set is `FULL_PRIVILEGES_MASK`: * `desired` bitset is returned regardless of the `target` permission set value * (what operator sets is what they get) * 2) Operator with no permissions (zero bitset): * `target` bitset is returned regardless of the `desired` value * (operator has no authority and cannot modify anything) * * @dev Example: * Consider an operator with the permissions bitmask 00001111 * is about to modify the target permission set 01010101 * Operator wants to set that permission set to 00110011 * Based on their role, an operator has the permissions * to update only lowest 4 bits on the target, meaning that * high 4 bits of the target set in this example is left * unchanged and low 4 bits get changed as desired: 01010011 * * @param operator address of the contract operator which is about to set the permissions * @param target input set of permissions to operator is going to modify * @param desired desired set of permissions operator would like to set * @return resulting set of permissions given operator will set */ function evaluateBy(address operator, uint256 target, uint256 desired) public view returns(uint256) { // read operator's permissions uint256 p = userRoles[operator]; // taking into account operator's permissions, // 1) enable the permissions desired on the `target` target |= p & desired; // 2) disable the permissions desired on the `target` target &= FULL_PRIVILEGES_MASK ^ (p & (FULL_PRIVILEGES_MASK ^ desired)); // return calculated result return target; } /** * @notice Checks if requested set of features is enabled globally on the contract * * @param required set of features to check against * @return true if all the features requested are enabled, false otherwise */ function isFeatureEnabled(uint256 required) public view returns(bool) { // delegate call to `__hasRole`, passing `features` property return __hasRole(features(), required); } /** * @notice Checks if transaction sender `msg.sender` has all the permissions required * * @param required set of permissions (role) to check against * @return true if all the permissions requested are enabled, false otherwise */ function isSenderInRole(uint256 required) public view returns(bool) { // delegate call to `isOperatorInRole`, passing transaction sender return isOperatorInRole(msg.sender, required); } /** * @notice Checks if operator has all the permissions (role) required * * @param operator address of the user to check role for * @param required set of permissions (role) to check * @return true if all the permissions requested are enabled, false otherwise */ function isOperatorInRole(address operator, uint256 required) public view returns(bool) { // delegate call to `__hasRole`, passing operator's permissions (role) return __hasRole(userRoles[operator], required); } /** * @dev Checks if role `actual` contains all the permissions required `required` * * @param actual existent role * @param required required role * @return true if actual has required role (all permissions), false otherwise */ function __hasRole(uint256 actual, uint256 required) internal pure returns(bool) { // check the bitmask for the role required and return the result return actual & required == required; } } /** * @title Illuvium (ILV) ERC20 token * * @notice Illuvium is a core ERC20 token powering the game. * It serves as an in-game currency, is tradable on exchanges, * it powers up the governance protocol (Illuvium DAO) and participates in Yield Farming. * * @dev Token Summary: * - Symbol: ILV * - Name: Illuvium * - Decimals: 18 * - Initial token supply: 7,000,000 ILV * - Maximum final token supply: 10,000,000 ILV * - Up to 3,000,000 ILV may get minted in 3 years period via yield farming * - Mintable: total supply may increase * - Burnable: total supply may decrease * * @dev Token balances and total supply are effectively 192 bits long, meaning that maximum * possible total supply smart contract is able to track is 2^192 (close to 10^40 tokens) * * @dev Smart contract doesn't use safe math. All arithmetic operations are overflow/underflow safe. * Additionally, Solidity 0.8.1 enforces overflow/underflow safety. * * @dev ERC20: reviewed according to https://eips.ethereum.org/EIPS/eip-20 * * @dev ERC20: contract has passed OpenZeppelin ERC20 tests, * see https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/test/token/ERC20/ERC20.behavior.js * see https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/test/token/ERC20/ERC20.test.js * see adopted copies of these tests in the `test` folder * * @dev ERC223/ERC777: not supported; * send tokens via `safeTransferFrom` and implement `ERC20Receiver.onERC20Received` on the receiver instead * * @dev Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) - resolved * Related events and functions are marked with "ISBN:978-1-7281-3027-9" tag: * - event Transferred(address indexed _by, address indexed _from, address indexed _to, uint256 _value) * - event Approved(address indexed _owner, address indexed _spender, uint256 _oldValue, uint256 _value) * - function increaseAllowance(address _spender, uint256 _value) public returns (bool) * - function decreaseAllowance(address _spender, uint256 _value) public returns (bool) * See: https://ieeexplore.ieee.org/document/8802438 * See: https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * @author Basil Gorin */ contract IlluviumERC20 is AccessControl { /** * @dev Smart contract unique identifier, a random number * @dev Should be regenerated each time smart contact source code is changed * and changes smart contract itself is to be redeployed * @dev Generated using https://www.random.org/bytes/ */ uint256 public constant TOKEN_UID = 0x83ecb176af7c4f35a45ff0018282e3a05a1018065da866182df12285866f5a2c; /** * @notice Name of the token: Illuvium * * @notice ERC20 name of the token (long name) * * @dev ERC20 `function name() public view returns (string)` * * @dev Field is declared public: getter name() is created when compiled, * it returns the name of the token. */ string public constant name = "Illuvium"; /** * @notice Symbol of the token: ILV * * @notice ERC20 symbol of that token (short name) * * @dev ERC20 `function symbol() public view returns (string)` * * @dev Field is declared public: getter symbol() is created when compiled, * it returns the symbol of the token */ string public constant symbol = "ILV"; /** * @notice Decimals of the token: 18 * * @dev ERC20 `function decimals() public view returns (uint8)` * * @dev Field is declared public: getter decimals() is created when compiled, * it returns the number of decimals used to get its user representation. * For example, if `decimals` equals `6`, a balance of `1,500,000` tokens should * be displayed to a user as `1,5` (`1,500,000 / 10 ** 6`). * * @dev NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including balanceOf() and transfer(). */ uint8 public constant decimals = 18; /** * @notice Total supply of the token: initially 7,000,000, * with the potential to grow up to 10,000,000 during yield farming period (3 years) * * @dev ERC20 `function totalSupply() public view returns (uint256)` * * @dev Field is declared public: getter totalSupply() is created when compiled, * it returns the amount of tokens in existence. */ uint256 public totalSupply; // is set to 7 million * 10^18 in the constructor /** * @dev A record of all the token balances * @dev This mapping keeps record of all token owners: * owner => balance */ mapping(address => uint256) public tokenBalances; /** * @notice A record of each account's voting delegate * * @dev Auxiliary data structure used to sum up an account's voting power * * @dev This mapping keeps record of all voting power delegations: * voting delegator (token owner) => voting delegate */ mapping(address => address) public votingDelegates; /** * @notice A voting power record binds voting power of a delegate to a particular * block when the voting power delegation change happened */ struct VotingPowerRecord { /* * @dev block.number when delegation has changed; starting from * that block voting power value is in effect */ uint64 blockNumber; /* * @dev cumulative voting power a delegate has obtained starting * from the block stored in blockNumber */ uint192 votingPower; } /** * @notice A record of each account's voting power * * @dev Primarily data structure to store voting power for each account. * Voting power sums up from the account's token balance and delegated * balances. * * @dev Stores current value and entire history of its changes. * The changes are stored as an array of checkpoints. * Checkpoint is an auxiliary data structure containing voting * power (number of votes) and block number when the checkpoint is saved * * @dev Maps voting delegate => voting power record */ mapping(address => VotingPowerRecord[]) public votingPowerHistory; /** * @dev A record of nonces for signing/validating signatures in `delegateWithSig` * for every delegate, increases after successful validation * * @dev Maps delegate address => delegate nonce */ mapping(address => uint256) public nonces; /** * @notice A record of all the allowances to spend tokens on behalf * @dev Maps token owner address to an address approved to spend * some tokens on behalf, maps approved address to that amount * @dev owner => spender => value */ mapping(address => mapping(address => uint256)) public transferAllowances; /** * @notice Enables ERC20 transfers of the tokens * (transfer by the token owner himself) * @dev Feature FEATURE_TRANSFERS must be enabled in order for * `transfer()` function to succeed */ uint32 public constant FEATURE_TRANSFERS = 0x0000_0001; /** * @notice Enables ERC20 transfers on behalf * (transfer by someone else on behalf of token owner) * @dev Feature FEATURE_TRANSFERS_ON_BEHALF must be enabled in order for * `transferFrom()` function to succeed * @dev Token owner must call `approve()` first to authorize * the transfer on behalf */ uint32 public constant FEATURE_TRANSFERS_ON_BEHALF = 0x0000_0002; /** * @dev Defines if the default behavior of `transfer` and `transferFrom` * checks if the receiver smart contract supports ERC20 tokens * @dev When feature FEATURE_UNSAFE_TRANSFERS is enabled the transfers do not * check if the receiver smart contract supports ERC20 tokens, * i.e. `transfer` and `transferFrom` behave like `unsafeTransferFrom` * @dev When feature FEATURE_UNSAFE_TRANSFERS is disabled (default) the transfers * check if the receiver smart contract supports ERC20 tokens, * i.e. `transfer` and `transferFrom` behave like `safeTransferFrom` */ uint32 public constant FEATURE_UNSAFE_TRANSFERS = 0x0000_0004; /** * @notice Enables token owners to burn their own tokens, * including locked tokens which are burnt first * @dev Feature FEATURE_OWN_BURNS must be enabled in order for * `burn()` function to succeed when called by token owner */ uint32 public constant FEATURE_OWN_BURNS = 0x0000_0008; /** * @notice Enables approved operators to burn tokens on behalf of their owners, * including locked tokens which are burnt first * @dev Feature FEATURE_OWN_BURNS must be enabled in order for * `burn()` function to succeed when called by approved operator */ uint32 public constant FEATURE_BURNS_ON_BEHALF = 0x0000_0010; /** * @notice Enables delegators to elect delegates * @dev Feature FEATURE_DELEGATIONS must be enabled in order for * `delegate()` function to succeed */ uint32 public constant FEATURE_DELEGATIONS = 0x0000_0020; /** * @notice Enables delegators to elect delegates on behalf * (via an EIP712 signature) * @dev Feature FEATURE_DELEGATIONS must be enabled in order for * `delegateWithSig()` function to succeed */ uint32 public constant FEATURE_DELEGATIONS_ON_BEHALF = 0x0000_0040; /** * @notice Token creator is responsible for creating (minting) * tokens to an arbitrary address * @dev Role ROLE_TOKEN_CREATOR allows minting tokens * (calling `mint` function) */ uint32 public constant ROLE_TOKEN_CREATOR = 0x0001_0000; /** * @notice Token destroyer is responsible for destroying (burning) * tokens owned by an arbitrary address * @dev Role ROLE_TOKEN_DESTROYER allows burning tokens * (calling `burn` function) */ uint32 public constant ROLE_TOKEN_DESTROYER = 0x0002_0000; /** * @notice ERC20 receivers are allowed to receive tokens without ERC20 safety checks, * which may be useful to simplify tokens transfers into "legacy" smart contracts * @dev When `FEATURE_UNSAFE_TRANSFERS` is not enabled addresses having * `ROLE_ERC20_RECEIVER` permission are allowed to receive tokens * via `transfer` and `transferFrom` functions in the same way they * would via `unsafeTransferFrom` function * @dev When `FEATURE_UNSAFE_TRANSFERS` is enabled `ROLE_ERC20_RECEIVER` permission * doesn't affect the transfer behaviour since * `transfer` and `transferFrom` behave like `unsafeTransferFrom` for any receiver * @dev ROLE_ERC20_RECEIVER is a shortening for ROLE_UNSAFE_ERC20_RECEIVER */ uint32 public constant ROLE_ERC20_RECEIVER = 0x0004_0000; /** * @notice ERC20 senders are allowed to send tokens without ERC20 safety checks, * which may be useful to simplify tokens transfers into "legacy" smart contracts * @dev When `FEATURE_UNSAFE_TRANSFERS` is not enabled senders having * `ROLE_ERC20_SENDER` permission are allowed to send tokens * via `transfer` and `transferFrom` functions in the same way they * would via `unsafeTransferFrom` function * @dev When `FEATURE_UNSAFE_TRANSFERS` is enabled `ROLE_ERC20_SENDER` permission * doesn't affect the transfer behaviour since * `transfer` and `transferFrom` behave like `unsafeTransferFrom` for any receiver * @dev ROLE_ERC20_SENDER is a shortening for ROLE_UNSAFE_ERC20_SENDER */ uint32 public constant ROLE_ERC20_SENDER = 0x0008_0000; /** * @dev Magic value to be returned by ERC20Receiver upon successful reception of token(s) * @dev Equal to `bytes4(keccak256("onERC20Received(address,address,uint256,bytes)"))`, * which can be also obtained as `ERC20Receiver(address(0)).onERC20Received.selector` */ bytes4 private constant ERC20_RECEIVED = 0x4fc35859; /** * @notice EIP-712 contract's domain typeHash, see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash */ bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /** * @notice EIP-712 delegation struct typeHash, see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash */ bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegate,uint256 nonce,uint256 expiry)"); /** * @dev Fired in transfer(), transferFrom() and some other (non-ERC20) functions * * @dev ERC20 `event Transfer(address indexed _from, address indexed _to, uint256 _value)` * * @param _from an address tokens were consumed from * @param _to an address tokens were sent to * @param _value number of tokens transferred */ event Transfer(address indexed _from, address indexed _to, uint256 _value); /** * @dev Fired in approve() and approveAtomic() functions * * @dev ERC20 `event Approval(address indexed _owner, address indexed _spender, uint256 _value)` * * @param _owner an address which granted a permission to transfer * tokens on its behalf * @param _spender an address which received a permission to transfer * tokens on behalf of the owner `_owner` * @param _value amount of tokens granted to transfer on behalf */ event Approval(address indexed _owner, address indexed _spender, uint256 _value); /** * @dev Fired in mint() function * * @param _by an address which minted some tokens (transaction sender) * @param _to an address the tokens were minted to * @param _value an amount of tokens minted */ event Minted(address indexed _by, address indexed _to, uint256 _value); /** * @dev Fired in burn() function * * @param _by an address which burned some tokens (transaction sender) * @param _from an address the tokens were burnt from * @param _value an amount of tokens burnt */ event Burnt(address indexed _by, address indexed _from, uint256 _value); /** * @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) * * @dev Similar to ERC20 Transfer event, but also logs an address which executed transfer * * @dev Fired in transfer(), transferFrom() and some other (non-ERC20) functions * * @param _by an address which performed the transfer * @param _from an address tokens were consumed from * @param _to an address tokens were sent to * @param _value number of tokens transferred */ event Transferred(address indexed _by, address indexed _from, address indexed _to, uint256 _value); /** * @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) * * @dev Similar to ERC20 Approve event, but also logs old approval value * * @dev Fired in approve() and approveAtomic() functions * * @param _owner an address which granted a permission to transfer * tokens on its behalf * @param _spender an address which received a permission to transfer * tokens on behalf of the owner `_owner` * @param _oldValue previously granted amount of tokens to transfer on behalf * @param _value new granted amount of tokens to transfer on behalf */ event Approved(address indexed _owner, address indexed _spender, uint256 _oldValue, uint256 _value); /** * @dev Notifies that a key-value pair in `votingDelegates` mapping has changed, * i.e. a delegator address has changed its delegate address * * @param _of delegator address, a token owner * @param _from old delegate, an address which delegate right is revoked * @param _to new delegate, an address which received the voting power */ event DelegateChanged(address indexed _of, address indexed _from, address indexed _to); /** * @dev Notifies that a key-value pair in `votingPowerHistory` mapping has changed, * i.e. a delegate's voting power has changed. * * @param _of delegate whose voting power has changed * @param _fromVal previous number of votes delegate had * @param _toVal new number of votes delegate has */ event VotingPowerChanged(address indexed _of, uint256 _fromVal, uint256 _toVal); /** * @dev Deploys the token smart contract, * assigns initial token supply to the address specified * * @param _initialHolder owner of the initial token supply */ constructor(address _initialHolder) { // verify initial holder address non-zero (is set) require(_initialHolder != address(0), "_initialHolder not set (zero address)"); // mint initial supply mint(_initialHolder, 7_000_000e18); } // ===== Start: ERC20/ERC223/ERC777 functions ===== /** * @notice Gets the balance of a particular address * * @dev ERC20 `function balanceOf(address _owner) public view returns (uint256 balance)` * * @param _owner the address to query the the balance for * @return balance an amount of tokens owned by the address specified */ function balanceOf(address _owner) public view returns (uint256 balance) { // read the balance and return return tokenBalances[_owner]; } /** * @notice Transfers some tokens to an external address or a smart contract * * @dev ERC20 `function transfer(address _to, uint256 _value) public returns (bool success)` * * @dev Called by token owner (an address which has a * positive token balance tracked by this smart contract) * @dev Throws on any error like * * insufficient token balance or * * incorrect `_to` address: * * zero address or * * self address or * * smart contract which doesn't support ERC20 * * @param _to an address to transfer tokens to, * must be either an external address or a smart contract, * compliant with the ERC20 standard * @param _value amount of tokens to be transferred, must * be greater than zero * @return success true on success, throws otherwise */ function transfer(address _to, uint256 _value) public returns (bool success) { // just delegate call to `transferFrom`, // `FEATURE_TRANSFERS` is verified inside it return transferFrom(msg.sender, _to, _value); } /** * @notice Transfers some tokens on behalf of address `_from' (token owner) * to some other address `_to` * * @dev ERC20 `function transferFrom(address _from, address _to, uint256 _value) public returns (bool success)` * * @dev Called by token owner on his own or approved address, * an address approved earlier by token owner to * transfer some amount of tokens on its behalf * @dev Throws on any error like * * insufficient token balance or * * incorrect `_to` address: * * zero address or * * same as `_from` address (self transfer) * * smart contract which doesn't support ERC20 * * @param _from token owner which approved caller (transaction sender) * to transfer `_value` of tokens on its behalf * @param _to an address to transfer tokens to, * must be either an external address or a smart contract, * compliant with the ERC20 standard * @param _value amount of tokens to be transferred, must * be greater than zero * @return success true on success, throws otherwise */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { // depending on `FEATURE_UNSAFE_TRANSFERS` we execute either safe (default) // or unsafe transfer // if `FEATURE_UNSAFE_TRANSFERS` is enabled // or receiver has `ROLE_ERC20_RECEIVER` permission // or sender has `ROLE_ERC20_SENDER` permission if(isFeatureEnabled(FEATURE_UNSAFE_TRANSFERS) || isOperatorInRole(_to, ROLE_ERC20_RECEIVER) || isSenderInRole(ROLE_ERC20_SENDER)) { // we execute unsafe transfer - delegate call to `unsafeTransferFrom`, // `FEATURE_TRANSFERS` is verified inside it unsafeTransferFrom(_from, _to, _value); } // otherwise - if `FEATURE_UNSAFE_TRANSFERS` is disabled // and receiver doesn't have `ROLE_ERC20_RECEIVER` permission else { // we execute safe transfer - delegate call to `safeTransferFrom`, passing empty `_data`, // `FEATURE_TRANSFERS` is verified inside it safeTransferFrom(_from, _to, _value, ""); } // both `unsafeTransferFrom` and `safeTransferFrom` throw on any error, so // if we're here - it means operation successful, // just return true return true; } /** * @notice Transfers some tokens on behalf of address `_from' (token owner) * to some other address `_to` * * @dev Inspired by ERC721 safeTransferFrom, this function allows to * send arbitrary data to the receiver on successful token transfer * @dev Called by token owner on his own or approved address, * an address approved earlier by token owner to * transfer some amount of tokens on its behalf * @dev Throws on any error like * * insufficient token balance or * * incorrect `_to` address: * * zero address or * * same as `_from` address (self transfer) * * smart contract which doesn't support ERC20Receiver interface * @dev Returns silently on success, throws otherwise * * @param _from token owner which approved caller (transaction sender) * to transfer `_value` of tokens on its behalf * @param _to an address to transfer tokens to, * must be either an external address or a smart contract, * compliant with the ERC20 standard * @param _value amount of tokens to be transferred, must * be greater than zero * @param _data [optional] additional data with no specified format, * sent in onERC20Received call to `_to` in case if its a smart contract */ function safeTransferFrom(address _from, address _to, uint256 _value, bytes memory _data) public { // first delegate call to `unsafeTransferFrom` // to perform the unsafe token(s) transfer unsafeTransferFrom(_from, _to, _value); // after the successful transfer - check if receiver supports // ERC20Receiver and execute a callback handler `onERC20Received`, // reverting whole transaction on any error: // check if receiver `_to` supports ERC20Receiver interface if(AddressUtils.isContract(_to)) { // if `_to` is a contract - execute onERC20Received bytes4 response = ERC20Receiver(_to).onERC20Received(msg.sender, _from, _value, _data); // expected response is ERC20_RECEIVED require(response == ERC20_RECEIVED, "invalid onERC20Received response"); } } /** * @notice Transfers some tokens on behalf of address `_from' (token owner) * to some other address `_to` * * @dev In contrast to `safeTransferFrom` doesn't check recipient * smart contract to support ERC20 tokens (ERC20Receiver) * @dev Designed to be used by developers when the receiver is known * to support ERC20 tokens but doesn't implement ERC20Receiver interface * @dev Called by token owner on his own or approved address, * an address approved earlier by token owner to * transfer some amount of tokens on its behalf * @dev Throws on any error like * * insufficient token balance or * * incorrect `_to` address: * * zero address or * * same as `_from` address (self transfer) * @dev Returns silently on success, throws otherwise * * @param _from token owner which approved caller (transaction sender) * to transfer `_value` of tokens on its behalf * @param _to an address to transfer tokens to, * must be either an external address or a smart contract, * compliant with the ERC20 standard * @param _value amount of tokens to be transferred, must * be greater than zero */ function unsafeTransferFrom(address _from, address _to, uint256 _value) public { // if `_from` is equal to sender, require transfers feature to be enabled // otherwise require transfers on behalf feature to be enabled require(_from == msg.sender && isFeatureEnabled(FEATURE_TRANSFERS) || _from != msg.sender && isFeatureEnabled(FEATURE_TRANSFERS_ON_BEHALF), _from == msg.sender? "transfers are disabled": "transfers on behalf are disabled"); // non-zero source address check - Zeppelin // obviously, zero source address is a client mistake // it's not part of ERC20 standard but it's reasonable to fail fast // since for zero value transfer transaction succeeds otherwise require(_from != address(0), "ERC20: transfer from the zero address"); // Zeppelin msg // non-zero recipient address check require(_to != address(0), "ERC20: transfer to the zero address"); // Zeppelin msg // sender and recipient cannot be the same require(_from != _to, "sender and recipient are the same (_from = _to)"); // sending tokens to the token smart contract itself is a client mistake require(_to != address(this), "invalid recipient (transfer to the token smart contract itself)"); // according to ERC-20 Token Standard, https://eips.ethereum.org/EIPS/eip-20 // "Transfers of 0 values MUST be treated as normal transfers and fire the Transfer event." if(_value == 0) { // emit an ERC20 transfer event emit Transfer(_from, _to, _value); // don't forget to return - we're done return; } // no need to make arithmetic overflow check on the _value - by design of mint() // in case of transfer on behalf if(_from != msg.sender) { // read allowance value - the amount of tokens allowed to transfer - into the stack uint256 _allowance = transferAllowances[_from][msg.sender]; // verify sender has an allowance to transfer amount of tokens requested require(_allowance >= _value, "ERC20: transfer amount exceeds allowance"); // Zeppelin msg // update allowance value on the stack _allowance -= _value; // update the allowance value in storage transferAllowances[_from][msg.sender] = _allowance; // emit an improved atomic approve event emit Approved(_from, msg.sender, _allowance + _value, _allowance); // emit an ERC20 approval event to reflect the decrease emit Approval(_from, msg.sender, _allowance); } // verify sender has enough tokens to transfer on behalf require(tokenBalances[_from] >= _value, "ERC20: transfer amount exceeds balance"); // Zeppelin msg // perform the transfer: // decrease token owner (sender) balance tokenBalances[_from] -= _value; // increase `_to` address (receiver) balance tokenBalances[_to] += _value; // move voting power associated with the tokens transferred __moveVotingPower(votingDelegates[_from], votingDelegates[_to], _value); // emit an improved transfer event emit Transferred(msg.sender, _from, _to, _value); // emit an ERC20 transfer event emit Transfer(_from, _to, _value); } /** * @notice Approves address called `_spender` to transfer some amount * of tokens on behalf of the owner * * @dev ERC20 `function approve(address _spender, uint256 _value) public returns (bool success)` * * @dev Caller must not necessarily own any tokens to grant the permission * * @param _spender an address approved by the caller (token owner) * to spend some tokens on its behalf * @param _value an amount of tokens spender `_spender` is allowed to * transfer on behalf of the token owner * @return success true on success, throws otherwise */ function approve(address _spender, uint256 _value) public returns (bool success) { // non-zero spender address check - Zeppelin // obviously, zero spender address is a client mistake // it's not part of ERC20 standard but it's reasonable to fail fast require(_spender != address(0), "ERC20: approve to the zero address"); // Zeppelin msg // read old approval value to emmit an improved event (ISBN:978-1-7281-3027-9) uint256 _oldValue = transferAllowances[msg.sender][_spender]; // perform an operation: write value requested into the storage transferAllowances[msg.sender][_spender] = _value; // emit an improved atomic approve event (ISBN:978-1-7281-3027-9) emit Approved(msg.sender, _spender, _oldValue, _value); // emit an ERC20 approval event emit Approval(msg.sender, _spender, _value); // operation successful, return true return true; } /** * @notice Returns the amount which _spender is still allowed to withdraw from _owner. * * @dev ERC20 `function allowance(address _owner, address _spender) public view returns (uint256 remaining)` * * @dev A function to check an amount of tokens owner approved * to transfer on its behalf by some other address called "spender" * * @param _owner an address which approves transferring some tokens on its behalf * @param _spender an address approved to transfer some tokens on behalf * @return remaining an amount of tokens approved address `_spender` can transfer on behalf * of token owner `_owner` */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { // read the value from storage and return return transferAllowances[_owner][_spender]; } // ===== End: ERC20/ERC223/ERC777 functions ===== // ===== Start: Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) ===== /** * @notice Increases the allowance granted to `spender` by the transaction sender * * @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) * * @dev Throws if value to increase by is zero or too big and causes arithmetic overflow * * @param _spender an address approved by the caller (token owner) * to spend some tokens on its behalf * @param _value an amount of tokens to increase by * @return success true on success, throws otherwise */ function increaseAllowance(address _spender, uint256 _value) public virtual returns (bool) { // read current allowance value uint256 currentVal = transferAllowances[msg.sender][_spender]; // non-zero _value and arithmetic overflow check on the allowance require(currentVal + _value > currentVal, "zero value approval increase or arithmetic overflow"); // delegate call to `approve` with the new value return approve(_spender, currentVal + _value); } /** * @notice Decreases the allowance granted to `spender` by the caller. * * @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) * * @dev Throws if value to decrease by is zero or is bigger than currently allowed value * * @param _spender an address approved by the caller (token owner) * to spend some tokens on its behalf * @param _value an amount of tokens to decrease by * @return success true on success, throws otherwise */ function decreaseAllowance(address _spender, uint256 _value) public virtual returns (bool) { // read current allowance value uint256 currentVal = transferAllowances[msg.sender][_spender]; // non-zero _value check on the allowance require(_value > 0, "zero value approval decrease"); // verify allowance decrease doesn't underflow require(currentVal >= _value, "ERC20: decreased allowance below zero"); // delegate call to `approve` with the new value return approve(_spender, currentVal - _value); } // ===== End: Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) ===== // ===== Start: Minting/burning extension ===== /** * @dev Mints (creates) some tokens to address specified * @dev The value specified is treated as is without taking * into account what `decimals` value is * @dev Behaves effectively as `mintTo` function, allowing * to specify an address to mint tokens to * @dev Requires sender to have `ROLE_TOKEN_CREATOR` permission * * @dev Throws on overflow, if totalSupply + _value doesn't fit into uint256 * * @param _to an address to mint tokens to * @param _value an amount of tokens to mint (create) */ function mint(address _to, uint256 _value) public { // check if caller has sufficient permissions to mint tokens require(isSenderInRole(ROLE_TOKEN_CREATOR), "insufficient privileges (ROLE_TOKEN_CREATOR required)"); // non-zero recipient address check require(_to != address(0), "ERC20: mint to the zero address"); // Zeppelin msg // non-zero _value and arithmetic overflow check on the total supply // this check automatically secures arithmetic overflow on the individual balance require(totalSupply + _value > totalSupply, "zero value mint or arithmetic overflow"); // uint192 overflow check (required by voting delegation) require(totalSupply + _value <= type(uint192).max, "total supply overflow (uint192)"); // perform mint: // increase total amount of tokens value totalSupply += _value; // increase `_to` address balance tokenBalances[_to] += _value; // create voting power associated with the tokens minted __moveVotingPower(address(0), votingDelegates[_to], _value); // fire a minted event emit Minted(msg.sender, _to, _value); // emit an improved transfer event emit Transferred(msg.sender, address(0), _to, _value); // fire ERC20 compliant transfer event emit Transfer(address(0), _to, _value); } /** * @dev Burns (destroys) some tokens from the address specified * @dev The value specified is treated as is without taking * into account what `decimals` value is * @dev Behaves effectively as `burnFrom` function, allowing * to specify an address to burn tokens from * @dev Requires sender to have `ROLE_TOKEN_DESTROYER` permission * * @param _from an address to burn some tokens from * @param _value an amount of tokens to burn (destroy) */ function burn(address _from, uint256 _value) public { // check if caller has sufficient permissions to burn tokens // and if not - check for possibility to burn own tokens or to burn on behalf if(!isSenderInRole(ROLE_TOKEN_DESTROYER)) { // if `_from` is equal to sender, require own burns feature to be enabled // otherwise require burns on behalf feature to be enabled require(_from == msg.sender && isFeatureEnabled(FEATURE_OWN_BURNS) || _from != msg.sender && isFeatureEnabled(FEATURE_BURNS_ON_BEHALF), _from == msg.sender? "burns are disabled": "burns on behalf are disabled"); // in case of burn on behalf if(_from != msg.sender) { // read allowance value - the amount of tokens allowed to be burnt - into the stack uint256 _allowance = transferAllowances[_from][msg.sender]; // verify sender has an allowance to burn amount of tokens requested require(_allowance >= _value, "ERC20: burn amount exceeds allowance"); // Zeppelin msg // update allowance value on the stack _allowance -= _value; // update the allowance value in storage transferAllowances[_from][msg.sender] = _allowance; // emit an improved atomic approve event emit Approved(msg.sender, _from, _allowance + _value, _allowance); // emit an ERC20 approval event to reflect the decrease emit Approval(_from, msg.sender, _allowance); } } // at this point we know that either sender is ROLE_TOKEN_DESTROYER or // we burn own tokens or on behalf (in latest case we already checked and updated allowances) // we have left to execute balance checks and burning logic itself // non-zero burn value check require(_value != 0, "zero value burn"); // non-zero source address check - Zeppelin require(_from != address(0), "ERC20: burn from the zero address"); // Zeppelin msg // verify `_from` address has enough tokens to destroy // (basically this is a arithmetic overflow check) require(tokenBalances[_from] >= _value, "ERC20: burn amount exceeds balance"); // Zeppelin msg // perform burn: // decrease `_from` address balance tokenBalances[_from] -= _value; // decrease total amount of tokens value totalSupply -= _value; // destroy voting power associated with the tokens burnt __moveVotingPower(votingDelegates[_from], address(0), _value); // fire a burnt event emit Burnt(msg.sender, _from, _value); // emit an improved transfer event emit Transferred(msg.sender, _from, address(0), _value); // fire ERC20 compliant transfer event emit Transfer(_from, address(0), _value); } // ===== End: Minting/burning extension ===== // ===== Start: DAO Support (Compound-like voting delegation) ===== /** * @notice Gets current voting power of the account `_of` * @param _of the address of account to get voting power of * @return current cumulative voting power of the account, * sum of token balances of all its voting delegators */ function getVotingPower(address _of) public view returns (uint256) { // get a link to an array of voting power history records for an address specified VotingPowerRecord[] storage history = votingPowerHistory[_of]; // lookup the history and return latest element return history.length == 0? 0: history[history.length - 1].votingPower; } /** * @notice Gets past voting power of the account `_of` at some block `_blockNum` * @dev Throws if `_blockNum` is not in the past (not the finalized block) * @param _of the address of account to get voting power of * @param _blockNum block number to get the voting power at * @return past cumulative voting power of the account, * sum of token balances of all its voting delegators at block number `_blockNum` */ function getVotingPowerAt(address _of, uint256 _blockNum) public view returns (uint256) { // make sure block number is not in the past (not the finalized block) require(_blockNum < block.number, "not yet determined"); // Compound msg // get a link to an array of voting power history records for an address specified VotingPowerRecord[] storage history = votingPowerHistory[_of]; // if voting power history for the account provided is empty if(history.length == 0) { // than voting power is zero - return the result return 0; } // check latest voting power history record block number: // if history was not updated after the block of interest if(history[history.length - 1].blockNumber <= _blockNum) { // we're done - return last voting power record return getVotingPower(_of); } // check first voting power history record block number: // if history was never updated before the block of interest if(history[0].blockNumber > _blockNum) { // we're done - voting power at the block num of interest was zero return 0; } // `votingPowerHistory[_of]` is an array ordered by `blockNumber`, ascending; // apply binary search on `votingPowerHistory[_of]` to find such an entry number `i`, that // `votingPowerHistory[_of][i].blockNumber <= _blockNum`, but in the same time // `votingPowerHistory[_of][i + 1].blockNumber > _blockNum` // return the result - voting power found at index `i` return history[__binaryLookup(_of, _blockNum)].votingPower; } /** * @dev Reads an entire voting power history array for the delegate specified * * @param _of delegate to query voting power history for * @return voting power history array for the delegate of interest */ function getVotingPowerHistory(address _of) public view returns(VotingPowerRecord[] memory) { // return an entire array as memory return votingPowerHistory[_of]; } /** * @dev Returns length of the voting power history array for the delegate specified; * useful since reading an entire array just to get its length is expensive (gas cost) * * @param _of delegate to query voting power history length for * @return voting power history array length for the delegate of interest */ function getVotingPowerHistoryLength(address _of) public view returns(uint256) { // read array length and return return votingPowerHistory[_of].length; } /** * @notice Delegates voting power of the delegator `msg.sender` to the delegate `_to` * * @dev Accepts zero value address to delegate voting power to, effectively * removing the delegate in that case * * @param _to address to delegate voting power to */ function delegate(address _to) public { // verify delegations are enabled require(isFeatureEnabled(FEATURE_DELEGATIONS), "delegations are disabled"); // delegate call to `__delegate` __delegate(msg.sender, _to); } /** * @notice Delegates voting power of the delegator (represented by its signature) to the delegate `_to` * * @dev Accepts zero value address to delegate voting power to, effectively * removing the delegate in that case * * @dev Compliant with EIP-712: Ethereum typed structured data hashing and signing, * see https://eips.ethereum.org/EIPS/eip-712 * * @param _to address to delegate voting power to * @param _nonce nonce used to construct the signature, and used to validate it; * nonce is increased by one after successful signature validation and vote delegation * @param _exp signature expiration time * @param v the recovery byte of the signature * @param r half of the ECDSA signature pair * @param s half of the ECDSA signature pair */ function delegateWithSig(address _to, uint256 _nonce, uint256 _exp, uint8 v, bytes32 r, bytes32 s) public { // verify delegations on behalf are enabled require(isFeatureEnabled(FEATURE_DELEGATIONS_ON_BEHALF), "delegations on behalf are disabled"); // build the EIP-712 contract domain separator bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), block.chainid, address(this))); // build the EIP-712 hashStruct of the delegation message bytes32 hashStruct = keccak256(abi.encode(DELEGATION_TYPEHASH, _to, _nonce, _exp)); // calculate the EIP-712 digest "\x19\x01" ‖ domainSeparator ‖ hashStruct(message) bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, hashStruct)); // recover the address who signed the message with v, r, s address signer = ecrecover(digest, v, r, s); // perform message integrity and security validations require(signer != address(0), "invalid signature"); // Compound msg require(_nonce == nonces[signer], "invalid nonce"); // Compound msg require(block.timestamp < _exp, "signature expired"); // Compound msg // update the nonce for that particular signer to avoid replay attack nonces[signer]++; // delegate call to `__delegate` - execute the logic required __delegate(signer, _to); } /** * @dev Auxiliary function to delegate delegator's `_from` voting power to the delegate `_to` * @dev Writes to `votingDelegates` and `votingPowerHistory` mappings * * @param _from delegator who delegates his voting power * @param _to delegate who receives the voting power */ function __delegate(address _from, address _to) private { // read current delegate to be replaced by a new one address _fromDelegate = votingDelegates[_from]; // read current voting power (it is equal to token balance) uint256 _value = tokenBalances[_from]; // reassign voting delegate to `_to` votingDelegates[_from] = _to; // update voting power for `_fromDelegate` and `_to` __moveVotingPower(_fromDelegate, _to, _value); // emit an event emit DelegateChanged(_from, _fromDelegate, _to); } /** * @dev Auxiliary function to move voting power `_value` * from delegate `_from` to the delegate `_to` * * @dev Doesn't have any effect if `_from == _to`, or if `_value == 0` * * @param _from delegate to move voting power from * @param _to delegate to move voting power to * @param _value voting power to move from `_from` to `_to` */ function __moveVotingPower(address _from, address _to, uint256 _value) private { // if there is no move (`_from == _to`) or there is nothing to move (`_value == 0`) if(_from == _to || _value == 0) { // return silently with no action return; } // if source address is not zero - decrease its voting power if(_from != address(0)) { // read current source address voting power uint256 _fromVal = getVotingPower(_from); // calculate decreased voting power // underflow is not possible by design: // voting power is limited by token balance which is checked by the callee uint256 _toVal = _fromVal - _value; // update source voting power from `_fromVal` to `_toVal` __updateVotingPower(_from, _fromVal, _toVal); } // if destination address is not zero - increase its voting power if(_to != address(0)) { // read current destination address voting power uint256 _fromVal = getVotingPower(_to); // calculate increased voting power // overflow is not possible by design: // max token supply limits the cumulative voting power uint256 _toVal = _fromVal + _value; // update destination voting power from `_fromVal` to `_toVal` __updateVotingPower(_to, _fromVal, _toVal); } } /** * @dev Auxiliary function to update voting power of the delegate `_of` * from value `_fromVal` to value `_toVal` * * @param _of delegate to update its voting power * @param _fromVal old voting power of the delegate * @param _toVal new voting power of the delegate */ function __updateVotingPower(address _of, uint256 _fromVal, uint256 _toVal) private { // get a link to an array of voting power history records for an address specified VotingPowerRecord[] storage history = votingPowerHistory[_of]; // if there is an existing voting power value stored for current block if(history.length != 0 && history[history.length - 1].blockNumber == block.number) { // update voting power which is already stored in the current block history[history.length - 1].votingPower = uint192(_toVal); } // otherwise - if there is no value stored for current block else { // add new element into array representing the value for current block history.push(VotingPowerRecord(uint64(block.number), uint192(_toVal))); } // emit an event emit VotingPowerChanged(_of, _fromVal, _toVal); } /** * @dev Auxiliary function to lookup an element in a sorted (asc) array of elements * * @dev This function finds the closest element in an array to the value * of interest (not exceeding that value) and returns its index within an array * * @dev An array to search in is `votingPowerHistory[_to][i].blockNumber`, * it is sorted in ascending order (blockNumber increases) * * @param _to an address of the delegate to get an array for * @param n value of interest to look for * @return an index of the closest element in an array to the value * of interest (not exceeding that value) */ function __binaryLookup(address _to, uint256 n) private view returns(uint256) { // get a link to an array of voting power history records for an address specified VotingPowerRecord[] storage history = votingPowerHistory[_to]; // left bound of the search interval, originally start of the array uint256 i = 0; // right bound of the search interval, originally end of the array uint256 j = history.length - 1; // the iteration process narrows down the bounds by // splitting the interval in a half oce per each iteration while(j > i) { // get an index in the middle of the interval [i, j] uint256 k = j - (j - i) / 2; // read an element to compare it with the value of interest VotingPowerRecord memory cp = history[k]; // if we've got a strict equal - we're lucky and done if(cp.blockNumber == n) { // just return the result - index `k` return k; } // if the value of interest is bigger - move left bound to the middle else if (cp.blockNumber < n) { // move left bound `i` to the middle position `k` i = k; } // otherwise, when the value of interest is smaller - move right bound to the middle else { // move right bound `j` to the middle position `k - 1`: // element at position `k` is bigger and cannot be the result j = k - 1; } } // reaching that point means no exact match found // since we're interested in the element which is not bigger than the // element of interest, we return the lower bound `i` return i; } } // ===== End: DAO Support (Compound-like voting delegation) ===== /** * @title Illuvium Aware * * @notice Helper smart contract to be inherited by other smart contracts requiring to * be linked to verified IlluviumERC20 instance and performing some basic tasks on it * * @author Basil Gorin */ abstract contract IlluviumAware is ILinkedToILV { /// @dev Link to ILV ERC20 Token IlluviumERC20 instance address public immutable override ilv; /** * @dev Creates IlluviumAware instance, requiring to supply deployed IlluviumERC20 instance address * * @param _ilv deployed IlluviumERC20 instance address */ constructor(address _ilv) { // verify ILV address is set and is correct require(_ilv != address(0), "ILV address not set"); require(IlluviumERC20(_ilv).TOKEN_UID() == 0x83ecb176af7c4f35a45ff0018282e3a05a1018065da866182df12285866f5a2c, "unexpected TOKEN_UID"); // write ILV address ilv = _ilv; } /** * @dev Executes IlluviumERC20.safeTransferFrom(address(this), _to, _value, "") * on the bound IlluviumERC20 instance * * @dev Reentrancy safe due to the IlluviumERC20 design */ function transferIlv(address _to, uint256 _value) internal { // just delegate call to the target transferIlvFrom(address(this), _to, _value); } /** * @dev Executes IlluviumERC20.transferFrom(_from, _to, _value) * on the bound IlluviumERC20 instance * * @dev Reentrancy safe due to the IlluviumERC20 design */ function transferIlvFrom(address _from, address _to, uint256 _value) internal { // just delegate call to the target IlluviumERC20(ilv).transferFrom(_from, _to, _value); } /** * @dev Executes IlluviumERC20.mint(_to, _values) * on the bound IlluviumERC20 instance * * @dev Reentrancy safe due to the IlluviumERC20 design */ function mintIlv(address _to, uint256 _value) internal { // just delegate call to the target IlluviumERC20(ilv).mint(_to, _value); } } /** * @title Illuvium Pool Base * * @notice An abstract contract containing common logic for any pool, * be it a flash pool (temporary pool like SNX) or a core pool (permanent pool like ILV/ETH or ILV pool) * * @dev Deployment and initialization. * Any pool deployed must be bound to the deployed pool factory (IlluviumPoolFactory) * Additionally, 3 token instance addresses must be defined on deployment: * - ILV token address * - sILV token address, used to mint sILV rewards * - pool token address, it can be ILV token address, ILV/ETH pair address, and others * * @dev Pool weight defines the fraction of the yield current pool receives among the other pools, * pool factory is responsible for the weight synchronization between the pools. * @dev The weight is logically 10% for ILV pool and 90% for ILV/ETH pool. * Since Solidity doesn't support fractions the weight is defined by the division of * pool weight by total pools weight (sum of all registered pools within the factory) * @dev For ILV Pool we use 100 as weight and for ILV/ETH pool - 900. * * @author Pedro Bergamini, reviewed by Basil Gorin */ abstract contract IlluviumPoolBase is IPool, IlluviumAware, ReentrancyGuard { /// @dev Data structure representing token holder using a pool struct User { // @dev Total staked amount uint256 tokenAmount; // @dev Total weight uint256 totalWeight; // @dev Auxiliary variable for yield calculation uint256 subYieldRewards; // @dev Auxiliary variable for vault rewards calculation uint256 subVaultRewards; // @dev An array of holder's deposits Deposit[] deposits; } /// @dev Token holder storage, maps token holder address to their data record mapping(address => User) public users; /// @dev Link to sILV ERC20 Token EscrowedIlluviumERC20 instance address public immutable override silv; /// @dev Link to the pool factory IlluviumPoolFactory instance IlluviumPoolFactory public immutable factory; /// @dev Link to the pool token instance, for example ILV or ILV/ETH pair address public immutable override poolToken; /// @dev Pool weight, 100 for ILV pool or 900 for ILV/ETH uint32 public override weight; /// @dev Block number of the last yield distribution event uint64 public override lastYieldDistribution; /// @dev Used to calculate yield rewards /// @dev This value is different from "reward per token" used in locked pool /// @dev Note: stakes are different in duration and "weight" reflects that uint256 public override yieldRewardsPerWeight; /// @dev Used to calculate yield rewards, keeps track of the tokens weight locked in staking uint256 public override usersLockingWeight; /** * @dev Stake weight is proportional to deposit amount and time locked, precisely * "deposit amount wei multiplied by (fraction of the year locked plus one)" * @dev To avoid significant precision loss due to multiplication by "fraction of the year" [0, 1], * weight is stored multiplied by 1e6 constant, as an integer * @dev Corner case 1: if time locked is zero, weight is deposit amount multiplied by 1e6 * @dev Corner case 2: if time locked is one year, fraction of the year locked is one, and * weight is a deposit amount multiplied by 2 * 1e6 */ uint256 internal constant WEIGHT_MULTIPLIER = 1e6; /** * @dev When we know beforehand that staking is done for a year, and fraction of the year locked is one, * we use simplified calculation and use the following constant instead previos one */ uint256 internal constant YEAR_STAKE_WEIGHT_MULTIPLIER = 2 * WEIGHT_MULTIPLIER; /** * @dev Rewards per weight are stored multiplied by 1e12, as integers. */ uint256 internal constant REWARD_PER_WEIGHT_MULTIPLIER = 1e12; /** * @dev Fired in _stake() and stake() * * @param _by an address which performed an operation, usually token holder * @param _from token holder address, the tokens will be returned to that address * @param amount amount of tokens staked */ event Staked(address indexed _by, address indexed _from, uint256 amount); /** * @dev Fired in _updateStakeLock() and updateStakeLock() * * @param _by an address which performed an operation * @param depositId updated deposit ID * @param lockedFrom deposit locked from value * @param lockedUntil updated deposit locked until value */ event StakeLockUpdated(address indexed _by, uint256 depositId, uint64 lockedFrom, uint64 lockedUntil); /** * @dev Fired in _unstake() and unstake() * * @param _by an address which performed an operation, usually token holder * @param _to an address which received the unstaked tokens, usually token holder * @param amount amount of tokens unstaked */ event Unstaked(address indexed _by, address indexed _to, uint256 amount); /** * @dev Fired in _sync(), sync() and dependent functions (stake, unstake, etc.) * * @param _by an address which performed an operation * @param yieldRewardsPerWeight updated yield rewards per weight value * @param lastYieldDistribution usually, current block number */ event Synchronized(address indexed _by, uint256 yieldRewardsPerWeight, uint64 lastYieldDistribution); /** * @dev Fired in _processRewards(), processRewards() and dependent functions (stake, unstake, etc.) * * @param _by an address which performed an operation * @param _to an address which claimed the yield reward * @param sIlv flag indicating if reward was paid (minted) in sILV * @param amount amount of yield paid */ event YieldClaimed(address indexed _by, address indexed _to, bool sIlv, uint256 amount); /** * @dev Fired in setWeight() * * @param _by an address which performed an operation, always a factory * @param _fromVal old pool weight value * @param _toVal new pool weight value */ event PoolWeightUpdated(address indexed _by, uint32 _fromVal, uint32 _toVal); /** * @dev Overridden in sub-contracts to construct the pool * * @param _ilv ILV ERC20 Token IlluviumERC20 address * @param _silv sILV ERC20 Token EscrowedIlluviumERC20 address * @param _factory Pool factory IlluviumPoolFactory instance/address * @param _poolToken token the pool operates on, for example ILV or ILV/ETH pair * @param _initBlock initial block used to calculate the rewards * note: _initBlock can be set to the future effectively meaning _sync() calls will do nothing * @param _weight number representing a weight of the pool, actual weight fraction * is calculated as that number divided by the total pools weight and doesn't exceed one */ constructor( address _ilv, address _silv, IlluviumPoolFactory _factory, address _poolToken, uint64 _initBlock, uint32 _weight ) IlluviumAware(_ilv) { // verify the inputs are set require(_silv != address(0), "sILV address not set"); require(address(_factory) != address(0), "ILV Pool fct address not set"); require(_poolToken != address(0), "pool token address not set"); require(_initBlock > 0, "init block not set"); require(_weight > 0, "pool weight not set"); // verify sILV instance supplied require( EscrowedIlluviumERC20(_silv).TOKEN_UID() == 0xac3051b8d4f50966afb632468a4f61483ae6a953b74e387a01ef94316d6b7d62, "unexpected sILV TOKEN_UID" ); // verify IlluviumPoolFactory instance supplied require( _factory.FACTORY_UID() == 0xc5cfd88c6e4d7e5c8a03c255f03af23c0918d8e82cac196f57466af3fd4a5ec7, "unexpected FACTORY_UID" ); // save the inputs into internal state variables silv = _silv; factory = _factory; poolToken = _poolToken; weight = _weight; // init the dependent internal state variables lastYieldDistribution = _initBlock; } /** * @notice Calculates current yield rewards value available for address specified * * @param _staker an address to calculate yield rewards value for * @return calculated yield reward value for the given address */ function pendingYieldRewards(address _staker) external view override returns (uint256) { // `newYieldRewardsPerWeight` will store stored or recalculated value for `yieldRewardsPerWeight` uint256 newYieldRewardsPerWeight; // if smart contract state was not updated recently, `yieldRewardsPerWeight` value // is outdated and we need to recalculate it in order to calculate pending rewards correctly if (blockNumber() > lastYieldDistribution && usersLockingWeight != 0) { uint256 endBlock = factory.endBlock(); uint256 multiplier = blockNumber() > endBlock ? endBlock - lastYieldDistribution : blockNumber() - lastYieldDistribution; uint256 ilvRewards = (multiplier * weight * factory.ilvPerBlock()) / factory.totalWeight(); // recalculated value for `yieldRewardsPerWeight` newYieldRewardsPerWeight = rewardToWeight(ilvRewards, usersLockingWeight) + yieldRewardsPerWeight; } else { // if smart contract state is up to date, we don't recalculate newYieldRewardsPerWeight = yieldRewardsPerWeight; } // based on the rewards per weight value, calculate pending rewards; User memory user = users[_staker]; uint256 pending = weightToReward(user.totalWeight, newYieldRewardsPerWeight) - user.subYieldRewards; return pending; } /** * @notice Returns total staked token balance for the given address * * @param _user an address to query balance for * @return total staked token balance */ function balanceOf(address _user) external view override returns (uint256) { // read specified user token amount and return return users[_user].tokenAmount; } /** * @notice Returns information on the given deposit for the given address * * @dev See getDepositsLength * * @param _user an address to query deposit for * @param _depositId zero-indexed deposit ID for the address specified * @return deposit info as Deposit structure */ function getDeposit(address _user, uint256 _depositId) external view override returns (Deposit memory) { // read deposit at specified index and return return users[_user].deposits[_depositId]; } /** * @notice Returns number of deposits for the given address. Allows iteration over deposits. * * @dev See getDeposit * * @param _user an address to query deposit length for * @return number of deposits for the given address */ function getDepositsLength(address _user) external view override returns (uint256) { // read deposits array length and return return users[_user].deposits.length; } /** * @notice Stakes specified amount of tokens for the specified amount of time, * and pays pending yield rewards if any * * @dev Requires amount to stake to be greater than zero * * @param _amount amount of tokens to stake * @param _lockUntil stake period as unix timestamp; zero means no locking * @param _useSILV a flag indicating if previous reward to be paid as sILV */ function stake( uint256 _amount, uint64 _lockUntil, bool _useSILV ) external override { // delegate call to an internal function _stake(msg.sender, _amount, _lockUntil, _useSILV, false); } /** * @notice Unstakes specified amount of tokens, and pays pending yield rewards if any * * @dev Requires amount to unstake to be greater than zero * * @param _depositId deposit ID to unstake from, zero-indexed * @param _amount amount of tokens to unstake * @param _useSILV a flag indicating if reward to be paid as sILV */ function unstake( uint256 _depositId, uint256 _amount, bool _useSILV ) external override { // delegate call to an internal function _unstake(msg.sender, _depositId, _amount, _useSILV); } /** * @notice Extends locking period for a given deposit * * @dev Requires new lockedUntil value to be: * higher than the current one, and * in the future, but * no more than 1 year in the future * * @param depositId updated deposit ID * @param lockedUntil updated deposit locked until value * @param useSILV used for _processRewards check if it should use ILV or sILV */ function updateStakeLock( uint256 depositId, uint64 lockedUntil, bool useSILV ) external { // sync and call processRewards _sync(); _processRewards(msg.sender, useSILV, false); // delegate call to an internal function _updateStakeLock(msg.sender, depositId, lockedUntil); } /** * @notice Service function to synchronize pool state with current time * * @dev Can be executed by anyone at any time, but has an effect only when * at least one block passes between synchronizations * @dev Executed internally when staking, unstaking, processing rewards in order * for calculations to be correct and to reflect state progress of the contract * @dev When timing conditions are not met (executed too frequently, or after factory * end block), function doesn't throw and exits silently */ function sync() external override { // delegate call to an internal function _sync(); } /** * @notice Service function to calculate and pay pending yield rewards to the sender * * @dev Can be executed by anyone at any time, but has an effect only when * executed by deposit holder and when at least one block passes from the * previous reward processing * @dev Executed internally when staking and unstaking, executes sync() under the hood * before making further calculations and payouts * @dev When timing conditions are not met (executed too frequently, or after factory * end block), function doesn't throw and exits silently * * @param _useSILV flag indicating whether to mint sILV token as a reward or not; * when set to true - sILV reward is minted immediately and sent to sender, * when set to false - new ILV reward deposit gets created if pool is an ILV pool * (poolToken is ILV token), or new pool deposit gets created together with sILV minted * when pool is not an ILV pool (poolToken is not an ILV token) */ function processRewards(bool _useSILV) external virtual override { // delegate call to an internal function _processRewards(msg.sender, _useSILV, true); } /** * @dev Executed by the factory to modify pool weight; the factory is expected * to keep track of the total pools weight when updating * * @dev Set weight to zero to disable the pool * * @param _weight new weight to set for the pool */ function setWeight(uint32 _weight) external override { // verify function is executed by the factory require(msg.sender == address(factory), "access denied"); // emit an event logging old and new weight values emit PoolWeightUpdated(msg.sender, weight, _weight); // set the new weight value weight = _weight; } /** * @dev Similar to public pendingYieldRewards, but performs calculations based on * current smart contract state only, not taking into account any additional * time/blocks which might have passed * * @param _staker an address to calculate yield rewards value for * @return pending calculated yield reward value for the given address */ function _pendingYieldRewards(address _staker) internal view returns (uint256 pending) { // read user data structure into memory User memory user = users[_staker]; // and perform the calculation using the values read return weightToReward(user.totalWeight, yieldRewardsPerWeight) - user.subYieldRewards; } /** * @dev Used internally, mostly by children implementations, see stake() * * @param _staker an address which stakes tokens and which will receive them back * @param _amount amount of tokens to stake * @param _lockUntil stake period as unix timestamp; zero means no locking * @param _useSILV a flag indicating if previous reward to be paid as sILV * @param _isYield a flag indicating if that stake is created to store yield reward * from the previously unstaked stake */ function _stake( address _staker, uint256 _amount, uint64 _lockUntil, bool _useSILV, bool _isYield ) internal virtual { // validate the inputs require(_amount > 0, "zero amount"); require( _lockUntil == 0 || (_lockUntil > now256() && _lockUntil - now256() <= 365 days), "invalid lock interval" ); // update smart contract state _sync(); // get a link to user data struct, we will write to it later User storage user = users[_staker]; // process current pending rewards if any if (user.tokenAmount > 0) { _processRewards(_staker, _useSILV, false); } // in most of the cases added amount `addedAmount` is simply `_amount` // however for deflationary tokens this can be different // read the current balance uint256 previousBalance = IERC20(poolToken).balanceOf(address(this)); // transfer `_amount`; note: some tokens may get burnt here transferPoolTokenFrom(address(msg.sender), address(this), _amount); // read new balance, usually this is just the difference `previousBalance - _amount` uint256 newBalance = IERC20(poolToken).balanceOf(address(this)); // calculate real amount taking into account deflation uint256 addedAmount = newBalance - previousBalance; // set the `lockFrom` and `lockUntil` taking into account that // zero value for `_lockUntil` means "no locking" and leads to zero values // for both `lockFrom` and `lockUntil` uint64 lockFrom = _lockUntil > 0 ? uint64(now256()) : 0; uint64 lockUntil = _lockUntil; // stake weight formula rewards for locking uint256 stakeWeight = (((lockUntil - lockFrom) * WEIGHT_MULTIPLIER) / 365 days + WEIGHT_MULTIPLIER) * addedAmount; // makes sure stakeWeight is valid assert(stakeWeight > 0); // create and save the deposit (append it to deposits array) Deposit memory deposit = Deposit({ tokenAmount: addedAmount, weight: stakeWeight, lockedFrom: lockFrom, lockedUntil: lockUntil, isYield: _isYield }); // deposit ID is an index of the deposit in `deposits` array user.deposits.push(deposit); // update user record user.tokenAmount += addedAmount; user.totalWeight += stakeWeight; user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight); // update global variable usersLockingWeight += stakeWeight; // emit an event emit Staked(msg.sender, _staker, _amount); } /** * @dev Used internally, mostly by children implementations, see unstake() * * @param _staker an address which unstakes tokens (which previously staked them) * @param _depositId deposit ID to unstake from, zero-indexed * @param _amount amount of tokens to unstake * @param _useSILV a flag indicating if reward to be paid as sILV */ function _unstake( address _staker, uint256 _depositId, uint256 _amount, bool _useSILV ) internal virtual { // verify an amount is set require(_amount > 0, "zero amount"); // get a link to user data struct, we will write to it later User storage user = users[_staker]; // get a link to the corresponding deposit, we may write to it later Deposit storage stakeDeposit = user.deposits[_depositId]; // deposit structure may get deleted, so we save isYield flag to be able to use it bool isYield = stakeDeposit.isYield; // verify available balance // if staker address ot deposit doesn't exist this check will fail as well require(stakeDeposit.tokenAmount >= _amount, "amount exceeds stake"); // update smart contract state _sync(); // and process current pending rewards if any _processRewards(_staker, _useSILV, false); // recalculate deposit weight uint256 previousWeight = stakeDeposit.weight; uint256 newWeight = (((stakeDeposit.lockedUntil - stakeDeposit.lockedFrom) * WEIGHT_MULTIPLIER) / 365 days + WEIGHT_MULTIPLIER) * (stakeDeposit.tokenAmount - _amount); // update the deposit, or delete it if its depleted if (stakeDeposit.tokenAmount - _amount == 0) { delete user.deposits[_depositId]; } else { stakeDeposit.tokenAmount -= _amount; stakeDeposit.weight = newWeight; } // update user record user.tokenAmount -= _amount; user.totalWeight = user.totalWeight - previousWeight + newWeight; user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight); // update global variable usersLockingWeight = usersLockingWeight - previousWeight + newWeight; // if the deposit was created by the pool itself as a yield reward if (isYield) { // mint the yield via the factory factory.mintYieldTo(msg.sender, _amount); } else { // otherwise just return tokens back to holder transferPoolToken(msg.sender, _amount); } // emit an event emit Unstaked(msg.sender, _staker, _amount); } /** * @dev Used internally, mostly by children implementations, see sync() * * @dev Updates smart contract state (`yieldRewardsPerWeight`, `lastYieldDistribution`), * updates factory state via `updateILVPerBlock` */ function _sync() internal virtual { // update ILV per block value in factory if required if (factory.shouldUpdateRatio()) { factory.updateILVPerBlock(); } // check bound conditions and if these are not met - // exit silently, without emitting an event uint256 endBlock = factory.endBlock(); if (lastYieldDistribution >= endBlock) { return; } if (blockNumber() <= lastYieldDistribution) { return; } // if locking weight is zero - update only `lastYieldDistribution` and exit if (usersLockingWeight == 0) { lastYieldDistribution = uint64(blockNumber()); return; } // to calculate the reward we need to know how many blocks passed, and reward per block uint256 currentBlock = blockNumber() > endBlock ? endBlock : blockNumber(); uint256 blocksPassed = currentBlock - lastYieldDistribution; uint256 ilvPerBlock = factory.ilvPerBlock(); // calculate the reward uint256 ilvReward = (blocksPassed * ilvPerBlock * weight) / factory.totalWeight(); // update rewards per weight and `lastYieldDistribution` yieldRewardsPerWeight += rewardToWeight(ilvReward, usersLockingWeight); lastYieldDistribution = uint64(currentBlock); // emit an event emit Synchronized(msg.sender, yieldRewardsPerWeight, lastYieldDistribution); } /** * @dev Used internally, mostly by children implementations, see processRewards() * * @param _staker an address which receives the reward (which has staked some tokens earlier) * @param _useSILV flag indicating whether to mint sILV token as a reward or not, see processRewards() * @param _withUpdate flag allowing to disable synchronization (see sync()) if set to false * @return pendingYield the rewards calculated and optionally re-staked */ function _processRewards( address _staker, bool _useSILV, bool _withUpdate ) internal virtual returns (uint256 pendingYield) { // update smart contract state if required if (_withUpdate) { _sync(); } // calculate pending yield rewards, this value will be returned pendingYield = _pendingYieldRewards(_staker); // if pending yield is zero - just return silently if (pendingYield == 0) return 0; // get link to a user data structure, we will write into it later User storage user = users[_staker]; // if sILV is requested if (_useSILV) { // - mint sILV mintSIlv(_staker, pendingYield); } else if (poolToken == ilv) { // calculate pending yield weight, // 2e6 is the bonus weight when staking for 1 year uint256 depositWeight = pendingYield * YEAR_STAKE_WEIGHT_MULTIPLIER; // if the pool is ILV Pool - create new ILV deposit // and save it - push it into deposits array Deposit memory newDeposit = Deposit({ tokenAmount: pendingYield, lockedFrom: uint64(now256()), lockedUntil: uint64(now256() + 365 days), // staking yield for 1 year weight: depositWeight, isYield: true }); user.deposits.push(newDeposit); // update user record user.tokenAmount += pendingYield; user.totalWeight += depositWeight; // update global variable usersLockingWeight += depositWeight; } else { // for other pools - stake as pool address ilvPool = factory.getPoolAddress(ilv); ICorePool(ilvPool).stakeAsPool(_staker, pendingYield); } // update users's record for `subYieldRewards` if requested if (_withUpdate) { user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight); } // emit an event emit YieldClaimed(msg.sender, _staker, _useSILV, pendingYield); } /** * @dev See updateStakeLock() * * @param _staker an address to update stake lock * @param _depositId updated deposit ID * @param _lockedUntil updated deposit locked until value */ function _updateStakeLock( address _staker, uint256 _depositId, uint64 _lockedUntil ) internal { // validate the input time require(_lockedUntil > now256(), "lock should be in the future"); // get a link to user data struct, we will write to it later User storage user = users[_staker]; // get a link to the corresponding deposit, we may write to it later Deposit storage stakeDeposit = user.deposits[_depositId]; // validate the input against deposit structure require(_lockedUntil > stakeDeposit.lockedUntil, "invalid new lock"); // verify locked from and locked until values if (stakeDeposit.lockedFrom == 0) { require(_lockedUntil - now256() <= 365 days, "max lock period is 365 days"); stakeDeposit.lockedFrom = uint64(now256()); } else { require(_lockedUntil - stakeDeposit.lockedFrom <= 365 days, "max lock period is 365 days"); } // update locked until value, calculate new weight stakeDeposit.lockedUntil = _lockedUntil; uint256 newWeight = (((stakeDeposit.lockedUntil - stakeDeposit.lockedFrom) * WEIGHT_MULTIPLIER) / 365 days + WEIGHT_MULTIPLIER) * stakeDeposit.tokenAmount; // save previous weight uint256 previousWeight = stakeDeposit.weight; // update weight stakeDeposit.weight = newWeight; // update user total weight and global locking weight user.totalWeight = user.totalWeight - previousWeight + newWeight; usersLockingWeight = usersLockingWeight - previousWeight + newWeight; // emit an event emit StakeLockUpdated(_staker, _depositId, stakeDeposit.lockedFrom, _lockedUntil); } /** * @dev Converts stake weight (not to be mixed with the pool weight) to * ILV reward value, applying the 10^12 division on weight * * @param _weight stake weight * @param rewardPerWeight ILV reward per weight * @return reward value normalized to 10^12 */ function weightToReward(uint256 _weight, uint256 rewardPerWeight) public pure returns (uint256) { // apply the formula and return return (_weight * rewardPerWeight) / REWARD_PER_WEIGHT_MULTIPLIER; } /** * @dev Converts reward ILV value to stake weight (not to be mixed with the pool weight), * applying the 10^12 multiplication on the reward * - OR - * @dev Converts reward ILV value to reward/weight if stake weight is supplied as second * function parameter instead of reward/weight * * @param reward yield reward * @param rewardPerWeight reward/weight (or stake weight) * @return stake weight (or reward/weight) */ function rewardToWeight(uint256 reward, uint256 rewardPerWeight) public pure returns (uint256) { // apply the reverse formula and return return (reward * REWARD_PER_WEIGHT_MULTIPLIER) / rewardPerWeight; } /** * @dev Testing time-dependent functionality is difficult and the best way of * doing it is to override block number in helper test smart contracts * * @return `block.number` in mainnet, custom values in testnets (if overridden) */ function blockNumber() public view virtual returns (uint256) { // return current block number return block.number; } /** * @dev Testing time-dependent functionality is difficult and the best way of * doing it is to override time in helper test smart contracts * * @return `block.timestamp` in mainnet, custom values in testnets (if overridden) */ function now256() public view virtual returns (uint256) { // return current block timestamp return block.timestamp; } /** * @dev Executes EscrowedIlluviumERC20.mint(_to, _values) * on the bound EscrowedIlluviumERC20 instance * * @dev Reentrancy safe due to the EscrowedIlluviumERC20 design */ function mintSIlv(address _to, uint256 _value) private { // just delegate call to the target EscrowedIlluviumERC20(silv).mint(_to, _value); } /** * @dev Executes SafeERC20.safeTransfer on a pool token * * @dev Reentrancy safety enforced via `ReentrancyGuard.nonReentrant` */ function transferPoolToken(address _to, uint256 _value) internal nonReentrant { // just delegate call to the target SafeERC20.safeTransfer(IERC20(poolToken), _to, _value); } /** * @dev Executes SafeERC20.safeTransferFrom on a pool token * * @dev Reentrancy safety enforced via `ReentrancyGuard.nonReentrant` */ function transferPoolTokenFrom( address _from, address _to, uint256 _value ) internal nonReentrant { // just delegate call to the target SafeERC20.safeTransferFrom(IERC20(poolToken), _from, _to, _value); } } /** * @title Illuvium Core Pool * * @notice Core pools represent permanent pools like ILV or ILV/ETH Pair pool, * core pools allow staking for arbitrary periods of time up to 1 year * * @dev See IlluviumPoolBase for more details * * @author Pedro Bergamini, reviewed by Basil Gorin */ contract IlluviumCorePool is IlluviumPoolBase { /// @dev Flag indicating pool type, false means "core pool" bool public constant override isFlashPool = false; /// @dev Link to deployed IlluviumVault instance address public vault; /// @dev Used to calculate vault rewards /// @dev This value is different from "reward per token" used in locked pool /// @dev Note: stakes are different in duration and "weight" reflects that uint256 public vaultRewardsPerWeight; /// @dev Pool tokens value available in the pool; /// pool token examples are ILV (ILV core pool) or ILV/ETH pair (LP core pool) /// @dev For LP core pool this value doesnt' count for ILV tokens received as Vault rewards /// while for ILV core pool it does count for such tokens as well uint256 public poolTokenReserve; /** * @dev Fired in receiveVaultRewards() * * @param _by an address that sent the rewards, always a vault * @param amount amount of tokens received */ event VaultRewardsReceived(address indexed _by, uint256 amount); /** * @dev Fired in _processVaultRewards() and dependent functions, like processRewards() * * @param _by an address which executed the function * @param _to an address which received a reward * @param amount amount of reward received */ event VaultRewardsClaimed(address indexed _by, address indexed _to, uint256 amount); /** * @dev Fired in setVault() * * @param _by an address which executed the function, always a factory owner */ event VaultUpdated(address indexed _by, address _fromVal, address _toVal); /** * @dev Creates/deploys an instance of the core pool * * @param _ilv ILV ERC20 Token IlluviumERC20 address * @param _silv sILV ERC20 Token EscrowedIlluviumERC20 address * @param _factory Pool factory IlluviumPoolFactory instance/address * @param _poolToken token the pool operates on, for example ILV or ILV/ETH pair * @param _initBlock initial block used to calculate the rewards * @param _weight number representing a weight of the pool, actual weight fraction * is calculated as that number divided by the total pools weight and doesn't exceed one */ constructor( address _ilv, address _silv, IlluviumPoolFactory _factory, address _poolToken, uint64 _initBlock, uint32 _weight ) IlluviumPoolBase(_ilv, _silv, _factory, _poolToken, _initBlock, _weight) {} /** * @notice Calculates current vault rewards value available for address specified * * @dev Performs calculations based on current smart contract state only, * not taking into account any additional time/blocks which might have passed * * @param _staker an address to calculate vault rewards value for * @return pending calculated vault reward value for the given address */ function pendingVaultRewards(address _staker) public view returns (uint256 pending) { User memory user = users[_staker]; return weightToReward(user.totalWeight, vaultRewardsPerWeight) - user.subVaultRewards; } /** * @dev Executed only by the factory owner to Set the vault * * @param _vault an address of deployed IlluviumVault instance */ function setVault(address _vault) external { // verify function is executed by the factory owner require(factory.owner() == msg.sender, "access denied"); // verify input is set require(_vault != address(0), "zero input"); // emit an event emit VaultUpdated(msg.sender, vault, _vault); // update vault address vault = _vault; } /** * @dev Executed by the vault to transfer vault rewards ILV from the vault * into the pool * * @dev This function is executed only for ILV core pools * * @param _rewardsAmount amount of ILV rewards to transfer into the pool */ function receiveVaultRewards(uint256 _rewardsAmount) external { require(msg.sender == vault, "access denied"); // return silently if there is no reward to receive if (_rewardsAmount == 0) { return; } require(usersLockingWeight > 0, "zero locking weight"); transferIlvFrom(msg.sender, address(this), _rewardsAmount); vaultRewardsPerWeight += rewardToWeight(_rewardsAmount, usersLockingWeight); // update `poolTokenReserve` only if this is a ILV Core Pool if (poolToken == ilv) { poolTokenReserve += _rewardsAmount; } emit VaultRewardsReceived(msg.sender, _rewardsAmount); } /** * @notice Service function to calculate and pay pending vault and yield rewards to the sender * * @dev Internally executes similar function `_processRewards` from the parent smart contract * to calculate and pay yield rewards; adds vault rewards processing * * @dev Can be executed by anyone at any time, but has an effect only when * executed by deposit holder and when at least one block passes from the * previous reward processing * @dev Executed internally when "staking as a pool" (`stakeAsPool`) * @dev When timing conditions are not met (executed too frequently, or after factory * end block), function doesn't throw and exits silently * * @dev _useSILV flag has a context of yield rewards only * * @param _useSILV flag indicating whether to mint sILV token as a reward or not; * when set to true - sILV reward is minted immediately and sent to sender, * when set to false - new ILV reward deposit gets created if pool is an ILV pool * (poolToken is ILV token), or new pool deposit gets created together with sILV minted * when pool is not an ILV pool (poolToken is not an ILV token) */ function processRewards(bool _useSILV) external override { _processRewards(msg.sender, _useSILV, true); } /** * @dev Executed internally by the pool itself (from the parent `IlluviumPoolBase` smart contract) * as part of yield rewards processing logic (`IlluviumPoolBase._processRewards` function) * @dev Executed when _useSILV is false and pool is not an ILV pool - see `IlluviumPoolBase._processRewards` * * @param _staker an address which stakes (the yield reward) * @param _amount amount to be staked (yield reward amount) */ function stakeAsPool(address _staker, uint256 _amount) external { require(factory.poolExists(msg.sender), "access denied"); _sync(); User storage user = users[_staker]; if (user.tokenAmount > 0) { _processRewards(_staker, true, false); } uint256 depositWeight = _amount * YEAR_STAKE_WEIGHT_MULTIPLIER; Deposit memory newDeposit = Deposit({ tokenAmount: _amount, lockedFrom: uint64(now256()), lockedUntil: uint64(now256() + 365 days), weight: depositWeight, isYield: true }); user.tokenAmount += _amount; user.totalWeight += depositWeight; user.deposits.push(newDeposit); usersLockingWeight += depositWeight; user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight); user.subVaultRewards = weightToReward(user.totalWeight, vaultRewardsPerWeight); // update `poolTokenReserve` only if this is a LP Core Pool (stakeAsPool can be executed only for LP pool) poolTokenReserve += _amount; } /** * @inheritdoc IlluviumPoolBase * * @dev Additionally to the parent smart contract, updates vault rewards of the holder, * and updates (increases) pool token reserve (pool tokens value available in the pool) */ function _stake( address _staker, uint256 _amount, uint64 _lockedUntil, bool _useSILV, bool _isYield ) internal override { super._stake(_staker, _amount, _lockedUntil, _useSILV, _isYield); User storage user = users[_staker]; user.subVaultRewards = weightToReward(user.totalWeight, vaultRewardsPerWeight); poolTokenReserve += _amount; } /** * @inheritdoc IlluviumPoolBase * * @dev Additionally to the parent smart contract, updates vault rewards of the holder, * and updates (decreases) pool token reserve (pool tokens value available in the pool) */ function _unstake( address _staker, uint256 _depositId, uint256 _amount, bool _useSILV ) internal override { User storage user = users[_staker]; Deposit memory stakeDeposit = user.deposits[_depositId]; require(stakeDeposit.lockedFrom == 0 || now256() > stakeDeposit.lockedUntil, "deposit not yet unlocked"); poolTokenReserve -= _amount; super._unstake(_staker, _depositId, _amount, _useSILV); user.subVaultRewards = weightToReward(user.totalWeight, vaultRewardsPerWeight); } /** * @inheritdoc IlluviumPoolBase * * @dev Additionally to the parent smart contract, processes vault rewards of the holder, * and for ILV pool updates (increases) pool token reserve (pool tokens value available in the pool) */ function _processRewards( address _staker, bool _useSILV, bool _withUpdate ) internal override returns (uint256 pendingYield) { _processVaultRewards(_staker); pendingYield = super._processRewards(_staker, _useSILV, _withUpdate); // update `poolTokenReserve` only if this is a ILV Core Pool if (poolToken == ilv && !_useSILV) { poolTokenReserve += pendingYield; } } /** * @dev Used internally to process vault rewards for the staker * * @param _staker address of the user (staker) to process rewards for */ function _processVaultRewards(address _staker) private { User storage user = users[_staker]; uint256 pendingVaultClaim = pendingVaultRewards(_staker); if (pendingVaultClaim == 0) return; // read ILV token balance of the pool via standard ERC20 interface uint256 ilvBalance = IERC20(ilv).balanceOf(address(this)); require(ilvBalance >= pendingVaultClaim, "contract ILV balance too low"); // update `poolTokenReserve` only if this is a ILV Core Pool if (poolToken == ilv) { // protects against rounding errors poolTokenReserve -= pendingVaultClaim > poolTokenReserve ? poolTokenReserve : pendingVaultClaim; } user.subVaultRewards = weightToReward(user.totalWeight, vaultRewardsPerWeight); // transfer fails if pool ILV balance is not enough - which is a desired behavior transferIlv(_staker, pendingVaultClaim); emit VaultRewardsClaimed(msg.sender, _staker, pendingVaultClaim); } } /** * @title Illuvium Pool Factory * * @notice ILV Pool Factory manages Illuvium Yield farming pools, provides a single * public interface to access the pools, provides an interface for the pools * to mint yield rewards, access pool-related info, update weights, etc. * * @notice The factory is authorized (via its owner) to register new pools, change weights * of the existing pools, removing the pools (by changing their weights to zero) * * @dev The factory requires ROLE_TOKEN_CREATOR permission on the ILV token to mint yield * (see `mintYieldTo` function) * * @author Pedro Bergamini, reviewed by Basil Gorin */ contract IlluviumPoolFactory is Ownable, IlluviumAware { /** * @dev Smart contract unique identifier, a random number * @dev Should be regenerated each time smart contact source code is changed * and changes smart contract itself is to be redeployed * @dev Generated using https://www.random.org/bytes/ */ uint256 public constant FACTORY_UID = 0xc5cfd88c6e4d7e5c8a03c255f03af23c0918d8e82cac196f57466af3fd4a5ec7; /// @dev Auxiliary data structure used only in getPoolData() view function struct PoolData { // @dev pool token address (like ILV) address poolToken; // @dev pool address (like deployed core pool instance) address poolAddress; // @dev pool weight (200 for ILV pools, 800 for ILV/ETH pools - set during deployment) uint32 weight; // @dev flash pool flag bool isFlashPool; } /** * @dev ILV/block determines yield farming reward base * used by the yield pools controlled by the factory */ uint192 public ilvPerBlock; /** * @dev The yield is distributed proportionally to pool weights; * total weight is here to help in determining the proportion */ uint32 public totalWeight; /** * @dev ILV/block decreases by 3% every blocks/update (set to 91252 blocks during deployment); * an update is triggered by executing `updateILVPerBlock` public function */ uint32 public immutable blocksPerUpdate; /** * @dev End block is the last block when ILV/block can be decreased; * it is implied that yield farming stops after that block */ uint32 public endBlock; /** * @dev Each time the ILV/block ratio gets updated, the block number * when the operation has occurred gets recorded into `lastRatioUpdate` * @dev This block number is then used to check if blocks/update `blocksPerUpdate` * has passed when decreasing yield reward by 3% */ uint32 public lastRatioUpdate; /// @dev sILV token address is used to create ILV core pool(s) address public immutable silv; /// @dev Maps pool token address (like ILV) -> pool address (like core pool instance) mapping(address => address) public pools; /// @dev Keeps track of registered pool addresses, maps pool address -> exists flag mapping(address => bool) public poolExists; /** * @dev Fired in createPool() and registerPool() * * @param _by an address which executed an action * @param poolToken pool token address (like ILV) * @param poolAddress deployed pool instance address * @param weight pool weight * @param isFlashPool flag indicating if pool is a flash pool */ event PoolRegistered( address indexed _by, address indexed poolToken, address indexed poolAddress, uint64 weight, bool isFlashPool ); /** * @dev Fired in changePoolWeight() * * @param _by an address which executed an action * @param poolAddress deployed pool instance address * @param weight new pool weight */ event WeightUpdated(address indexed _by, address indexed poolAddress, uint32 weight); /** * @dev Fired in updateILVPerBlock() * * @param _by an address which executed an action * @param newIlvPerBlock new ILV/block value */ event IlvRatioUpdated(address indexed _by, uint256 newIlvPerBlock); /** * @dev Creates/deploys a factory instance * * @param _ilv ILV ERC20 token address * @param _silv sILV ERC20 token address * @param _ilvPerBlock initial ILV/block value for rewards * @param _blocksPerUpdate how frequently the rewards gets updated (decreased by 3%), blocks * @param _initBlock block number to measure _blocksPerUpdate from * @param _endBlock block number when farming stops and rewards cannot be updated anymore */ constructor( address _ilv, address _silv, uint192 _ilvPerBlock, uint32 _blocksPerUpdate, uint32 _initBlock, uint32 _endBlock ) IlluviumAware(_ilv) { // verify the inputs are set require(_silv != address(0), "sILV address not set"); require(_ilvPerBlock > 0, "ILV/block not set"); require(_blocksPerUpdate > 0, "blocks/update not set"); require(_initBlock > 0, "init block not set"); require(_endBlock > _initBlock, "invalid end block: must be greater than init block"); // verify sILV instance supplied require( EscrowedIlluviumERC20(_silv).TOKEN_UID() == 0xac3051b8d4f50966afb632468a4f61483ae6a953b74e387a01ef94316d6b7d62, "unexpected sILV TOKEN_UID" ); // save the inputs into internal state variables silv = _silv; ilvPerBlock = _ilvPerBlock; blocksPerUpdate = _blocksPerUpdate; lastRatioUpdate = _initBlock; endBlock = _endBlock; } /** * @notice Given a pool token retrieves corresponding pool address * * @dev A shortcut for `pools` mapping * * @param poolToken pool token address (like ILV) to query pool address for * @return pool address for the token specified */ function getPoolAddress(address poolToken) external view returns (address) { // read the mapping and return return pools[poolToken]; } /** * @notice Reads pool information for the pool defined by its pool token address, * designed to simplify integration with the front ends * * @param _poolToken pool token address to query pool information for * @return pool information packed in a PoolData struct */ function getPoolData(address _poolToken) public view returns (PoolData memory) { // get the pool address from the mapping address poolAddr = pools[_poolToken]; // throw if there is no pool registered for the token specified require(poolAddr != address(0), "pool not found"); // read pool information from the pool smart contract // via the pool interface (IPool) address poolToken = IPool(poolAddr).poolToken(); bool isFlashPool = IPool(poolAddr).isFlashPool(); uint32 weight = IPool(poolAddr).weight(); // create the in-memory structure and return it return PoolData({ poolToken: poolToken, poolAddress: poolAddr, weight: weight, isFlashPool: isFlashPool }); } /** * @dev Verifies if `blocksPerUpdate` has passed since last ILV/block * ratio update and if ILV/block reward can be decreased by 3% * * @return true if enough time has passed and `updateILVPerBlock` can be executed */ function shouldUpdateRatio() public view returns (bool) { // if yield farming period has ended if (blockNumber() > endBlock) { // ILV/block reward cannot be updated anymore return false; } // check if blocks/update (91252 blocks) have passed since last update return blockNumber() >= lastRatioUpdate + blocksPerUpdate; } /** * @dev Creates a core pool (IlluviumCorePool) and registers it within the factory * * @dev Can be executed by the pool factory owner only * * @param poolToken pool token address (like ILV, or ILV/ETH pair) * @param initBlock init block to be used for the pool created * @param weight weight of the pool to be created */ function createPool( address poolToken, uint64 initBlock, uint32 weight ) external virtual onlyOwner { // create/deploy new core pool instance IPool pool = new IlluviumCorePool(ilv, silv, this, poolToken, initBlock, weight); // register it within a factory registerPool(address(pool)); } /** * @dev Registers an already deployed pool instance within the factory * * @dev Can be executed by the pool factory owner only * * @param poolAddr address of the already deployed pool instance */ function registerPool(address poolAddr) public onlyOwner { // read pool information from the pool smart contract // via the pool interface (IPool) address poolToken = IPool(poolAddr).poolToken(); bool isFlashPool = IPool(poolAddr).isFlashPool(); uint32 weight = IPool(poolAddr).weight(); // ensure that the pool is not already registered within the factory require(pools[poolToken] == address(0), "this pool is already registered"); // create pool structure, register it within the factory pools[poolToken] = poolAddr; poolExists[poolAddr] = true; // update total pool weight of the factory totalWeight += weight; // emit an event emit PoolRegistered(msg.sender, poolToken, poolAddr, weight, isFlashPool); } /** * @notice Decreases ILV/block reward by 3%, can be executed * no more than once per `blocksPerUpdate` blocks */ function updateILVPerBlock() external { // checks if ratio can be updated i.e. if blocks/update (91252 blocks) have passed require(shouldUpdateRatio(), "too frequent"); // decreases ILV/block reward by 3% ilvPerBlock = (ilvPerBlock * 97) / 100; // set current block as the last ratio update block lastRatioUpdate = uint32(blockNumber()); // emit an event emit IlvRatioUpdated(msg.sender, ilvPerBlock); } /** * @dev Mints ILV tokens; executed by ILV Pool only * * @dev Requires factory to have ROLE_TOKEN_CREATOR permission * on the ILV ERC20 token instance * * @param _to an address to mint tokens to * @param _amount amount of ILV tokens to mint */ function mintYieldTo(address _to, uint256 _amount) external { // verify that sender is a pool registered withing the factory require(poolExists[msg.sender], "access denied"); // mint ILV tokens as required mintIlv(_to, _amount); } /** * @dev Changes the weight of the pool; * executed by the pool itself or by the factory owner * * @param poolAddr address of the pool to change weight for * @param weight new weight value to set to */ function changePoolWeight(address poolAddr, uint32 weight) external { // verify function is executed either by factory owner or by the pool itself require(msg.sender == owner() || poolExists[msg.sender]); // recalculate total weight totalWeight = totalWeight + weight - IPool(poolAddr).weight(); // set the new pool weight IPool(poolAddr).setWeight(weight); // emit an event emit WeightUpdated(msg.sender, poolAddr, weight); } /** * @dev Testing time-dependent functionality is difficult and the best way of * doing it is to override block number in helper test smart contracts * * @return `block.number` in mainnet, custom values in testnets (if overridden) */ function blockNumber() public view virtual returns (uint256) { // return current block number return block.number; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.3._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.3._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } /** * @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}. */ // Copied from Open Zeppelin contract ERC20 is IERC20 { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @notice Token creator is responsible for creating (minting) * tokens to an arbitrary address * @dev Role ROLE_TOKEN_CREATOR allows minting tokens * (calling `mint` function) */ uint32 public constant ROLE_TOKEN_CREATOR = 0x0001_0000; /** * @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(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] - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender] - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender] - amount; _balances[recipient] = _balances[recipient] + amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply + amount; _balances[account] = _balances[account] + amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account] - amount; _totalSupply = _totalSupply - amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev 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 {} } contract EscrowedIlluviumERC20 is ERC20("Escrowed Illuvium", "sILV"), AccessControl { /** * @dev Smart contract unique identifier, a random number * @dev Should be regenerated each time smart contact source code is changed * and changes smart contract itself is to be redeployed * @dev Generated using https://www.random.org/bytes/ */ uint256 public constant TOKEN_UID = 0xac3051b8d4f50966afb632468a4f61483ae6a953b74e387a01ef94316d6b7d62; /** * @notice Must be called by ROLE_TOKEN_CREATOR addresses. * * @param recipient address to receive the tokens. * @param amount number of tokens to be minted. */ function mint(address recipient, uint256 amount) external { require(isSenderInRole(ROLE_TOKEN_CREATOR), "insufficient privileges (ROLE_TOKEN_CREATOR required)"); _mint(recipient, amount); } /** * @param amount number of tokens to be burned. */ function burn(uint256 amount) external { _burn(msg.sender, amount); } } /** * @title Flash Pool Base * * @notice An abstract contract containing logic for a new Flash Pool version. * It fixes the REWARD_PER_WEIGHT_MULTIPLIER constant to allow bigger supply * tokens flash pools. * * @dev Deployment and initialization. * Any pool deployed must be bound to the deployed pool factory (IlluviumPoolFactory) * Additionally, 3 token instance addresses must be defined on deployment: * - ILV token address * - sILV token address, used to mint sILV rewards * - pool token address, it can be ILV token address, ILV/ETH pair address, and others * * @dev Pool weight defines the fraction of the yield current pool receives among the other pools, * pool factory is responsible for the weight synchronization between the pools. * @dev The weight is logically 10% for ILV pool and 90% for ILV/ETH pool. * Since Solidity doesn't support fractions the weight is defined by the division of * pool weight by total pools weight (sum of all registered pools within the factory) * @dev For ILV Pool we use 200 as weight and for ILV/ETH pool 800. * * @author Pedro Bergamini, reviewed by Basil Gorin */ abstract contract FlashPoolBase is IPool, IlluviumAware, ReentrancyGuard { /// @dev Data structure representing token holder using a pool struct User { // @dev Total staked amount uint256 tokenAmount; // @dev Total weight uint256 totalWeight; // @dev Auxiliary variable for yield calculation uint256 subYieldRewards; // @dev Auxiliary variable for vault rewards calculation uint256 subVaultRewards; // @dev An array of holder's deposits Deposit[] deposits; } /// @dev Token holder storage, maps token holder address to their data record mapping(address => User) public users; /// @dev Link to sILV ERC20 Token EscrowedIlluviumERC20 instance address public immutable override silv; /// @dev Link to the pool factory IlluviumPoolFactory instance IlluviumPoolFactory public immutable factory; /// @dev Link to the internal token instance, for example SNX or XYZ address public immutable internalToken; /// @dev Pool weight, 100 for ILV pool or 900 for ILV/ETH uint32 public override weight; /// @dev Block number of the last yield distribution event uint64 public override lastYieldDistribution; /// @dev Used to calculate yield rewards /// @dev This value is different from "reward per token" used in locked pool /// @dev Note: stakes are different in duration and "weight" reflects that uint256 public override yieldRewardsPerWeight; /// @dev Used to calculate yield rewards, keeps track of the tokens weight locked in staking uint256 public override usersLockingWeight; /** * @dev Stake weight is proportional to deposit amount and time locked, precisely * "deposit amount wei multiplied by (fraction of the year locked plus one)" * @dev To avoid significant precision loss due to multiplication by "fraction of the year" [0, 1], * weight is stored multiplied by 1e6 constant, as an integer * @dev Corner case 1: if time locked is zero, weight is deposit amount multiplied by 1e6 * @dev Corner case 2: if time locked is one year, fraction of the year locked is one, and * weight is a deposit amount multiplied by 2 * 1e6 */ uint256 internal constant WEIGHT_MULTIPLIER = 1e6; /** * @dev When we know beforehand that staking is done for a year, and fraction of the year locked is one, * we use simplified calculation and use the following constant instead previos one */ uint256 internal constant YEAR_STAKE_WEIGHT_MULTIPLIER = 2 * WEIGHT_MULTIPLIER; /** * @dev Rewards per weight are stored multiplied by 1e12, as integers. */ uint256 internal constant REWARD_PER_WEIGHT_MULTIPLIER = 1e18; /** * @dev Fired in _stake() and stake() * * @param _by an address which performed an operation, usually token holder * @param _from token holder address, the tokens will be returned to that address * @param amount amount of tokens staked */ event Staked(address indexed _by, address indexed _from, uint256 amount); /** * @dev Fired in _updateStakeLock() and updateStakeLock() * * @param _by an address which performed an operation * @param depositId updated deposit ID * @param lockedFrom deposit locked from value * @param lockedUntil updated deposit locked until value */ event StakeLockUpdated(address indexed _by, uint256 depositId, uint64 lockedFrom, uint64 lockedUntil); /** * @dev Fired in _unstake() and unstake() * * @param _by an address which performed an operation, usually token holder * @param _to an address which received the unstaked tokens, usually token holder * @param amount amount of tokens unstaked */ event Unstaked(address indexed _by, address indexed _to, uint256 amount); /** * @dev Fired in _sync(), sync() and dependent functions (stake, unstake, etc.) * * @param _by an address which performed an operation * @param yieldRewardsPerWeight updated yield rewards per weight value * @param lastYieldDistribution usually, current block number */ event Synchronized(address indexed _by, uint256 yieldRewardsPerWeight, uint64 lastYieldDistribution); /** * @dev Fired in _processRewards(), processRewards() and dependent functions (stake, unstake, etc.) * * @param _by an address which performed an operation * @param _to an address which claimed the yield reward * @param sIlv flag indicating if reward was paid (minted) in sILV * @param amount amount of yield paid */ event YieldClaimed(address indexed _by, address indexed _to, bool sIlv, uint256 amount); /** * @dev Fired in setWeight() * * @param _by an address which performed an operation, always a factory * @param _fromVal old pool weight value * @param _toVal new pool weight value */ event PoolWeightUpdated(address indexed _by, uint32 _fromVal, uint32 _toVal); /** * @dev Overridden in sub-contracts to construct the pool * * @param _ilv ILV ERC20 Token IlluviumERC20 address * @param _silv sILV ERC20 Token EscrowedIlluviumERC20 address * @param _factory Pool factory IlluviumPoolFactory instance/address * @param _internalToken token the pool operates on * @param _initBlock initial block used to calculate the rewards * note: _initBlock can be set to the future effectively meaning _sync() calls will do nothing * @param _weight number representing a weight of the pool, actual weight fraction * is calculated as that number divided by the total pools weight and doesn't exceed one */ constructor( address _ilv, address _silv, IlluviumPoolFactory _factory, address _internalToken, uint64 _initBlock, uint32 _weight ) IlluviumAware(_ilv) { // verify the inputs are set require(_silv != address(0), "sILV address not set"); require(address(_factory) != address(0), "ILV Pool fct address not set"); require(_internalToken != address(0), "token address not set"); require(_initBlock > 0, "init block not set"); require(_weight > 0, "pool weight not set"); // verify sILV instance supplied require( EscrowedIlluviumERC20(_silv).TOKEN_UID() == 0xac3051b8d4f50966afb632468a4f61483ae6a953b74e387a01ef94316d6b7d62, "unexpected sILV TOKEN_UID" ); // verify IlluviumPoolFactory instance supplied require( _factory.FACTORY_UID() == 0xc5cfd88c6e4d7e5c8a03c255f03af23c0918d8e82cac196f57466af3fd4a5ec7, "unexpected FACTORY_UID" ); // save the inputs into internal state variables silv = _silv; factory = _factory; internalToken = _internalToken; weight = _weight; // init the dependent internal state variables lastYieldDistribution = _initBlock; } /** * @dev Faked link to the pool token instance */ function poolToken() external view override returns(address) { return address(this); } /** * @notice Calculates current yield rewards value available for address specified * * @param _staker an address to calculate yield rewards value for * @return calculated yield reward value for the given address */ function pendingYieldRewards(address _staker) external view override returns (uint256) { // `newYieldRewardsPerWeight` will store stored or recalculated value for `yieldRewardsPerWeight` uint256 newYieldRewardsPerWeight; // if smart contract state was not updated recently, `yieldRewardsPerWeight` value // is outdated and we need to recalculate it in order to calculate pending rewards correctly if (blockNumber() > lastYieldDistribution && usersLockingWeight != 0) { uint256 endBlock = factory.endBlock(); uint256 multiplier = blockNumber() > endBlock ? endBlock - lastYieldDistribution : blockNumber() - lastYieldDistribution; uint256 ilvRewards = (multiplier * weight * factory.ilvPerBlock()) / factory.totalWeight(); // recalculated value for `yieldRewardsPerWeight` newYieldRewardsPerWeight = rewardToWeight(ilvRewards, usersLockingWeight) + yieldRewardsPerWeight; } else { // if smart contract state is up to date, we don't recalculate newYieldRewardsPerWeight = yieldRewardsPerWeight; } // based on the rewards per weight value, calculate pending rewards; User memory user = users[_staker]; uint256 pending = weightToReward(user.totalWeight, newYieldRewardsPerWeight) - user.subYieldRewards; return pending; } /** * @notice Returns total staked token balance for the given address * * @param _user an address to query balance for * @return total staked token balance */ function balanceOf(address _user) external view override returns (uint256) { // read specified user token amount and return return users[_user].tokenAmount; } /** * @notice Returns information on the given deposit for the given address * * @dev See getDepositsLength * * @param _user an address to query deposit for * @param _depositId zero-indexed deposit ID for the address specified * @return deposit info as Deposit structure */ function getDeposit(address _user, uint256 _depositId) external view override returns (Deposit memory) { // read deposit at specified index and return return users[_user].deposits[_depositId]; } /** * @notice Returns number of deposits for the given address. Allows iteration over deposits. * * @dev See getDeposit * * @param _user an address to query deposit length for * @return number of deposits for the given address */ function getDepositsLength(address _user) external view override returns (uint256) { // read deposits array length and return return users[_user].deposits.length; } /** * @notice Stakes specified amount of tokens for the specified amount of time, * and pays pending yield rewards if any * * @dev Requires amount to stake to be greater than zero * * @param _amount amount of tokens to stake * @param _lockUntil stake period as unix timestamp; zero means no locking * @param _useSILV a flag indicating if previous reward to be paid as sILV */ function stake( uint256 _amount, uint64 _lockUntil, bool _useSILV ) external override { // delegate call to an internal function _stake(msg.sender, _amount, _lockUntil, _useSILV, false); } /** * @notice Unstakes specified amount of tokens, and pays pending yield rewards if any * * @dev Requires amount to unstake to be greater than zero * * @param _depositId deposit ID to unstake from, zero-indexed * @param _amount amount of tokens to unstake * @param _useSILV a flag indicating if reward to be paid as sILV */ function unstake( uint256 _depositId, uint256 _amount, bool _useSILV ) external override { // delegate call to an internal function _unstake(msg.sender, _depositId, _amount, _useSILV); } /** * @notice Extends locking period for a given deposit * * @dev Requires new lockedUntil value to be: * higher than the current one, and * in the future, but * no more than 1 year in the future * * @param depositId updated deposit ID * @param lockedUntil updated deposit locked until value * @param useSILV used for _processRewards check if it should use ILV or sILV */ function updateStakeLock( uint256 depositId, uint64 lockedUntil, bool useSILV ) external { // sync and call processRewards _sync(); _processRewards(msg.sender, useSILV, false); // delegate call to an internal function _updateStakeLock(msg.sender, depositId, lockedUntil); } /** * @notice Service function to synchronize pool state with current time * * @dev Can be executed by anyone at any time, but has an effect only when * at least one block passes between synchronizations * @dev Executed internally when staking, unstaking, processing rewards in order * for calculations to be correct and to reflect state progress of the contract * @dev When timing conditions are not met (executed too frequently, or after factory * end block), function doesn't throw and exits silently */ function sync() external override { // delegate call to an internal function _sync(); } /** * @notice Service function to calculate and pay pending yield rewards to the sender * * @dev Can be executed by anyone at any time, but has an effect only when * executed by deposit holder and when at least one block passes from the * previous reward processing * @dev Executed internally when staking and unstaking, executes sync() under the hood * before making further calculations and payouts * @dev When timing conditions are not met (executed too frequently, or after factory * end block), function doesn't throw and exits silently * * @param _useSILV flag indicating whether to mint sILV token as a reward or not; * when set to true - sILV reward is minted immediately and sent to sender, * when set to false - new pool deposit gets created together with sILV minted */ function processRewards(bool _useSILV) external virtual override { // delegate call to an internal function _processRewards(msg.sender, _useSILV, true); } /** * @dev Executed by the factory to modify pool weight; the factory is expected * to keep track of the total pools weight when updating * * @dev Set weight to zero to disable the pool * * @param _weight new weight to set for the pool */ function setWeight(uint32 _weight) external override { // verify function is executed by the factory require(msg.sender == address(factory), "access denied"); // emit an event logging old and new weight values emit PoolWeightUpdated(msg.sender, weight, _weight); // set the new weight value weight = _weight; } /** * @dev Similar to public pendingYieldRewards, but performs calculations based on * current smart contract state only, not taking into account any additional * time/blocks which might have passed * * @param _staker an address to calculate yield rewards value for * @return pending calculated yield reward value for the given address */ function _pendingYieldRewards(address _staker) internal view returns (uint256 pending) { // read user data structure into memory User memory user = users[_staker]; // and perform the calculation using the values read return weightToReward(user.totalWeight, yieldRewardsPerWeight) - user.subYieldRewards; } /** * @dev Used internally, mostly by children implementations, see stake() * * @param _staker an address which stakes tokens and which will receive them back * @param _amount amount of tokens to stake * @param _lockUntil stake period as unix timestamp; zero means no locking * @param _useSILV a flag indicating if previous reward to be paid as sILV * @param _isYield a flag indicating if that stake is created to store yield reward * from the previously unstaked stake */ function _stake( address _staker, uint256 _amount, uint64 _lockUntil, bool _useSILV, bool _isYield ) internal virtual { // validate the inputs require(_amount > 0, "zero amount"); require( _lockUntil == 0 || (_lockUntil > now256() && _lockUntil - now256() <= 365 days), "invalid lock interval" ); // update smart contract state _sync(); // get a link to user data struct, we will write to it later User storage user = users[_staker]; // process current pending rewards if any if (user.tokenAmount > 0) { _processRewards(_staker, _useSILV, false); } // in most of the cases added amount `addedAmount` is simply `_amount` // however for deflationary tokens this can be different // read the current balance uint256 previousBalance = IERC20(internalToken).balanceOf(address(this)); // transfer `_amount`; note: some tokens may get burnt here transferPoolTokenFrom(address(msg.sender), address(this), _amount); // read new balance, usually this is just the difference `previousBalance - _amount` uint256 newBalance = IERC20(internalToken).balanceOf(address(this)); // calculate real amount taking into account deflation uint256 addedAmount = newBalance - previousBalance; // set the `lockFrom` and `lockUntil` taking into account that // zero value for `_lockUntil` means "no locking" and leads to zero values // for both `lockFrom` and `lockUntil` uint64 lockFrom = _lockUntil > 0 ? uint64(now256()) : 0; uint64 lockUntil = _lockUntil; // stake weight formula rewards for locking uint256 stakeWeight = (((lockUntil - lockFrom) * WEIGHT_MULTIPLIER) / 365 days + WEIGHT_MULTIPLIER) * addedAmount; // makes sure stakeWeight is valid assert(stakeWeight > 0); // create and save the deposit (append it to deposits array) Deposit memory deposit = Deposit({ tokenAmount: addedAmount, weight: stakeWeight, lockedFrom: lockFrom, lockedUntil: lockUntil, isYield: _isYield }); // deposit ID is an index of the deposit in `deposits` array user.deposits.push(deposit); // update user record user.tokenAmount += addedAmount; user.totalWeight += stakeWeight; user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight); // update global variable usersLockingWeight += stakeWeight; // emit an event emit Staked(msg.sender, _staker, _amount); } /** * @dev Used internally, mostly by children implementations, see unstake() * * @param _staker an address which unstakes tokens (which previously staked them) * @param _depositId deposit ID to unstake from, zero-indexed * @param _amount amount of tokens to unstake * @param _useSILV a flag indicating if reward to be paid as sILV */ function _unstake( address _staker, uint256 _depositId, uint256 _amount, bool _useSILV ) internal virtual { // verify an amount is set require(_amount > 0, "zero amount"); // get a link to user data struct, we will write to it later User storage user = users[_staker]; // get a link to the corresponding deposit, we may write to it later Deposit storage stakeDeposit = user.deposits[_depositId]; // deposit structure may get deleted, so we save isYield flag to be able to use it bool isYield = stakeDeposit.isYield; // verify available balance // if staker address ot deposit doesn't exist this check will fail as well require(stakeDeposit.tokenAmount >= _amount, "amount exceeds stake"); // update smart contract state _sync(); // and process current pending rewards if any _processRewards(_staker, _useSILV, false); // recalculate deposit weight uint256 previousWeight = stakeDeposit.weight; uint256 newWeight = (((stakeDeposit.lockedUntil - stakeDeposit.lockedFrom) * WEIGHT_MULTIPLIER) / 365 days + WEIGHT_MULTIPLIER) * (stakeDeposit.tokenAmount - _amount); // update the deposit, or delete it if its depleted if (stakeDeposit.tokenAmount - _amount == 0) { delete user.deposits[_depositId]; } else { stakeDeposit.tokenAmount -= _amount; stakeDeposit.weight = newWeight; } // update user record user.tokenAmount -= _amount; user.totalWeight = user.totalWeight - previousWeight + newWeight; user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight); // update global variable usersLockingWeight = usersLockingWeight - previousWeight + newWeight; // if the deposit was created by the pool itself as a yield reward if (isYield) { // mint the yield via the factory factory.mintYieldTo(msg.sender, _amount); } else { // otherwise just return tokens back to holder transferPoolToken(msg.sender, _amount); } // emit an event emit Unstaked(msg.sender, _staker, _amount); } /** * @dev Used internally, mostly by children implementations, see sync() * * @dev Updates smart contract state (`yieldRewardsPerWeight`, `lastYieldDistribution`), * updates factory state via `updateILVPerBlock` */ function _sync() internal virtual { // update ILV per block value in factory if required if (factory.shouldUpdateRatio()) { factory.updateILVPerBlock(); } // check bound conditions and if these are not met - // exit silently, without emitting an event uint256 endBlock = factory.endBlock(); if (lastYieldDistribution >= endBlock) { return; } if (blockNumber() <= lastYieldDistribution) { return; } // if locking weight is zero - update only `lastYieldDistribution` and exit if (usersLockingWeight == 0) { lastYieldDistribution = uint64(blockNumber()); return; } // to calculate the reward we need to know how many blocks passed, and reward per block uint256 currentBlock = blockNumber() > endBlock ? endBlock : blockNumber(); uint256 blocksPassed = currentBlock - lastYieldDistribution; uint256 ilvPerBlock = factory.ilvPerBlock(); // calculate the reward uint256 ilvReward = (blocksPassed * ilvPerBlock * weight) / factory.totalWeight(); // update rewards per weight and `lastYieldDistribution` yieldRewardsPerWeight += rewardToWeight(ilvReward, usersLockingWeight); lastYieldDistribution = uint64(currentBlock); // emit an event emit Synchronized(msg.sender, yieldRewardsPerWeight, lastYieldDistribution); } /** * @dev Used internally, mostly by children implementations, see processRewards() * * @param _staker an address which receives the reward (which has staked some tokens earlier) * @param _useSILV flag indicating whether to mint sILV token as a reward or not, see processRewards() * @param _withUpdate flag allowing to disable synchronization (see sync()) if set to false * @return pendingYield the rewards calculated and optionally re-staked */ function _processRewards( address _staker, bool _useSILV, bool _withUpdate ) internal virtual returns (uint256 pendingYield) { // update smart contract state if required if (_withUpdate) { _sync(); } // calculate pending yield rewards, this value will be returned pendingYield = _pendingYieldRewards(_staker); // if pending yield is zero - just return silently if (pendingYield == 0) return 0; // get link to a user data structure, we will write into it later User storage user = users[_staker]; // if sILV is requested if (_useSILV) { // - mint sILV mintSIlv(_staker, pendingYield); } else { // for other pools - stake as pool address ilvPool = factory.getPoolAddress(ilv); ICorePool(ilvPool).stakeAsPool(_staker, pendingYield); } // update users's record for `subYieldRewards` if requested if (_withUpdate) { user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight); } // emit an event emit YieldClaimed(msg.sender, _staker, _useSILV, pendingYield); } /** * @dev See updateStakeLock() * * @param _staker an address to update stake lock * @param _depositId updated deposit ID * @param _lockedUntil updated deposit locked until value */ function _updateStakeLock( address _staker, uint256 _depositId, uint64 _lockedUntil ) internal { // validate the input time require(_lockedUntil > now256(), "lock should be in the future"); // get a link to user data struct, we will write to it later User storage user = users[_staker]; // get a link to the corresponding deposit, we may write to it later Deposit storage stakeDeposit = user.deposits[_depositId]; // validate the input against deposit structure require(_lockedUntil > stakeDeposit.lockedUntil, "invalid new lock"); // verify locked from and locked until values if (stakeDeposit.lockedFrom == 0) { require(_lockedUntil - now256() <= 365 days, "max lock period is 365 days"); stakeDeposit.lockedFrom = uint64(now256()); } else { require(_lockedUntil - stakeDeposit.lockedFrom <= 365 days, "max lock period is 365 days"); } // update locked until value, calculate new weight stakeDeposit.lockedUntil = _lockedUntil; uint256 newWeight = (((stakeDeposit.lockedUntil - stakeDeposit.lockedFrom) * WEIGHT_MULTIPLIER) / 365 days + WEIGHT_MULTIPLIER) * stakeDeposit.tokenAmount; // save previous weight uint256 previousWeight = stakeDeposit.weight; // update weight stakeDeposit.weight = newWeight; // update user total weight and global locking weight user.totalWeight = user.totalWeight - previousWeight + newWeight; usersLockingWeight = usersLockingWeight - previousWeight + newWeight; // emit an event emit StakeLockUpdated(_staker, _depositId, stakeDeposit.lockedFrom, _lockedUntil); } /** * @dev Converts stake weight (not to be mixed with the pool weight) to * ILV reward value, applying the 10^12 division on weight * * @param _weight stake weight * @param rewardPerWeight ILV reward per weight * @return reward value normalized to 10^12 */ function weightToReward(uint256 _weight, uint256 rewardPerWeight) public pure returns (uint256) { // apply the formula and return return (_weight * rewardPerWeight) / REWARD_PER_WEIGHT_MULTIPLIER; } /** * @dev Converts reward ILV value to stake weight (not to be mixed with the pool weight), * applying the 10^12 multiplication on the reward * - OR - * @dev Converts reward ILV value to reward/weight if stake weight is supplied as second * function parameter instead of reward/weight * * @param reward yield reward * @param rewardPerWeight reward/weight (or stake weight) * @return stake weight (or reward/weight) */ function rewardToWeight(uint256 reward, uint256 rewardPerWeight) public pure returns (uint256) { // apply the reverse formula and return return (reward * REWARD_PER_WEIGHT_MULTIPLIER) / rewardPerWeight; } /** * @dev Testing time-dependent functionality is difficult and the best way of * doing it is to override block number in helper test smart contracts * * @return `block.number` in mainnet, custom values in testnets (if overridden) */ function blockNumber() public view virtual returns (uint256) { // return current block number return block.number; } /** * @dev Testing time-dependent functionality is difficult and the best way of * doing it is to override time in helper test smart contracts * * @return `block.timestamp` in mainnet, custom values in testnets (if overridden) */ function now256() public view virtual returns (uint256) { // return current block timestamp return block.timestamp; } /** * @dev Executes EscrowedIlluviumERC20.mint(_to, _values) * on the bound EscrowedIlluviumERC20 instance * * @dev Reentrancy safe due to the EscrowedIlluviumERC20 design */ function mintSIlv(address _to, uint256 _value) private { // just delegate call to the target EscrowedIlluviumERC20(silv).mint(_to, _value); } /** * @dev Executes SafeERC20.safeTransfer on a pool token * * @dev Reentrancy safety enforced via `ReentrancyGuard.nonReentrant` */ function transferPoolToken(address _to, uint256 _value) internal nonReentrant { // just delegate call to the target SafeERC20.safeTransfer(IERC20(internalToken), _to, _value); } /** * @dev Executes SafeERC20.safeTransferFrom on a pool token * * @dev Reentrancy safety enforced via `ReentrancyGuard.nonReentrant` */ function transferPoolTokenFrom( address _from, address _to, uint256 _value ) internal nonReentrant { // just delegate call to the target SafeERC20.safeTransferFrom(IERC20(internalToken), _from, _to, _value); } } /** * @title Flash Pool V2 * * @notice Flash pools represent temporary pools like SNX pool. * * @notice Flash pools doesn't lock tokens, staked tokens can be unstaked at any time * * @dev See FlashPoolBase for more details * * @author Pedro Bergamini, reviewed by Basil Gorin */ contract FlashPoolV2 is FlashPoolBase { /// @dev Pool expiration time, the pool considered to be disabled once end block is reached /// @dev Expired pools don't process any rewards, users are expected to withdraw staked tokens /// from the flash pools once they expire uint64 public endBlock; /// @dev Flag indicating pool type, true means "flash pool" bool public constant override isFlashPool = true; /** * @dev Creates/deploys an instance of the flash pool * * @param _ilv ILV ERC20 Token IlluviumERC20 address * @param _silv sILV ERC20 Token EscrowedIlluviumERC20 address * @param _factory Pool factory IlluviumPoolFactory instance/address * @param _internalToken token the pool operates on, for example ILV or ILV/ETH pair * @param _initBlock initial block used to calculate the rewards * @param _weight number representing a weight of the pool, actual weight fraction * is calculated as that number divided by the total pools weight and doesn't exceed one * @param _endBlock pool expiration time (as block number) */ constructor( address _ilv, address _silv, IlluviumPoolFactory _factory, address _internalToken, uint64 _initBlock, uint32 _weight, uint64 _endBlock ) FlashPoolBase(_ilv, _silv, _factory, _internalToken, _initBlock, _weight) { // check the inputs which are not checked by the pool base require(_endBlock > _initBlock, "end block must be higher than init block"); // assign the end block endBlock = _endBlock; } /** * @notice The function to check pool state. Flash pool is considered "disabled" * once time reaches its "end block" * * @return true if pool is disabled (time has reached end block), false otherwise */ function isPoolDisabled() public view returns (bool) { // verify the pool expiration condition and return the result return blockNumber() >= endBlock; } /** * @inheritdoc FlashPoolBase * * @dev Overrides the _stake() in base by setting the locked until value to 1 year in the future; * locked until value has only locked weight effect and doesn't do any real token locking * * @param _lockedUntil not used, overridden with now + 1 year just to have correct calculation * of the locking weights */ function _stake( address _staker, uint256 _amount, uint64 _lockedUntil, bool useSILV, bool isYield ) internal override { // override the `_lockedUntil` and execute parent // we set "locked period" to 365 days only to have correct calculation of locking weights, // the tokens are not really locked since _unstake in the core pool doesn't check the "locked period" super._stake(_staker, _amount, uint64(now256() + 365 days), useSILV, isYield); } /** * @inheritdoc FlashPoolBase * * @dev In addition to regular sync() routine of the base, set the pool weight * to zero, effectively disabling the pool in the factory * @dev If the pool is disabled regular sync() routine is ignored */ function _sync() internal override { // if pool is disabled/expired if (isPoolDisabled()) { // if weight is not yet set if (weight != 0) { // set the pool weight (sets both factory and local values) factory.changePoolWeight(address(this), 0); } // and exit return; } // for enabled pools perform regular sync() routine super._sync(); } }
* @title Illuvium Pool @notice An abstraction representing a pool, see IlluviumPoolBase for details @author Pedro Bergamini, reviewed by Basil Gorin/
interface IPool is ILinkedToILV { } struct Deposit { uint256 tokenAmount; uint256 weight; uint64 lockedFrom; uint64 lockedUntil; bool isYield; } }
6,185,422
[ 1, 45, 2906, 89, 522, 379, 8828, 225, 1922, 1223, 701, 1128, 5123, 279, 2845, 16, 2621, 467, 2906, 89, 522, 379, 2864, 2171, 364, 3189, 225, 453, 329, 303, 605, 18639, 301, 8767, 16, 10725, 329, 635, 605, 345, 330, 611, 280, 267, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 467, 2864, 353, 467, 13174, 774, 2627, 58, 288, 203, 97, 203, 225, 1958, 4019, 538, 305, 288, 203, 565, 2254, 5034, 1147, 6275, 31, 203, 565, 2254, 5034, 3119, 31, 203, 565, 2254, 1105, 8586, 1265, 31, 203, 565, 2254, 1105, 8586, 9716, 31, 203, 565, 1426, 353, 16348, 31, 203, 225, 289, 203, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: contracts\IERC20.sol pragma solidity ^0.5.0; /** * @dev ERC20 contract interface. */ contract IERC20 { function totalSupply() public view returns (uint); function transfer(address _to, uint _value) public returns (bool success); function transferFrom(address _from, address _to, uint _value) public returns (bool success); function balanceOf(address _owner) public view returns (uint balance); function approve(address _spender, uint _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint remaining); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed owner, address indexed spender, uint tokens); } // File: contracts\SafeMathLib.sol pragma solidity ^0.5.0; // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- library SafeMathLib { using SafeMathLib for uint; /** * @dev Sum two uint numbers. * @param a Number 1 * @param b Number 2 * @return uint */ function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a, "SafeMathLib.add: required c >= a"); } /** * @dev Substraction of uint numbers. * @param a Number 1 * @param b Number 2 * @return uint */ function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a, "SafeMathLib.sub: required b <= a"); c = a - b; } /** * @dev Product of two uint numbers. * @param a Number 1 * @param b Number 2 * @return uint */ function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require((a == 0 || c / a == b), "SafeMathLib.mul: required (a == 0 || c / a == b)"); } /** * @dev Division of two uint numbers. * @param a Number 1 * @param b Number 2 * @return uint */ function div(uint a, uint b) internal pure returns (uint c) { require(b > 0, "SafeMathLib.div: required b > 0"); c = a / b; } } // File: contracts\FITHTokenSale.sol pragma solidity ^0.5.0; /** * @dev Fiatech FITH token sale contract. */ contract FITHTokenSale { using SafeMathLib for uint; address payable public owner; IERC20 public tokenContract; uint256 public tokenPrice; uint256 public tokensSold; // tokens bought event raised when buyer purchases tokens event TokensBought(address _buyer, uint256 _amount, uint256 _tokensSold); // token price update event event TokenPriceUpdate(address _admin, uint256 _tokenPrice); /** * @dev Constructor */ constructor(IERC20 _tokenContract, uint256 _tokenPrice) public { require(_tokenPrice > 0, "_tokenPrice greater than zero required"); owner = msg.sender; tokenContract = _tokenContract; tokenPrice = _tokenPrice; } modifier onlyOwner() { require(msg.sender == owner, "Owner required"); _; } function tokensAvailable() public view returns (uint) { return tokenContract.balanceOf(address(this)); } function _buyTokens(uint256 _numberOfTokens) internal { require(tokensAvailable() >= _numberOfTokens, "insufficient tokens on token-sale contract"); require(tokenContract.transfer(msg.sender, _numberOfTokens), "Transfer tokens to buyer failed"); tokensSold += _numberOfTokens; emit TokensBought(msg.sender, _numberOfTokens, tokensSold); } function updateTokenPrice(uint256 _tokenPrice) public onlyOwner { require(_tokenPrice > 0 && _tokenPrice != tokenPrice, "Token price must be greater than zero and different than current"); tokenPrice = _tokenPrice; emit TokenPriceUpdate(owner, _tokenPrice); } function buyTokens(uint256 _numberOfTokens) public payable { require(msg.value == (_numberOfTokens * tokenPrice), "Incorrect number of tokens"); _buyTokens(_numberOfTokens); } function endSale() public onlyOwner { require(tokenContract.transfer(owner, tokenContract.balanceOf(address(this))), "Transfer token-sale token balance to owner failed"); // Just transfer the ether balance to the owner owner.transfer(address(this).balance); } /** * Accept ETH for tokens */ function () external payable { uint tks = (msg.value).div(tokenPrice); _buyTokens(tks); } /** * @dev Owner can transfer out (recover) any ERC20 tokens accidentally sent to this contract. * @param tokenAddress Token contract address we want to recover lost tokens from. * @param tokens Amount of tokens to be recovered, usually the same as the balance of this contract. * @return bool */ function recoverAnyERC20Token(address tokenAddress, uint tokens) external onlyOwner returns (bool ok) { ok = IERC20(tokenAddress).transfer(owner, tokens); } }
tokens bought event raised when buyer purchases tokens token price update event
{ using SafeMathLib for uint; address payable public owner; IERC20 public tokenContract; uint256 public tokenPrice; uint256 public tokensSold; event TokensBought(address _buyer, uint256 _amount, uint256 _tokensSold); event TokenPriceUpdate(address _admin, uint256 _tokenPrice); constructor(IERC20 _tokenContract, uint256 _tokenPrice) public contract FITHTokenSale { require(_tokenPrice > 0, "_tokenPrice greater than zero required"); owner = msg.sender; tokenContract = _tokenContract; tokenPrice = _tokenPrice; } modifier onlyOwner() { require(msg.sender == owner, "Owner required"); _; } function tokensAvailable() public view returns (uint) { return tokenContract.balanceOf(address(this)); } function _buyTokens(uint256 _numberOfTokens) internal { require(tokensAvailable() >= _numberOfTokens, "insufficient tokens on token-sale contract"); require(tokenContract.transfer(msg.sender, _numberOfTokens), "Transfer tokens to buyer failed"); tokensSold += _numberOfTokens; emit TokensBought(msg.sender, _numberOfTokens, tokensSold); } function updateTokenPrice(uint256 _tokenPrice) public onlyOwner { require(_tokenPrice > 0 && _tokenPrice != tokenPrice, "Token price must be greater than zero and different than current"); tokenPrice = _tokenPrice; emit TokenPriceUpdate(owner, _tokenPrice); } function buyTokens(uint256 _numberOfTokens) public payable { require(msg.value == (_numberOfTokens * tokenPrice), "Incorrect number of tokens"); _buyTokens(_numberOfTokens); } function endSale() public onlyOwner { require(tokenContract.transfer(owner, tokenContract.balanceOf(address(this))), "Transfer token-sale token balance to owner failed"); owner.transfer(address(this).balance); } function () external payable { uint tks = (msg.value).div(tokenPrice); _buyTokens(tks); } function recoverAnyERC20Token(address tokenAddress, uint tokens) external onlyOwner returns (bool ok) { ok = IERC20(tokenAddress).transfer(owner, tokens); } }
12,985,698
[ 1, 7860, 800, 9540, 871, 11531, 1347, 27037, 5405, 343, 3304, 2430, 1147, 6205, 1089, 871, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 95, 203, 202, 9940, 14060, 10477, 5664, 364, 2254, 31, 203, 202, 203, 565, 1758, 8843, 429, 1071, 3410, 31, 203, 377, 203, 202, 45, 654, 39, 3462, 1071, 1147, 8924, 31, 203, 202, 203, 202, 11890, 5034, 1071, 1147, 5147, 31, 203, 565, 2254, 5034, 1071, 2430, 55, 1673, 31, 203, 202, 203, 565, 871, 13899, 13809, 9540, 12, 2867, 389, 70, 16213, 16, 2254, 5034, 389, 8949, 16, 2254, 5034, 389, 7860, 55, 1673, 1769, 203, 202, 203, 202, 2575, 3155, 5147, 1891, 12, 2867, 389, 3666, 16, 2254, 5034, 389, 2316, 5147, 1769, 203, 202, 203, 202, 203, 202, 203, 565, 3885, 12, 45, 654, 39, 3462, 389, 2316, 8924, 16, 2254, 5034, 389, 2316, 5147, 13, 1071, 203, 203, 16351, 478, 6379, 1345, 30746, 203, 202, 95, 203, 202, 202, 6528, 24899, 2316, 5147, 405, 374, 16, 4192, 2316, 5147, 6802, 2353, 3634, 1931, 8863, 203, 1082, 203, 3639, 3410, 273, 1234, 18, 15330, 31, 203, 3639, 1147, 8924, 273, 389, 2316, 8924, 31, 203, 3639, 1147, 5147, 273, 389, 2316, 5147, 31, 203, 565, 289, 203, 202, 203, 202, 20597, 1338, 5541, 1435, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 3410, 16, 315, 5541, 1931, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 202, 203, 202, 915, 2430, 5268, 1435, 1071, 1476, 1135, 261, 11890, 13, 288, 203, 202, 202, 2463, 1147, 8924, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 202, 97, 203, 202, 203, 202, 203, 202, 203, 202, 915, 389, 70, 9835, 2 ]
pragma solidity ^0.4.24; contract/* interface */ ERC223ContractInterface { function tokenFallback(address _from, uint256 _value, bytes _data) external; } // implements ERC223 // see: https://github.com/ethereum/EIPs/issues/223 contract ERC223Contract is ERC223ContractInterface { // Reject all ERC223 compatible tokens // --- param names commented out to prevent 'Unused function parameter' compilation warnings --- function tokenFallback(address /*_from*/, uint256 /*_value*/, bytes /*_data*/) external { revert("tokenFallback rejection"); } }
implements ERC223 see: https:github.com/ethereum/EIPs/issues/223 Reject all ERC223 compatible tokens --- param names commented out to prevent 'Unused function parameter' compilation warnings ---
contract ERC223Contract is ERC223ContractInterface { function tokenFallback(address /*_from*/, uint256 /*_value*/, bytes /*_data*/) external { revert("tokenFallback rejection"); } }
5,357,334
[ 1, 17061, 4232, 39, 3787, 23, 2621, 30, 2333, 30, 6662, 18, 832, 19, 546, 822, 379, 19, 41, 18246, 19, 9618, 19, 3787, 23, 20159, 777, 4232, 39, 3787, 23, 7318, 2430, 9948, 579, 1257, 31813, 596, 358, 5309, 296, 21106, 445, 1569, 11, 8916, 5599, 9948, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 4232, 39, 3787, 23, 8924, 353, 4232, 39, 3787, 23, 8924, 1358, 288, 203, 203, 225, 445, 1147, 12355, 12, 2867, 1748, 67, 2080, 5549, 16, 2254, 5034, 1748, 67, 1132, 5549, 16, 1731, 1748, 67, 892, 5549, 13, 3903, 288, 203, 565, 15226, 2932, 2316, 12355, 283, 3710, 8863, 203, 225, 289, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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-02-23 */ // SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/utils/math/Math.sol // OpenZeppelin Contracts v4.4.0 (utils/math/Math.sol) pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // File: @openzeppelin/contracts/utils/Strings.sol // 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); } } // File: @openzeppelin/contracts/utils/Context.sol // 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; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.0 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts v4.4.0 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // 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); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: erc721a/contracts/ERC721A.sol // Creator: Chiru Labs pragma solidity ^0.8.4; error ApprovalCallerNotOwnerNorApproved(); error ApprovalQueryForNonexistentToken(); error ApproveToCaller(); error ApprovalToCurrentOwner(); error BalanceQueryForZeroAddress(); error MintedQueryForZeroAddress(); error BurnedQueryForZeroAddress(); error MintToZeroAddress(); error MintZeroQuantity(); error OwnerIndexOutOfBounds(); error OwnerQueryForNonexistentToken(); error TokenIndexOutOfBounds(); error TransferCallerNotOwnerNorApproved(); error TransferFromIncorrectOwner(); error TransferToNonERC721ReceiverImplementer(); error TransferToZeroAddress(); error URIQueryForNonexistentToken(); /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**128 - 1 (max value of uint128). */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * 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. */ function tokenByIndex(uint256 index) public view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @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. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @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 || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (!_checkOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(updatedIndex); } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @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 { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } // File: contracts/Mfer.sol pragma solidity ^0.8.4; contract BaycMfer is ERC721A, Ownable { using Strings for uint256; string baseURI; string public baseExtension = ".json"; uint256 public cost = 0.0069 ether; uint256 public freeSupply = 969; uint256 public maxFreePerTransaction = 20; uint256 public maxSupply = 6969; constructor( ) ERC721A("baycmfers", "baycmfers") { setBaseURI("ipfs://QmZAgfLXgPeqEmGi7cBhHsHV6Xqw4SumpeMvJRMW7eRkxi/"); } function _baseURI() internal view virtual override returns (string memory) { return baseURI; } function mint(uint256 _mintAmount) public payable { uint256 supply = totalSupply(); require(_mintAmount > 0); require(supply + _mintAmount <= maxSupply); // check if freeMint is opened if (supply >= freeSupply) { paidMint(_mintAmount); } else { freeMint(_mintAmount); } } function freeMint(uint256 _mintAmount) internal { uint256 supply = totalSupply(); uint256 freeAvailable = freeSupply - supply; uint256 freeToMint = Math.min(freeAvailable, _mintAmount); freeToMint = Math.min(freeToMint, maxFreePerTransaction); _safeMint(msg.sender, freeToMint); } function paidMint(uint256 _mintAmount) internal { require(msg.value >= cost * _mintAmount); _safeMint(msg.sender, _mintAmount); } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)) : ""; } function setCost(uint256 _newCost) public onlyOwner { cost = _newCost; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function setBaseExtension(string memory _newBaseExtension) public onlyOwner { baseExtension = _newBaseExtension; } function withdraw() public payable onlyOwner { (bool os, ) = payable(owner()).call{value: address(this).balance}(""); require(os); } }
File: contracts/Mfer.sol
contract BaycMfer is ERC721A, Ownable { using Strings for uint256; string baseURI; string public baseExtension = ".json"; uint256 public cost = 0.0069 ether; uint256 public freeSupply = 969; uint256 public maxFreePerTransaction = 20; uint256 public maxSupply = 6969; constructor( function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity } pragma solidity ^0.8.4; ) ERC721A("baycmfers", "baycmfers") { } function _baseURI() internal view virtual override returns (string memory) { return baseURI; } function mint(uint256 _mintAmount) public payable { uint256 supply = totalSupply(); require(_mintAmount > 0); require(supply + _mintAmount <= maxSupply); if (supply >= freeSupply) { paidMint(_mintAmount); freeMint(_mintAmount); } } function mint(uint256 _mintAmount) public payable { uint256 supply = totalSupply(); require(_mintAmount > 0); require(supply + _mintAmount <= maxSupply); if (supply >= freeSupply) { paidMint(_mintAmount); freeMint(_mintAmount); } } } else { function freeMint(uint256 _mintAmount) internal { uint256 supply = totalSupply(); uint256 freeAvailable = freeSupply - supply; uint256 freeToMint = Math.min(freeAvailable, _mintAmount); freeToMint = Math.min(freeToMint, maxFreePerTransaction); _safeMint(msg.sender, freeToMint); } function paidMint(uint256 _mintAmount) internal { require(msg.value >= cost * _mintAmount); _safeMint(msg.sender, _mintAmount); } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)) : ""; } function setCost(uint256 _newCost) public onlyOwner { cost = _newCost; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function setBaseExtension(string memory _newBaseExtension) public onlyOwner { baseExtension = _newBaseExtension; } function withdraw() public payable onlyOwner { require(os); } (bool os, ) = payable(owner()).call{value: address(this).balance}(""); }
2,456,636
[ 1, 812, 30, 20092, 19, 49, 586, 18, 18281, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 605, 528, 71, 49, 586, 353, 4232, 39, 27, 5340, 37, 16, 14223, 6914, 288, 203, 225, 1450, 8139, 364, 2254, 5034, 31, 203, 203, 225, 533, 1026, 3098, 31, 203, 225, 533, 1071, 1026, 3625, 273, 3552, 1977, 14432, 203, 225, 2254, 5034, 1071, 6991, 273, 374, 18, 713, 8148, 225, 2437, 31, 203, 225, 2254, 5034, 1071, 4843, 3088, 1283, 273, 2468, 8148, 31, 203, 225, 2254, 5034, 1071, 943, 9194, 2173, 3342, 273, 4200, 31, 203, 225, 2254, 5034, 1071, 943, 3088, 1283, 273, 20963, 8148, 31, 203, 203, 225, 3885, 12, 203, 565, 445, 389, 5771, 1345, 1429, 18881, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 787, 1345, 548, 16, 203, 3639, 2254, 5034, 10457, 203, 203, 565, 445, 389, 5205, 1345, 1429, 18881, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 787, 1345, 548, 16, 203, 3639, 2254, 5034, 10457, 203, 97, 203, 203, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 24, 31, 203, 203, 203, 203, 203, 225, 262, 4232, 39, 27, 5340, 37, 2932, 70, 528, 7670, 18881, 3113, 315, 70, 528, 7670, 18881, 7923, 288, 203, 225, 289, 203, 21281, 225, 445, 389, 1969, 3098, 1435, 2713, 1476, 5024, 3849, 1135, 261, 1080, 3778, 13, 288, 203, 565, 327, 1026, 3098, 31, 203, 225, 289, 203, 203, 225, 445, 312, 474, 12, 11890, 5034, 389, 81, 474, 6275, 13, 1071, 8843, 429, 288, 203, 565, 2 ]
./full_match/1/0x9bfBD7CaDbF2AD0980eb04D6769E766c22E801CA/sources/src/ProtectionPlan.sol
* @dev transfers an amount of ERC20 to a recipient and the webacy vault if the amount param is zero, it attempts to transfer the entire balance of the tokenId @param contractAddress the ERC20 contract @param recipient the transfer to address @param tokenId the token to transfer balance from @param amount the amount to transfer for the tokenId, if zero then this will transfer the balanceOf instead/
function _transfer1155(address contractAddress, address recipient, uint256 tokenId, uint256 amount) private returns (bool) { IERC1155 erc1155 = IERC1155(contractAddress); uint256 balance = erc1155.balanceOf(member, tokenId); uint256 transferAmount; if (balance > 0) { if (amount > 0 && amount <= balance) { transferAmount = amount; transferAmount = balance; } (bool success,) = contractAddress.call( abi.encodeWithSignature( "safeTransferFrom(address,address,uint256,uint256,bytes)", member, recipient, tokenId, transferAmount, bytes("") ) ); return success; } return false; }
16,469,016
[ 1, 2338, 18881, 392, 3844, 434, 4232, 39, 3462, 358, 279, 8027, 471, 326, 3311, 3505, 9229, 1377, 309, 326, 3844, 579, 353, 3634, 16, 518, 7531, 358, 7412, 326, 7278, 11013, 434, 326, 1147, 548, 225, 6835, 1887, 326, 4232, 39, 3462, 6835, 225, 8027, 326, 7412, 358, 1758, 225, 1147, 548, 326, 1147, 358, 7412, 11013, 628, 225, 3844, 326, 3844, 358, 7412, 364, 326, 1147, 548, 16, 309, 3634, 1508, 333, 903, 7412, 326, 11013, 951, 3560, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 389, 13866, 2499, 2539, 12, 2867, 6835, 1887, 16, 1758, 8027, 16, 2254, 5034, 1147, 548, 16, 2254, 5034, 3844, 13, 203, 3639, 3238, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 467, 654, 39, 2499, 2539, 6445, 71, 2499, 2539, 273, 467, 654, 39, 2499, 2539, 12, 16351, 1887, 1769, 203, 203, 3639, 2254, 5034, 11013, 273, 6445, 71, 2499, 2539, 18, 12296, 951, 12, 5990, 16, 1147, 548, 1769, 203, 3639, 2254, 5034, 7412, 6275, 31, 203, 3639, 309, 261, 12296, 405, 374, 13, 288, 203, 5411, 309, 261, 8949, 405, 374, 597, 3844, 1648, 11013, 13, 288, 203, 7734, 7412, 6275, 273, 3844, 31, 203, 7734, 7412, 6275, 273, 11013, 31, 203, 5411, 289, 203, 203, 5411, 261, 6430, 2216, 16, 13, 273, 6835, 1887, 18, 1991, 12, 203, 7734, 24126, 18, 3015, 1190, 5374, 12, 203, 10792, 315, 4626, 5912, 1265, 12, 2867, 16, 2867, 16, 11890, 5034, 16, 11890, 5034, 16, 3890, 2225, 16, 203, 10792, 3140, 16, 203, 10792, 8027, 16, 203, 10792, 1147, 548, 16, 203, 10792, 7412, 6275, 16, 203, 10792, 1731, 2932, 7923, 203, 7734, 262, 203, 5411, 11272, 203, 5411, 327, 2216, 31, 203, 3639, 289, 203, 3639, 327, 629, 31, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; contract FlufMarketplace is ERC1155Holder, Ownable { // Struct for setting individual assetPrices struct assetPrice { uint256 price; } // Asset Type => ERC1155 Contract Address mapping(string => address) public assetAddress; // Price set for Asset Type mapping (uint => assetPrice) public assetPricing; mapping (uint => mapping(address => bool)) public whiteList; mapping (uint => bool) public whiteListEnabled; address public flufAssetsAddress; bool public salesActive; constructor() { flufAssetsAddress = 0x6faD73936527D2a82AEA5384D252462941B44042; salesActive = false; } function setFlufAssetsAddress(address _address) public onlyOwner { flufAssetsAddress = _address; } function updateSaleActiveState(bool _bool) public onlyOwner { salesActive = _bool; } function setWhiteList(address[] calldata _addresses, uint assetId, bool _state) public onlyOwner { for (uint i = 0; i < _addresses.length; i++) { whiteList[assetId][_addresses[i]] = _state; } // Since we are setting a whitelist, it's pretty obvious that whitelisting has to be enabled for this tokenId whiteListEnabled[assetId] = true; } function setWhiteListState(uint[] calldata _assetIds, bool _state) public onlyOwner{ for (uint i = 0; i < _assetIds.length; i++) { whiteListEnabled[_assetIds[i]] = _state; } } function listNewAssetType(address _address, string memory _name) public onlyOwner returns (bool) { assetAddress[_name] = _address; return true; } function changeAssetPrice(uint256 assetId, uint256 newPrice) public payable onlyOwner { require(assetId >= 0, "You can't change the price of an asset sub zero"); require(newPrice >= 0, "You can't give away assets for free"); assetPrice storage c = assetPricing[assetId]; c.price = newPrice; } function changeAssetPriceBatch(uint256[] memory assetIds, uint256[] memory newPrices) public payable onlyOwner { for(uint x = 0; x < assetIds.length; x++) { require(assetIds[x] >= 0, "You can't change the price of an asset sub zero"); require(newPrices[x] >= 0, "You can't give away assets for free"); assetPrice storage c = assetPricing[assetIds[x]]; c.price = newPrices[x]; } } function withdrawFunds() public onlyOwner { uint balance = address(this).balance; payable(msg.sender).transfer(balance); } function isVaultStocked(uint256 assetId, uint256 quantity) public view returns (bool) { // Use the assetTypeName to lookup contract address, store balanceOf for comparison // Swap with marketplace balance check uint256 assetCount = IERC1155(flufAssetsAddress).balanceOf(address(this), assetId); return assetCount >= quantity; } function buyAsset(uint256 assetId) public payable { require(salesActive == true, "Sales are currently not active"); uint quantity = 1; // Check that vault has asset available require(isVaultStocked(assetId, quantity), "VAULT HALT: The asset you are trying to buy is not available"); // If whitelist is enabled for this assetID we should check if the user is whitelisted if(whiteListEnabled[assetId] == true){ require(whiteList[assetId][msg.sender] == true, "WHITELIST HALT: You are not whitelisted for this drop, check back later.."); } // Check that msg.sender sent enough for price require(msg.value == getAssetPrice(assetId) * quantity, "MARKET STOP: You must send the proper value to buy asset"); IERC1155(flufAssetsAddress).safeTransferFrom(address(this), msg.sender, assetId, quantity, ""); } function getEthBalance() public view returns (uint256) { return address(this).balance; } function getAssetPrice(uint assetId) public view returns(uint256) { return assetPricing[assetId].price; } function emergencyTokenWithdraw(uint256 _asset, uint256 _amount) public payable onlyOwner { IERC1155(flufAssetsAddress).safeTransferFrom(address(this), msg.sender, _asset, _amount, ""); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC1155Receiver) returns (bool) { return super.supportsInterface(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 "./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 String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC1155Receiver.sol"; import "../../../utils/introspection/ERC165.sol"; /** * @dev _Available since v3.1._ */ abstract contract ERC1155Receiver is ERC165, IERC1155Receiver { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ERC1155Receiver.sol"; /** * @dev _Available since v3.1._ */ contract ERC1155Holder is ERC1155Receiver { function onERC1155Received( address, address, uint256, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC1155Received.selector; } function onERC1155BatchReceived( address, address, uint256[] memory, uint256[] memory, bytes memory ) public virtual override returns (bytes4) { return this.onERC1155BatchReceived.selector; } } // 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 "../../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/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } }
Struct for setting individual assetPrices
contract FlufMarketplace is ERC1155Holder, Ownable { pragma solidity ^0.8.0; struct assetPrice { uint256 price; } mapping (uint => mapping(address => bool)) public whiteList; mapping (uint => bool) public whiteListEnabled; address public flufAssetsAddress; bool public salesActive; mapping(string => address) public assetAddress; mapping (uint => assetPrice) public assetPricing; constructor() { flufAssetsAddress = 0x6faD73936527D2a82AEA5384D252462941B44042; salesActive = false; } function setFlufAssetsAddress(address _address) public onlyOwner { flufAssetsAddress = _address; } function updateSaleActiveState(bool _bool) public onlyOwner { salesActive = _bool; } function setWhiteList(address[] calldata _addresses, uint assetId, bool _state) public onlyOwner { for (uint i = 0; i < _addresses.length; i++) { whiteList[assetId][_addresses[i]] = _state; } } function setWhiteList(address[] calldata _addresses, uint assetId, bool _state) public onlyOwner { for (uint i = 0; i < _addresses.length; i++) { whiteList[assetId][_addresses[i]] = _state; } } whiteListEnabled[assetId] = true; function setWhiteListState(uint[] calldata _assetIds, bool _state) public onlyOwner{ for (uint i = 0; i < _assetIds.length; i++) { whiteListEnabled[_assetIds[i]] = _state; } } function setWhiteListState(uint[] calldata _assetIds, bool _state) public onlyOwner{ for (uint i = 0; i < _assetIds.length; i++) { whiteListEnabled[_assetIds[i]] = _state; } } function listNewAssetType(address _address, string memory _name) public onlyOwner returns (bool) { assetAddress[_name] = _address; return true; } function changeAssetPrice(uint256 assetId, uint256 newPrice) public payable onlyOwner { require(assetId >= 0, "You can't change the price of an asset sub zero"); require(newPrice >= 0, "You can't give away assets for free"); assetPrice storage c = assetPricing[assetId]; c.price = newPrice; } function changeAssetPriceBatch(uint256[] memory assetIds, uint256[] memory newPrices) public payable onlyOwner { for(uint x = 0; x < assetIds.length; x++) { require(assetIds[x] >= 0, "You can't change the price of an asset sub zero"); require(newPrices[x] >= 0, "You can't give away assets for free"); assetPrice storage c = assetPricing[assetIds[x]]; c.price = newPrices[x]; } } function changeAssetPriceBatch(uint256[] memory assetIds, uint256[] memory newPrices) public payable onlyOwner { for(uint x = 0; x < assetIds.length; x++) { require(assetIds[x] >= 0, "You can't change the price of an asset sub zero"); require(newPrices[x] >= 0, "You can't give away assets for free"); assetPrice storage c = assetPricing[assetIds[x]]; c.price = newPrices[x]; } } function withdrawFunds() public onlyOwner { uint balance = address(this).balance; payable(msg.sender).transfer(balance); } function isVaultStocked(uint256 assetId, uint256 quantity) public view returns (bool) { uint256 assetCount = IERC1155(flufAssetsAddress).balanceOf(address(this), assetId); return assetCount >= quantity; } function buyAsset(uint256 assetId) public payable { require(salesActive == true, "Sales are currently not active"); uint quantity = 1; require(isVaultStocked(assetId, quantity), "VAULT HALT: The asset you are trying to buy is not available"); if(whiteListEnabled[assetId] == true){ require(whiteList[assetId][msg.sender] == true, "WHITELIST HALT: You are not whitelisted for this drop, check back later.."); } IERC1155(flufAssetsAddress).safeTransferFrom(address(this), msg.sender, assetId, quantity, ""); } function buyAsset(uint256 assetId) public payable { require(salesActive == true, "Sales are currently not active"); uint quantity = 1; require(isVaultStocked(assetId, quantity), "VAULT HALT: The asset you are trying to buy is not available"); if(whiteListEnabled[assetId] == true){ require(whiteList[assetId][msg.sender] == true, "WHITELIST HALT: You are not whitelisted for this drop, check back later.."); } IERC1155(flufAssetsAddress).safeTransferFrom(address(this), msg.sender, assetId, quantity, ""); } require(msg.value == getAssetPrice(assetId) * quantity, "MARKET STOP: You must send the proper value to buy asset"); function getEthBalance() public view returns (uint256) { return address(this).balance; } function getAssetPrice(uint assetId) public view returns(uint256) { return assetPricing[assetId].price; } function emergencyTokenWithdraw(uint256 _asset, uint256 _amount) public payable onlyOwner { IERC1155(flufAssetsAddress).safeTransferFrom(address(this), msg.sender, _asset, _amount, ""); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC1155Receiver) returns (bool) { return super.supportsInterface(interfaceId); } }
12,665,677
[ 1, 3823, 364, 3637, 7327, 3310, 31862, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 3857, 696, 3882, 24577, 353, 4232, 39, 2499, 2539, 6064, 16, 14223, 6914, 288, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 565, 1958, 3310, 5147, 288, 203, 3639, 2254, 5034, 6205, 31, 203, 565, 289, 203, 565, 2874, 261, 11890, 516, 2874, 12, 2867, 516, 1426, 3719, 1071, 27859, 31, 203, 565, 2874, 261, 11890, 516, 1426, 13, 1071, 27859, 1526, 31, 203, 565, 1758, 1071, 1183, 696, 10726, 1887, 31, 203, 565, 1426, 1071, 272, 5408, 3896, 31, 203, 377, 203, 565, 2874, 12, 1080, 516, 1758, 13, 1071, 3310, 1887, 31, 203, 565, 2874, 261, 11890, 516, 3310, 5147, 13, 1071, 3310, 52, 1512, 310, 31, 203, 565, 3885, 1435, 288, 203, 3639, 1183, 696, 10726, 1887, 273, 374, 92, 26, 507, 40, 27, 5520, 5718, 25, 5324, 40, 22, 69, 11149, 16985, 37, 8643, 5193, 40, 2947, 3247, 26, 5540, 9803, 38, 6334, 3028, 22, 31, 203, 3639, 272, 5408, 3896, 273, 629, 31, 203, 565, 289, 203, 377, 203, 565, 445, 444, 2340, 696, 10726, 1887, 12, 2867, 389, 2867, 13, 1071, 1338, 5541, 288, 203, 3639, 1183, 696, 10726, 1887, 273, 389, 2867, 31, 203, 565, 289, 203, 203, 565, 445, 1089, 30746, 3896, 1119, 12, 6430, 389, 6430, 13, 1071, 1338, 5541, 288, 203, 3639, 272, 5408, 3896, 273, 389, 6430, 31, 203, 565, 289, 203, 377, 203, 565, 445, 444, 13407, 682, 12, 2867, 8526, 745, 892, 389, 13277, 16, 2254, 3310, 548, 16, 1426, 389, 2019, 13, 1071, 1338, 2 ]
./partial_match/56/0xC6c11c8A42499E8EF89FAe2560E9a168af5C8f82/sources/HouseChef.sol
Refill rewards into chef
function refillRewards(uint256 _amount) override external nonReentrant{ updatePool(); rewardToken.safeTransferFrom(address(msg.sender), address(this), _amount); }
11,270,558
[ 1, 1957, 737, 283, 6397, 1368, 462, 10241, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1278, 737, 17631, 14727, 12, 11890, 5034, 389, 8949, 13, 3849, 3903, 1661, 426, 8230, 970, 95, 203, 3639, 1089, 2864, 5621, 203, 3639, 19890, 1345, 18, 4626, 5912, 1265, 12, 2867, 12, 3576, 18, 15330, 3631, 1758, 12, 2211, 3631, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0x108198be6f08B9A32e653A3CCB7c1Dc76d8470a0/sources/project:/FanPass.sol
Token related params
TokenData private _tokenData;
876,965
[ 1, 1345, 3746, 859, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3155, 751, 3238, 389, 2316, 751, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/4/0xfF720B2dF1b38Df6D6DabBe1B9f7cfAd5033c9e9/sources/Comptroller.sol
* @notice Claim all GAMA accrued by the holders @param holders The addresses to claim GAMA for @param gTokens The list of markets to claim GAMA in @param borrowers Whether or not to claim GAMA earned by borrowing @param suppliers Whether or not to claim GAMA earned by supplying/
function claimGama(address[] memory holders, GToken[] memory gTokens, bool borrowers, bool suppliers) public { for (uint i = 0; i < gTokens.length; i++) { GToken gToken = gTokens[i]; require(markets[address(gToken)].isListed, "market must be listed"); if (borrowers == true) { updateGamaBorrowIndex(address(gToken), borrowIndex); for (uint j = 0; j < holders.length; j++) { distributeBorrowerGama(address(gToken), holders[j], borrowIndex, true); } } if (suppliers == true) { updateGamaSupplyIndex(address(gToken)); for (uint j = 0; j < holders.length; j++) { distributeSupplierGama(address(gToken), holders[j], true); } } } for (uint i = 0; i < gTokens.length; i++) { GToken gToken = gTokens[i]; require(markets[address(gToken)].isListed, "market must be listed"); if (borrowers == true) { updateGamaBorrowIndex(address(gToken), borrowIndex); for (uint j = 0; j < holders.length; j++) { distributeBorrowerGama(address(gToken), holders[j], borrowIndex, true); } } if (suppliers == true) { updateGamaSupplyIndex(address(gToken)); for (uint j = 0; j < holders.length; j++) { distributeSupplierGama(address(gToken), holders[j], true); } } } Exp memory borrowIndex = Exp({mantissa: gToken.borrowIndex()}); for (uint i = 0; i < gTokens.length; i++) { GToken gToken = gTokens[i]; require(markets[address(gToken)].isListed, "market must be listed"); if (borrowers == true) { updateGamaBorrowIndex(address(gToken), borrowIndex); for (uint j = 0; j < holders.length; j++) { distributeBorrowerGama(address(gToken), holders[j], borrowIndex, true); } } if (suppliers == true) { updateGamaSupplyIndex(address(gToken)); for (uint j = 0; j < holders.length; j++) { distributeSupplierGama(address(gToken), holders[j], true); } } } for (uint i = 0; i < gTokens.length; i++) { GToken gToken = gTokens[i]; require(markets[address(gToken)].isListed, "market must be listed"); if (borrowers == true) { updateGamaBorrowIndex(address(gToken), borrowIndex); for (uint j = 0; j < holders.length; j++) { distributeBorrowerGama(address(gToken), holders[j], borrowIndex, true); } } if (suppliers == true) { updateGamaSupplyIndex(address(gToken)); for (uint j = 0; j < holders.length; j++) { distributeSupplierGama(address(gToken), holders[j], true); } } } for (uint i = 0; i < gTokens.length; i++) { GToken gToken = gTokens[i]; require(markets[address(gToken)].isListed, "market must be listed"); if (borrowers == true) { updateGamaBorrowIndex(address(gToken), borrowIndex); for (uint j = 0; j < holders.length; j++) { distributeBorrowerGama(address(gToken), holders[j], borrowIndex, true); } } if (suppliers == true) { updateGamaSupplyIndex(address(gToken)); for (uint j = 0; j < holders.length; j++) { distributeSupplierGama(address(gToken), holders[j], true); } } } }
8,722,138
[ 1, 9762, 777, 611, 2192, 37, 4078, 86, 5957, 635, 326, 366, 4665, 225, 366, 4665, 1021, 6138, 358, 7516, 611, 2192, 37, 364, 225, 314, 5157, 1021, 666, 434, 2267, 2413, 358, 7516, 611, 2192, 37, 316, 225, 29759, 414, 17403, 578, 486, 358, 7516, 611, 2192, 37, 425, 1303, 329, 635, 29759, 310, 225, 1169, 8127, 414, 17403, 578, 486, 358, 7516, 611, 2192, 37, 425, 1303, 329, 635, 14467, 310, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7516, 43, 20789, 12, 2867, 8526, 3778, 366, 4665, 16, 611, 1345, 8526, 3778, 314, 5157, 16, 1426, 29759, 414, 16, 1426, 1169, 8127, 414, 13, 1071, 288, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 314, 5157, 18, 2469, 31, 277, 27245, 288, 203, 5411, 611, 1345, 314, 1345, 273, 314, 5157, 63, 77, 15533, 203, 5411, 2583, 12, 3355, 2413, 63, 2867, 12, 75, 1345, 13, 8009, 291, 682, 329, 16, 315, 27151, 1297, 506, 12889, 8863, 203, 5411, 309, 261, 70, 15318, 414, 422, 638, 13, 288, 203, 7734, 1089, 43, 20789, 38, 15318, 1016, 12, 2867, 12, 75, 1345, 3631, 29759, 1016, 1769, 203, 7734, 364, 261, 11890, 525, 273, 374, 31, 525, 411, 366, 4665, 18, 2469, 31, 525, 27245, 288, 203, 10792, 25722, 38, 15318, 264, 43, 20789, 12, 2867, 12, 75, 1345, 3631, 366, 4665, 63, 78, 6487, 29759, 1016, 16, 638, 1769, 203, 7734, 289, 203, 5411, 289, 203, 5411, 309, 261, 2859, 8127, 414, 422, 638, 13, 288, 203, 7734, 1089, 43, 20789, 3088, 1283, 1016, 12, 2867, 12, 75, 1345, 10019, 203, 7734, 364, 261, 11890, 525, 273, 374, 31, 525, 411, 366, 4665, 18, 2469, 31, 525, 27245, 288, 203, 10792, 25722, 13254, 43, 20789, 12, 2867, 12, 75, 1345, 3631, 366, 4665, 63, 78, 6487, 638, 1769, 203, 7734, 289, 203, 5411, 289, 203, 3639, 289, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 314, 5157, 18, 2469, 31, 277, 27245, 288, 203, 5411, 2 ]
./full_match/1/0x3Bd85DF9633eF0205206BB519E4dDee152Bb0005/sources/contracts/token/RewardsDistributor.sol
Last known strategy principal normalized into DAI
mapping(address => uint256) private strategyPrincipal;
3,049,984
[ 1, 3024, 4846, 6252, 8897, 5640, 1368, 463, 18194, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 6252, 9155, 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 ]
// Сочетаемость глаголов (и отглагольных частей речи) с предложным // паттерном. // LC->07.08.2018 facts гл_предл language=Russian { arity=3 //violation_score=-5 generic return=boolean } #define ГЛ_ИНФ(v) инфинитив:v{}, глагол:v{} #region Предлог_В // ------------------- С ПРЕДЛОГОМ 'В' --------------------------- #region Предложный // Глаголы и отглагольные части речи, присоединяющие // предложное дополнение с предлогом В и сущ. в предложном падеже. wordentry_set Гл_В_Предл = { rus_verbs:взорваться{}, // В Дагестане взорвался автомобиль // вернуть после перекомпиляции rus_verbs:подорожать{}, // В Дагестане подорожал хлеб rus_verbs:воевать{}, // Воевал во Франции. rus_verbs:устать{}, // Устали в дороге? rus_verbs:изнывать{}, // В Лондоне Черчилль изнывал от нетерпения. rus_verbs:решить{}, // Что решат в правительстве? rus_verbs:выскакивать{}, // Один из бойцов на улицу выскакивает. rus_verbs:обстоять{}, // В действительности же дело обстояло не так. rus_verbs:подыматься{}, rus_verbs:поехать{}, // поедем в такси! rus_verbs:уехать{}, // он уехал в такси rus_verbs:прибыть{}, // они прибыли в качестве независимых наблюдателей rus_verbs:ОБЛАЧИТЬ{}, rus_verbs:ОБЛАЧАТЬ{}, rus_verbs:ОБЛАЧИТЬСЯ{}, rus_verbs:ОБЛАЧАТЬСЯ{}, rus_verbs:НАРЯДИТЬСЯ{}, rus_verbs:НАРЯЖАТЬСЯ{}, rus_verbs:ПОВАЛЯТЬСЯ{}, // повалявшись в снегу, бежать обратно в тепло. rus_verbs:ПОКРЫВАТЬ{}, // Во многих местах ее покрывали трещины, наросты и довольно плоские выступы. (ПОКРЫВАТЬ) rus_verbs:ПРОЖИГАТЬ{}, // Синий луч искрился белыми пятнами и прожигал в земле дымящуюся борозду. (ПРОЖИГАТЬ) rus_verbs:МЫЧАТЬ{}, // В огромной куче тел жалобно мычали задавленные трупами и раненые бизоны. (МЫЧАТЬ) rus_verbs:РАЗБОЙНИЧАТЬ{}, // Эти существа обычно разбойничали в трехстах милях отсюда (РАЗБОЙНИЧАТЬ) rus_verbs:МАЯЧИТЬ{}, // В отдалении маячили огромные серые туши мастодонтов и мамонтов с изогнутыми бивнями. (МАЯЧИТЬ/ЗАМАЯЧИТЬ) rus_verbs:ЗАМАЯЧИТЬ{}, rus_verbs:НЕСТИСЬ{}, // Кони неслись вперед в свободном и легком галопе (НЕСТИСЬ) rus_verbs:ДОБЫТЬ{}, // Они надеялись застать "медвежий народ" врасплох и добыть в бою голову величайшего из воинов. (ДОБЫТЬ) rus_verbs:СПУСТИТЬ{}, // Время от времени грохот или вопль объявляли о спущенной где-то во дворце ловушке. (СПУСТИТЬ) rus_verbs:ОБРАЗОВЫВАТЬСЯ{}, // Она сузила глаза, на лице ее стала образовываться маска безумия. (ОБРАЗОВЫВАТЬСЯ) rus_verbs:КИШЕТЬ{}, // в этом районе кишмя кишели разбойники и драконы. (КИШЕТЬ) rus_verbs:ДЫШАТЬ{}, // Она тяжело дышала в тисках гнева (ДЫШАТЬ) rus_verbs:ЗАДЕВАТЬ{}, // тот задевал в нем какую-то струну (ЗАДЕВАТЬ) rus_verbs:УСТУПИТЬ{}, // Так что теперь уступи мне в этом. (УСТУПИТЬ) rus_verbs:ТЕРЯТЬ{}, // Хотя он хорошо питался, он терял в весе (ТЕРЯТЬ/ПОТЕРЯТЬ) rus_verbs:ПоТЕРЯТЬ{}, rus_verbs:УТЕРЯТЬ{}, rus_verbs:РАСТЕРЯТЬ{}, rus_verbs:СМЫКАТЬСЯ{}, // Словно медленно смыкающийся во сне глаз, отверстие медленно закрывалось. (СМЫКАТЬСЯ/СОМКНУТЬСЯ, + оборот с СЛОВНО/БУДТО + вин.п.) rus_verbs:СОМКНУТЬСЯ{}, rus_verbs:РАЗВОРОШИТЬ{}, // Вольф не узнал никаких отдельных слов, но звуки и взаимодействующая высота тонов разворошили что-то в его памяти. (РАЗВОРОШИТЬ) rus_verbs:ПРОСТОЯТЬ{}, // Он поднялся и некоторое время простоял в задумчивости. (ПРОСТОЯТЬ,ВЫСТОЯТЬ,ПОСТОЯТЬ) rus_verbs:ВЫСТОЯТЬ{}, rus_verbs:ПОСТОЯТЬ{}, rus_verbs:ВЗВЕСИТЬ{}, // Он поднял и взвесил в руке один из рогов изобилия. (ВЗВЕСИТЬ/ВЗВЕШИВАТЬ) rus_verbs:ВЗВЕШИВАТЬ{}, rus_verbs:ДРЕЙФОВАТЬ{}, // Он и тогда не упадет, а будет дрейфовать в отбрасываемой диском тени. (ДРЕЙФОВАТЬ) прилагательное:быстрый{}, // Кисель быстр в приготовлении rus_verbs:призвать{}, // В День Воли белорусов призвали побороть страх и лень rus_verbs:призывать{}, rus_verbs:ВОСПОЛЬЗОВАТЬСЯ{}, // этими деньгами смогу воспользоваться в отпуске (ВОСПОЛЬЗОВАТЬСЯ) rus_verbs:КОНКУРИРОВАТЬ{}, // Наши клубы могли бы в Англии конкурировать с лидерами (КОНКУРИРОВАТЬ) rus_verbs:ПОЗВАТЬ{}, // Американскую телеведущую позвали замуж в прямом эфире (ПОЗВАТЬ) rus_verbs:ВЫХОДИТЬ{}, // Районные газеты Вологодчины будут выходить в цвете и новом формате (ВЫХОДИТЬ) rus_verbs:РАЗВОРАЧИВАТЬСЯ{}, // Сюжет фэнтези разворачивается в двух мирах (РАЗВОРАЧИВАТЬСЯ) rus_verbs:ОБСУДИТЬ{}, // В Самаре обсудили перспективы информатизации ветеринарии (ОБСУДИТЬ) rus_verbs:ВЗДРОГНУТЬ{}, // она сильно вздрогнула во сне (ВЗДРОГНУТЬ) rus_verbs:ПРЕДСТАВЛЯТЬ{}, // Сенаторы, представляющие в Комитете по разведке обе партии, поддержали эту просьбу (ПРЕДСТАВЛЯТЬ) rus_verbs:ДОМИНИРОВАТЬ{}, // в химическом составе одной из планет доминирует метан (ДОМИНИРОВАТЬ) rus_verbs:ОТКРЫТЬ{}, // Крым открыл в Москве собственный туристический офис (ОТКРЫТЬ) rus_verbs:ПОКАЗАТЬ{}, // В Пушкинском музее показали золото инков (ПОКАЗАТЬ) rus_verbs:наблюдать{}, // Наблюдаемый в отражении цвет излучения rus_verbs:ПРОЛЕТЕТЬ{}, // Крупный астероид пролетел в непосредственной близости от Земли (ПРОЛЕТЕТЬ) rus_verbs:РАССЛЕДОВАТЬ{}, // В Дагестане расследуют убийство федерального судьи (РАССЛЕДОВАТЬ) rus_verbs:ВОЗОБНОВИТЬСЯ{}, // В Кемеровской области возобновилось движение по трассам международного значения (ВОЗОБНОВИТЬСЯ) rus_verbs:ИЗМЕНИТЬСЯ{}, // изменилась она во всем (ИЗМЕНИТЬСЯ) rus_verbs:СВЕРКАТЬ{}, // за широким окном комнаты город сверкал во тьме разноцветными огнями (СВЕРКАТЬ) rus_verbs:СКОНЧАТЬСЯ{}, // В Риме скончался режиссёр знаменитого сериала «Спрут» (СКОНЧАТЬСЯ) rus_verbs:ПРЯТАТЬСЯ{}, // Cкрытые спутники прячутся в кольцах Сатурна (ПРЯТАТЬСЯ) rus_verbs:ВЫЗЫВАТЬ{}, // этот человек всегда вызывал во мне восхищение (ВЫЗЫВАТЬ) rus_verbs:ВЫПУСТИТЬ{}, // Избирательные бюллетени могут выпустить в форме брошюры (ВЫПУСТИТЬ) rus_verbs:НАЧИНАТЬСЯ{}, // В Москве начинается «марш в защиту детей» (НАЧИНАТЬСЯ) rus_verbs:ЗАСТРЕЛИТЬ{}, // В Дагестане застрелили преподавателя медресе (ЗАСТРЕЛИТЬ) rus_verbs:УРАВНЯТЬ{}, // Госзаказчиков уравняют в правах с поставщиками (УРАВНЯТЬ) rus_verbs:промахнуться{}, // в первой половине невероятным образом промахнулся экс-форвард московского ЦСКА rus_verbs:ОБЫГРАТЬ{}, // "Рубин" сенсационно обыграл в Мадриде вторую команду Испании (ОБЫГРАТЬ) rus_verbs:ВКЛЮЧИТЬ{}, // В Челябинской области включен аварийный роуминг (ВКЛЮЧИТЬ) rus_verbs:УЧАСТИТЬСЯ{}, // В селах Балаковского района участились случаи поджогов стогов сена (УЧАСТИТЬСЯ) rus_verbs:СПАСТИ{}, // В Австралии спасли повисшего на проводе коршуна (СПАСТИ) rus_verbs:ВЫПАСТЬ{}, // Отдельные фрагменты достигли земли, выпав в виде метеоритного дождя (ВЫПАСТЬ) rus_verbs:НАГРАДИТЬ{}, // В Лондоне наградили лауреатов премии Brit Awards (НАГРАДИТЬ) rus_verbs:ОТКРЫТЬСЯ{}, // в Москве открылся первый международный кинофестиваль rus_verbs:ПОДНИМАТЬСЯ{}, // во мне поднималось раздражение rus_verbs:ЗАВЕРШИТЬСЯ{}, // В Италии завершился традиционный Венецианский карнавал (ЗАВЕРШИТЬСЯ) инфинитив:проводить{ вид:несоверш }, // Кузбасские депутаты проводят в Кемерове прием граждан глагол:проводить{ вид:несоверш }, деепричастие:проводя{}, rus_verbs:отсутствовать{}, // Хозяйка квартиры в этот момент отсутствовала rus_verbs:доложить{}, // об итогах своего визита он намерен доложить в американском сенате и Белом доме (ДОЛОЖИТЬ ОБ, В предл) rus_verbs:ИЗДЕВАТЬСЯ{}, // В Эйлате издеваются над туристами (ИЗДЕВАТЬСЯ В предл) rus_verbs:НАРУШИТЬ{}, // В нескольких регионах нарушено наземное транспортное сообщение (НАРУШИТЬ В предл) rus_verbs:БЕЖАТЬ{}, // далеко внизу во тьме бежала невидимая река (БЕЖАТЬ В предл) rus_verbs:СОБРАТЬСЯ{}, // Дмитрий оглядел собравшихся во дворе мальчишек (СОБРАТЬСЯ В предл) rus_verbs:ПОСЛЫШАТЬСЯ{}, // далеко вверху во тьме послышался ответ (ПОСЛЫШАТЬСЯ В предл) rus_verbs:ПОКАЗАТЬСЯ{}, // во дворе показалась высокая фигура (ПОКАЗАТЬСЯ В предл) rus_verbs:УЛЫБНУТЬСЯ{}, // Дмитрий горько улыбнулся во тьме (УЛЫБНУТЬСЯ В предл) rus_verbs:ТЯНУТЬСЯ{}, // убежища тянулись во всех направлениях (ТЯНУТЬСЯ В предл) rus_verbs:РАНИТЬ{}, // В американском университете ранили человека (РАНИТЬ В предл) rus_verbs:ЗАХВАТИТЬ{}, // Пираты освободили корабль, захваченный в Гвинейском заливе (ЗАХВАТИТЬ В предл) rus_verbs:РАЗБЕГАТЬСЯ{}, // люди разбегались во всех направлениях (РАЗБЕГАТЬСЯ В предл) rus_verbs:ПОГАСНУТЬ{}, // во всем доме погас свет (ПОГАСНУТЬ В предл) rus_verbs:ПОШЕВЕЛИТЬСЯ{}, // Дмитрий пошевелился во сне (ПОШЕВЕЛИТЬСЯ В предл) rus_verbs:ЗАСТОНАТЬ{}, // раненый застонал во сне (ЗАСТОНАТЬ В предл) прилагательное:ВИНОВАТЫЙ{}, // во всем виновато вино (ВИНОВАТЫЙ В) rus_verbs:ОСТАВЛЯТЬ{}, // США оставляют в районе Персидского залива только один авианосец (ОСТАВЛЯТЬ В предл) rus_verbs:ОТКАЗЫВАТЬСЯ{}, // В России отказываются от планов авиагруппы в Арктике (ОТКАЗЫВАТЬСЯ В предл) rus_verbs:ЛИКВИДИРОВАТЬ{}, // В Кабардино-Балкарии ликвидирован подпольный завод по переработке нефти (ЛИКВИДИРОВАТЬ В предл) rus_verbs:РАЗОБЛАЧИТЬ{}, // В США разоблачили крупнейшую махинацию с кредитками (РАЗОБЛАЧИТЬ В предл) rus_verbs:СХВАТИТЬ{}, // их схватили во сне (СХВАТИТЬ В предл) rus_verbs:НАЧАТЬ{}, // В Белгороде начали сбор подписей за отставку мэра (НАЧАТЬ В предл) rus_verbs:РАСТИ{}, // Cамая маленькая муха растёт в голове муравья (РАСТИ В предл) rus_verbs:похитить{}, // Двое россиян, похищенных террористами в Сирии, освобождены (похитить в предл) rus_verbs:УЧАСТВОВАТЬ{}, // были застрелены два испанских гражданских гвардейца , участвовавших в слежке (УЧАСТВОВАТЬ В) rus_verbs:УСЫНОВИТЬ{}, // Американцы забирают усыновленных в России детей (УСЫНОВИТЬ В) rus_verbs:ПРОИЗВЕСТИ{}, // вы не увидите мясо или молоко , произведенное в районе (ПРОИЗВЕСТИ В предл) rus_verbs:ОРИЕНТИРОВАТЬСЯ{}, // призван помочь госслужащему правильно ориентироваться в сложных нравственных коллизиях (ОРИЕНТИРОВАТЬСЯ В) rus_verbs:ПОВРЕДИТЬ{}, // В зале игровых автоматов повреждены стены и потолок (ПОВРЕДИТЬ В предл) rus_verbs:ИЗЪЯТЬ{}, // В настоящее время в детском учреждении изъяты суточные пробы пищи (ИЗЪЯТЬ В предл) rus_verbs:СОДЕРЖАТЬСЯ{}, // осужденных , содержащихся в помещениях штрафного изолятора (СОДЕРЖАТЬСЯ В) rus_verbs:ОТЧИСЛИТЬ{}, // был отчислен за неуспеваемость в 2007 году (ОТЧИСЛИТЬ В предл) rus_verbs:проходить{}, // находился на санкционированном митинге , проходившем в рамках празднования Дня народного единства (проходить в предл) rus_verbs:ПОДУМЫВАТЬ{}, // сейчас в правительстве Приамурья подумывают о создании специального пункта помощи туристам (ПОДУМЫВАТЬ В) rus_verbs:ОТРАПОРТОВЫВАТЬ{}, // главы субъектов не просто отрапортовывали в Москве (ОТРАПОРТОВЫВАТЬ В предл) rus_verbs:ВЕСТИСЬ{}, // в городе ведутся работы по установке праздничной иллюминации (ВЕСТИСЬ В) rus_verbs:ОДОБРИТЬ{}, // Одобренным в первом чтении законопроектом (ОДОБРИТЬ В) rus_verbs:ЗАМЫЛИТЬСЯ{}, // ему легче исправлять , то , что замылилось в глазах предыдущего руководства (ЗАМЫЛИТЬСЯ В) rus_verbs:АВТОРИЗОВАТЬСЯ{}, // потом имеют право авторизоваться в системе Международного бакалавриата (АВТОРИЗОВАТЬСЯ В) rus_verbs:ОПУСТИТЬСЯ{}, // Россия опустилась в списке на шесть позиций (ОПУСТИТЬСЯ В предл) rus_verbs:СГОРЕТЬ{}, // Совладелец сгоревшего в Бразилии ночного клуба сдался полиции (СГОРЕТЬ В) частица:нет{}, // В этом нет сомнения. частица:нету{}, // В этом нету сомнения. rus_verbs:поджечь{}, // Поджегший себя в Москве мужчина оказался ветераном-афганцем rus_verbs:ввести{}, // В Молдавии введен запрет на амнистию или помилование педофилов. прилагательное:ДОСТУПНЫЙ{}, // Наиболее интересные таблички доступны в основной экспозиции музея (ДОСТУПНЫЙ В) rus_verbs:ПОВИСНУТЬ{}, // вопрос повис в мглистом демократическом воздухе (ПОВИСНУТЬ В) rus_verbs:ВЗОРВАТЬ{}, // В Ираке смертник взорвал в мечети группу туркменов (ВЗОРВАТЬ В) rus_verbs:ОТНЯТЬ{}, // В Финляндии у россиянки, прибывшей по туристической визе, отняли детей (ОТНЯТЬ В) rus_verbs:НАЙТИ{}, // Я недавно посетил врача и у меня в глазах нашли какую-то фигню (НАЙТИ В предл) rus_verbs:ЗАСТРЕЛИТЬСЯ{}, // Девушка, застрелившаяся в центре Киева, была замешана в скандале с влиятельными людьми (ЗАСТРЕЛИТЬСЯ В) rus_verbs:стартовать{}, // В Страсбурге сегодня стартует зимняя сессия Парламентской ассамблеи Совета Европы (стартовать в) rus_verbs:ЗАКЛАДЫВАТЬСЯ{}, // Отношение к деньгам закладывается в детстве (ЗАКЛАДЫВАТЬСЯ В) rus_verbs:НАПИВАТЬСЯ{}, // Депутатам помешают напиваться в здании Госдумы (НАПИВАТЬСЯ В) rus_verbs:ВЫПРАВИТЬСЯ{}, // Прежде всего было заявлено, что мировая экономика каким-то образом сама выправится в процессе бизнес-цикла (ВЫПРАВИТЬСЯ В) rus_verbs:ЯВЛЯТЬСЯ{}, // она являлась ко мне во всех моих снах (ЯВЛЯТЬСЯ В) rus_verbs:СТАЖИРОВАТЬСЯ{}, // сейчас я стажируюсь в одной компании (СТАЖИРОВАТЬСЯ В) rus_verbs:ОБСТРЕЛЯТЬ{}, // Уроженцы Чечни, обстрелявшие полицейских в центре Москвы, арестованы (ОБСТРЕЛЯТЬ В) rus_verbs:РАСПРОСТРАНИТЬ{}, // Воски — распространённые в растительном и животном мире сложные эфиры высших жирных кислот и высших высокомолекулярных спиртов (РАСПРОСТРАНИТЬ В) rus_verbs:ПРИВЕСТИ{}, // Сравнительная фугасность некоторых взрывчатых веществ приведена в следующей таблице (ПРИВЕСТИ В) rus_verbs:ЗАПОДОЗРИТЬ{}, // Чиновников Минкультуры заподозрили в афере с заповедными землями (ЗАПОДОЗРИТЬ В) rus_verbs:НАСТУПАТЬ{}, // В Гренландии стали наступать ледники (НАСТУПАТЬ В) rus_verbs:ВЫДЕЛЯТЬСЯ{}, // В истории Земли выделяются следующие ледниковые эры (ВЫДЕЛЯТЬСЯ В) rus_verbs:ПРЕДСТАВИТЬ{}, // Данные представлены в хронологическом порядке (ПРЕДСТАВИТЬ В) rus_verbs:ОБРУШИТЬСЯ{}, // В Северной Осетии на воинскую часть обрушилась снежная лавина (ОБРУШИТЬСЯ В, НА) rus_verbs:ПОДАВАТЬ{}, // Готовые компоты подают в столовых и кафе (ПОДАВАТЬ В) rus_verbs:ГОТОВИТЬ{}, // Сегодня компот готовят в домашних условиях из сухофруктов или замороженных фруктов и ягод (ГОТОВИТЬ В) rus_verbs:ВОЗДЕЛЫВАТЬСЯ{}, // в настоящее время он повсеместно возделывается в огородах (ВОЗДЕЛЫВАТЬСЯ В) rus_verbs:РАСКЛАДЫВАТЬ{}, // Созревшие семенные экземпляры раскладывают на солнце или в теплом месте, где они делаются мягкими (РАСКЛАДЫВАТЬСЯ В, НА) rus_verbs:РАСКЛАДЫВАТЬСЯ{}, rus_verbs:СОБИРАТЬСЯ{}, // Обыкновенно огурцы собираются в полуспелом состоянии (СОБИРАТЬСЯ В) rus_verbs:ПРОГРЕМЕТЬ{}, // В торговом центре Ижевска прогремел взрыв (ПРОГРЕМЕТЬ В) rus_verbs:СНЯТЬ{}, // чтобы снять их во всей красоте. (СНЯТЬ В) rus_verbs:ЯВИТЬСЯ{}, // она явилась к нему во сне. (ЯВИТЬСЯ В) rus_verbs:ВЕРИТЬ{}, // мы же во всем верили капитану. (ВЕРИТЬ В предл) rus_verbs:выдержать{}, // Игра выдержана в научно-фантастическом стиле. (ВЫДЕРЖАННЫЙ В) rus_verbs:ПРЕОДОЛЕТЬ{}, // мы пытались преодолеть ее во многих местах. (ПРЕОДОЛЕТЬ В) инфинитив:НАПИСАТЬ{ aux stress="напис^ать" }, // Программа, написанная в спешке, выполнила недопустимую операцию. (НАПИСАТЬ В) глагол:НАПИСАТЬ{ aux stress="напис^ать" }, прилагательное:НАПИСАННЫЙ{}, rus_verbs:ЕСТЬ{}, // ты даже во сне ел. (ЕСТЬ/кушать В) rus_verbs:УСЕСТЬСЯ{}, // Он удобно уселся в кресле. (УСЕСТЬСЯ В) rus_verbs:ТОРГОВАТЬ{}, // Он торгует в палатке. (ТОРГОВАТЬ В) rus_verbs:СОВМЕСТИТЬ{}, // Он совместил в себе писателя и художника. (СОВМЕСТИТЬ В) rus_verbs:ЗАБЫВАТЬ{}, // об этом нельзя забывать даже во сне. (ЗАБЫВАТЬ В) rus_verbs:поговорить{}, // Давайте поговорим об этом в присутствии адвоката rus_verbs:убрать{}, // В вагонах метро для комфорта пассажиров уберут сиденья (УБРАТЬ В, ДЛЯ) rus_verbs:упасть{}, // В Таиланде на автобус с российскими туристами упал башенный кран (УПАСТЬ В, НА) rus_verbs:раскрыть{}, // В России раскрыли крупнейшую в стране сеть фальшивомонетчиков (РАСКРЫТЬ В) rus_verbs:соединить{}, // соединить в себе (СОЕДИНИТЬ В предл) rus_verbs:избрать{}, // В Южной Корее избран новый президент (ИЗБРАТЬ В предл) rus_verbs:проводиться{}, // Обыски проводятся в воронежском Доме прав человека (ПРОВОДИТЬСЯ В) безлич_глагол:хватает{}, // В этой статье не хватает ссылок на источники информации. (БЕЗЛИЧ хватать в) rus_verbs:наносить{}, // В ближнем бою наносит мощные удары своим костлявым кулаком. (НАНОСИТЬ В + предл.) rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА) прилагательное:известный{}, // В Европе сахар был известен ещё римлянам. (ИЗВЕСТНЫЙ В) rus_verbs:выработать{}, // Способы, выработанные во Франции, перешли затем в Германию и другие страны Европы. (ВЫРАБОТАТЬ В) rus_verbs:КУЛЬТИВИРОВАТЬСЯ{}, // Культивируется в регионах с умеренным климатом с умеренным количеством осадков и требует плодородной почвы. (КУЛЬТИВИРОВАТЬСЯ В) rus_verbs:чаять{}, // мама души не чаяла в своих детях (ЧАЯТЬ В) rus_verbs:улыбаться{}, // Вадим улыбался во сне. (УЛЫБАТЬСЯ В) rus_verbs:растеряться{}, // Приезжие растерялись в бетонном лабиринте улиц (РАСТЕРЯТЬСЯ В) rus_verbs:выть{}, // выли волки где-то в лесу (ВЫТЬ В) rus_verbs:ЗАВЕРИТЬ{}, // выступавший заверил нас в намерении выполнить обещание (ЗАВЕРИТЬ В) rus_verbs:ИСЧЕЗНУТЬ{}, // звери исчезли во мраке. (ИСЧЕЗНУТЬ В) rus_verbs:ВСТАТЬ{}, // встать во главе человечества. (ВСТАТЬ В) rus_verbs:УПОТРЕБЛЯТЬ{}, // В Тибете употребляют кирпичный зелёный чай. (УПОТРЕБЛЯТЬ В) rus_verbs:ПОДАВАТЬСЯ{}, // Напиток охлаждается и подаётся в холодном виде. (ПОДАВАТЬСЯ В) rus_verbs:ИСПОЛЬЗОВАТЬСЯ{}, // в игре используются текстуры большего разрешения (ИСПОЛЬЗОВАТЬСЯ В) rus_verbs:объявить{}, // В газете объявили о конкурсе. rus_verbs:ВСПЫХНУТЬ{}, // во мне вспыхнул гнев. (ВСПЫХНУТЬ В) rus_verbs:КРЫТЬСЯ{}, // В его словах кроется угроза. (КРЫТЬСЯ В) rus_verbs:подняться{}, // В классе вдруг поднялся шум. (подняться в) rus_verbs:наступить{}, // В классе наступила полная тишина. (наступить в) rus_verbs:кипеть{}, // В нём кипит злоба. (кипеть в) rus_verbs:соединиться{}, // В нём соединились храбрость и великодушие. (соединиться в) инфинитив:ПАРИТЬ{ aux stress="пар^ить"}, // Высоко в небе парит орёл, плавно описывая круги. (ПАРИТЬ В) глагол:ПАРИТЬ{ aux stress="пар^ить"}, деепричастие:паря{ aux stress="пар^я" }, прилагательное:ПАРЯЩИЙ{}, прилагательное:ПАРИВШИЙ{}, rus_verbs:СИЯТЬ{}, // Главы собора сияли в лучах солнца. (СИЯТЬ В) rus_verbs:РАСПОЛОЖИТЬ{}, // Гостиница расположена глубоко в горах. (РАСПОЛОЖИТЬ В) rus_verbs:развиваться{}, // Действие в комедии развивается в двух планах. (развиваться в) rus_verbs:ПОСАДИТЬ{}, // Дети посадили у нас во дворе цветы. (ПОСАДИТЬ В) rus_verbs:ИСКОРЕНЯТЬ{}, // Дурные привычки следует искоренять в самом начале. (ИСКОРЕНЯТЬ В) rus_verbs:ВОССТАНОВИТЬ{}, // Его восстановили в правах. (ВОССТАНОВИТЬ В) rus_verbs:ПОЛАГАТЬСЯ{}, // мы полагаемся на него в этих вопросах (ПОЛАГАТЬСЯ В) rus_verbs:УМИРАТЬ{}, // они умирали во сне. (УМИРАТЬ В) rus_verbs:ПРИБАВИТЬ{}, // Она сильно прибавила в весе. (ПРИБАВИТЬ В) rus_verbs:посмотреть{}, // Посмотрите в списке. (посмотреть в) rus_verbs:производиться{}, // Выдача новых паспортов будет производиться в следующем порядке (производиться в) rus_verbs:принять{}, // Документ принят в следующей редакции (принять в) rus_verbs:сверкнуть{}, // меч его сверкнул во тьме. (сверкнуть в) rus_verbs:ВЫРАБАТЫВАТЬ{}, // ты должен вырабатывать в себе силу воли (ВЫРАБАТЫВАТЬ В) rus_verbs:достать{}, // Эти сведения мы достали в Волгограде. (достать в) rus_verbs:звучать{}, // в доме звучала музыка (звучать в) rus_verbs:колебаться{}, // колеблется в выборе (колебаться в) rus_verbs:мешать{}, // мешать в кастрюле суп (мешать в) rus_verbs:нарастать{}, // во мне нарастал гнев (нарастать в) rus_verbs:отбыть{}, // Вадим отбыл в неизвестном направлении (отбыть в) rus_verbs:светиться{}, // во всем доме светилось только окно ее спальни. (светиться в) rus_verbs:вычитывать{}, // вычитывать в книге rus_verbs:гудеть{}, // У него в ушах гудит. rus_verbs:давать{}, // В этой лавке дают в долг? rus_verbs:поблескивать{}, // Красивое стеклышко поблескивало в пыльной траве у дорожки. rus_verbs:разойтись{}, // Они разошлись в темноте. rus_verbs:прибежать{}, // Мальчик прибежал в слезах. rus_verbs:биться{}, // Она билась в истерике. rus_verbs:регистрироваться{}, // регистрироваться в системе rus_verbs:считать{}, // я буду считать в уме rus_verbs:трахаться{}, // трахаться в гамаке rus_verbs:сконцентрироваться{}, // сконцентрироваться в одной точке rus_verbs:разрушать{}, // разрушать в дробилке rus_verbs:засидеться{}, // засидеться в гостях rus_verbs:засиживаться{}, // засиживаться в гостях rus_verbs:утопить{}, // утопить лодку в реке (утопить в реке) rus_verbs:навестить{}, // навестить в доме престарелых rus_verbs:запомнить{}, // запомнить в кэше rus_verbs:убивать{}, // убивать в помещении полиции (-score убивать неодуш. дом.) rus_verbs:базироваться{}, // установка базируется в черте города (ngram черта города - проверить что есть проверка) rus_verbs:покупать{}, // Чаще всего россияне покупают в интернете бытовую технику. rus_verbs:ходить{}, // ходить в пальто (сделать ХОДИТЬ + в + ОДЕЖДА предл.п.) rus_verbs:заложить{}, // диверсанты заложили в помещении бомбу rus_verbs:оглядываться{}, // оглядываться в зеркале rus_verbs:нарисовать{}, // нарисовать в тетрадке rus_verbs:пробить{}, // пробить отверствие в стене rus_verbs:повертеть{}, // повертеть в руке rus_verbs:вертеть{}, // Я вертел в руках rus_verbs:рваться{}, // Веревка рвется в месте надреза rus_verbs:распространяться{}, // распространяться в среде наркоманов rus_verbs:попрощаться{}, // попрощаться в здании морга rus_verbs:соображать{}, // соображать в уме инфинитив:просыпаться{ вид:несоверш }, глагол:просыпаться{ вид:несоверш }, // просыпаться в чужой кровати rus_verbs:заехать{}, // Коля заехал в гости (в гости - устойчивый наречный оборот) rus_verbs:разобрать{}, // разобрать в гараже rus_verbs:помереть{}, // помереть в пути rus_verbs:различить{}, // различить в темноте rus_verbs:рисовать{}, // рисовать в графическом редакторе rus_verbs:проследить{}, // проследить в записях камер слежения rus_verbs:совершаться{}, // Правосудие совершается в суде rus_verbs:задремать{}, // задремать в кровати rus_verbs:ругаться{}, // ругаться в комнате rus_verbs:зазвучать{}, // зазвучать в радиоприемниках rus_verbs:задохнуться{}, // задохнуться в воде rus_verbs:порождать{}, // порождать в неокрепших умах rus_verbs:отдыхать{}, // отдыхать в санатории rus_verbs:упоминаться{}, // упоминаться в предыдущем сообщении rus_verbs:образовать{}, // образовать в пробирке темную взвесь rus_verbs:отмечать{}, // отмечать в списке rus_verbs:подчеркнуть{}, // подчеркнуть в блокноте rus_verbs:плясать{}, // плясать в откружении незнакомых людей rus_verbs:повысить{}, // повысить в звании rus_verbs:поджидать{}, // поджидать в подъезде rus_verbs:отказать{}, // отказать в пересмотре дела rus_verbs:раствориться{}, // раствориться в бензине rus_verbs:отражать{}, // отражать в стихах rus_verbs:дремать{}, // дремать в гамаке rus_verbs:применяться{}, // применяться в домашних условиях rus_verbs:присниться{}, // присниться во сне rus_verbs:трястись{}, // трястись в драндулете rus_verbs:сохранять{}, // сохранять в неприкосновенности rus_verbs:расстрелять{}, // расстрелять в ложбине rus_verbs:рассчитать{}, // рассчитать в программе rus_verbs:перебирать{}, // перебирать в руке rus_verbs:разбиться{}, // разбиться в аварии rus_verbs:поискать{}, // поискать в углу rus_verbs:мучиться{}, // мучиться в тесной клетке rus_verbs:замелькать{}, // замелькать в телевизоре rus_verbs:грустить{}, // грустить в одиночестве rus_verbs:крутить{}, // крутить в банке rus_verbs:объявиться{}, // объявиться в городе rus_verbs:подготовить{}, // подготовить в тайне rus_verbs:различать{}, // различать в смеси rus_verbs:обнаруживать{}, // обнаруживать в крови rus_verbs:киснуть{}, // киснуть в захолустье rus_verbs:оборваться{}, // оборваться в начале фразы rus_verbs:запутаться{}, // запутаться в веревках rus_verbs:общаться{}, // общаться в интимной обстановке rus_verbs:сочинить{}, // сочинить в ресторане rus_verbs:изобрести{}, // изобрести в домашней лаборатории rus_verbs:прокомментировать{}, // прокомментировать в своем блоге rus_verbs:давить{}, // давить в зародыше rus_verbs:повториться{}, // повториться в новом обличье rus_verbs:отставать{}, // отставать в общем зачете rus_verbs:разработать{}, // разработать в лаборатории rus_verbs:качать{}, // качать в кроватке rus_verbs:заменить{}, // заменить в двигателе rus_verbs:задыхаться{}, // задыхаться в душной и влажной атмосфере rus_verbs:забегать{}, // забегать в спешке rus_verbs:наделать{}, // наделать в решении ошибок rus_verbs:исказиться{}, // исказиться в кривом зеркале rus_verbs:тушить{}, // тушить в помещении пожар rus_verbs:охранять{}, // охранять в здании входы rus_verbs:приметить{}, // приметить в кустах rus_verbs:скрыть{}, // скрыть в складках одежды rus_verbs:удерживать{}, // удерживать в заложниках rus_verbs:увеличиваться{}, // увеличиваться в размере rus_verbs:красоваться{}, // красоваться в новом платье rus_verbs:сохраниться{}, // сохраниться в тепле rus_verbs:лечить{}, // лечить в стационаре rus_verbs:смешаться{}, // смешаться в баке rus_verbs:прокатиться{}, // прокатиться в троллейбусе rus_verbs:договариваться{}, // договариваться в закрытом кабинете rus_verbs:опубликовать{}, // опубликовать в официальном блоге rus_verbs:охотиться{}, // охотиться в прериях rus_verbs:отражаться{}, // отражаться в окне rus_verbs:понизить{}, // понизить в должности rus_verbs:обедать{}, // обедать в ресторане rus_verbs:посидеть{}, // посидеть в тени rus_verbs:сообщаться{}, // сообщаться в оппозиционной газете rus_verbs:свершиться{}, // свершиться в суде rus_verbs:ночевать{}, // ночевать в гостинице rus_verbs:темнеть{}, // темнеть в воде rus_verbs:гибнуть{}, // гибнуть в застенках rus_verbs:усиливаться{}, // усиливаться в направлении главного удара rus_verbs:расплыться{}, // расплыться в улыбке rus_verbs:превышать{}, // превышать в несколько раз rus_verbs:проживать{}, // проживать в отдельной коморке rus_verbs:голубеть{}, // голубеть в тепле rus_verbs:исследовать{}, // исследовать в естественных условиях rus_verbs:обитать{}, // обитать в лесу rus_verbs:скучать{}, // скучать в одиночестве rus_verbs:сталкиваться{}, // сталкиваться в воздухе rus_verbs:таиться{}, // таиться в глубине rus_verbs:спасать{}, // спасать в море rus_verbs:заблудиться{}, // заблудиться в лесу rus_verbs:создаться{}, // создаться в новом виде rus_verbs:пошарить{}, // пошарить в кармане rus_verbs:планировать{}, // планировать в программе rus_verbs:отбить{}, // отбить в нижней части rus_verbs:отрицать{}, // отрицать в суде свою вину rus_verbs:основать{}, // основать в пустыне новый город rus_verbs:двоить{}, // двоить в глазах rus_verbs:устоять{}, // устоять в лодке rus_verbs:унять{}, // унять в ногах дрожь rus_verbs:отзываться{}, // отзываться в обзоре rus_verbs:притормозить{}, // притормозить в траве rus_verbs:читаться{}, // читаться в глазах rus_verbs:житься{}, // житься в деревне rus_verbs:заиграть{}, // заиграть в жилах rus_verbs:шевелить{}, // шевелить в воде rus_verbs:зазвенеть{}, // зазвенеть в ушах rus_verbs:зависнуть{}, // зависнуть в библиотеке rus_verbs:затаить{}, // затаить в душе обиду rus_verbs:сознаться{}, // сознаться в совершении rus_verbs:протекать{}, // протекать в легкой форме rus_verbs:выясняться{}, // выясняться в ходе эксперимента rus_verbs:скрестить{}, // скрестить в неволе rus_verbs:наводить{}, // наводить в комнате порядок rus_verbs:значиться{}, // значиться в документах rus_verbs:заинтересовать{}, // заинтересовать в получении результатов rus_verbs:познакомить{}, // познакомить в непринужденной обстановке rus_verbs:рассеяться{}, // рассеяться в воздухе rus_verbs:грохнуть{}, // грохнуть в подвале rus_verbs:обвинять{}, // обвинять в вымогательстве rus_verbs:столпиться{}, // столпиться в фойе rus_verbs:порыться{}, // порыться в сумке rus_verbs:ослабить{}, // ослабить в верхней части rus_verbs:обнаруживаться{}, // обнаруживаться в кармане куртки rus_verbs:спастись{}, // спастись в хижине rus_verbs:прерваться{}, // прерваться в середине фразы rus_verbs:применять{}, // применять в повседневной работе rus_verbs:строиться{}, // строиться в зоне отчуждения rus_verbs:путешествовать{}, // путешествовать в самолете rus_verbs:побеждать{}, // побеждать в честной битве rus_verbs:погубить{}, // погубить в себе артиста rus_verbs:рассматриваться{}, // рассматриваться в следующей главе rus_verbs:продаваться{}, // продаваться в специализированном магазине rus_verbs:разместиться{}, // разместиться в аудитории rus_verbs:повидать{}, // повидать в жизни rus_verbs:настигнуть{}, // настигнуть в пригородах rus_verbs:сгрудиться{}, // сгрудиться в центре загона rus_verbs:укрыться{}, // укрыться в доме rus_verbs:расплакаться{}, // расплакаться в суде rus_verbs:пролежать{}, // пролежать в канаве rus_verbs:замерзнуть{}, // замерзнуть в ледяной воде rus_verbs:поскользнуться{}, // поскользнуться в коридоре rus_verbs:таскать{}, // таскать в руках rus_verbs:нападать{}, // нападать в вольере rus_verbs:просматривать{}, // просматривать в браузере rus_verbs:обдумать{}, // обдумать в дороге rus_verbs:обвинить{}, // обвинить в измене rus_verbs:останавливать{}, // останавливать в дверях rus_verbs:теряться{}, // теряться в догадках rus_verbs:погибать{}, // погибать в бою rus_verbs:обозначать{}, // обозначать в списке rus_verbs:запрещать{}, // запрещать в парке rus_verbs:долететь{}, // долететь в вертолёте rus_verbs:тесниться{}, // тесниться в каморке rus_verbs:уменьшаться{}, // уменьшаться в размере rus_verbs:издавать{}, // издавать в небольшом издательстве rus_verbs:хоронить{}, // хоронить в море rus_verbs:перемениться{}, // перемениться в лице rus_verbs:установиться{}, // установиться в северных областях rus_verbs:прикидывать{}, // прикидывать в уме rus_verbs:затаиться{}, // затаиться в траве rus_verbs:раздобыть{}, // раздобыть в аптеке rus_verbs:перебросить{}, // перебросить в товарном составе rus_verbs:погружаться{}, // погружаться в батискафе rus_verbs:поживать{}, // поживать в одиночестве rus_verbs:признаваться{}, // признаваться в любви rus_verbs:захватывать{}, // захватывать в здании rus_verbs:покачиваться{}, // покачиваться в лодке rus_verbs:крутиться{}, // крутиться в колесе rus_verbs:помещаться{}, // помещаться в ящике rus_verbs:питаться{}, // питаться в столовой rus_verbs:отдохнуть{}, // отдохнуть в пансионате rus_verbs:кататься{}, // кататься в коляске rus_verbs:поработать{}, // поработать в цеху rus_verbs:подразумевать{}, // подразумевать в задании rus_verbs:ограбить{}, // ограбить в подворотне rus_verbs:преуспеть{}, // преуспеть в бизнесе rus_verbs:заерзать{}, // заерзать в кресле rus_verbs:разъяснить{}, // разъяснить в другой статье rus_verbs:продвинуться{}, // продвинуться в изучении rus_verbs:поколебаться{}, // поколебаться в начале rus_verbs:засомневаться{}, // засомневаться в честности rus_verbs:приникнуть{}, // приникнуть в уме rus_verbs:скривить{}, // скривить в усмешке rus_verbs:рассечь{}, // рассечь в центре опухоли rus_verbs:перепутать{}, // перепутать в роддоме rus_verbs:посмеяться{}, // посмеяться в перерыве rus_verbs:отмечаться{}, // отмечаться в полицейском участке rus_verbs:накопиться{}, // накопиться в отстойнике rus_verbs:уносить{}, // уносить в руках rus_verbs:навещать{}, // навещать в больнице rus_verbs:остыть{}, // остыть в проточной воде rus_verbs:запереться{}, // запереться в комнате rus_verbs:обогнать{}, // обогнать в первом круге rus_verbs:убеждаться{}, // убеждаться в неизбежности rus_verbs:подбирать{}, // подбирать в магазине rus_verbs:уничтожать{}, // уничтожать в полете rus_verbs:путаться{}, // путаться в показаниях rus_verbs:притаиться{}, // притаиться в темноте rus_verbs:проплывать{}, // проплывать в лодке rus_verbs:засесть{}, // засесть в окопе rus_verbs:подцепить{}, // подцепить в баре rus_verbs:насчитать{}, // насчитать в диктанте несколько ошибок rus_verbs:оправдаться{}, // оправдаться в суде rus_verbs:созреть{}, // созреть в естественных условиях rus_verbs:раскрываться{}, // раскрываться в подходящих условиях rus_verbs:ожидаться{}, // ожидаться в верхней части rus_verbs:одеваться{}, // одеваться в дорогих бутиках rus_verbs:упрекнуть{}, // упрекнуть в недостатке опыта rus_verbs:грабить{}, // грабить в подворотне rus_verbs:ужинать{}, // ужинать в ресторане rus_verbs:гонять{}, // гонять в жилах rus_verbs:уверить{}, // уверить в безопасности rus_verbs:потеряться{}, // потеряться в лесу rus_verbs:устанавливаться{}, // устанавливаться в комнате rus_verbs:предоставлять{}, // предоставлять в суде rus_verbs:протянуться{}, // протянуться в стене rus_verbs:допрашивать{}, // допрашивать в бункере rus_verbs:проработать{}, // проработать в кабинете rus_verbs:сосредоточить{}, // сосредоточить в своих руках rus_verbs:утвердить{}, // утвердить в должности rus_verbs:сочинять{}, // сочинять в дороге rus_verbs:померкнуть{}, // померкнуть в глазах rus_verbs:показываться{}, // показываться в окошке rus_verbs:похудеть{}, // похудеть в талии rus_verbs:проделывать{}, // проделывать в стене rus_verbs:прославиться{}, // прославиться в интернете rus_verbs:сдохнуть{}, // сдохнуть в нищете rus_verbs:раскинуться{}, // раскинуться в степи rus_verbs:развить{}, // развить в себе способности rus_verbs:уставать{}, // уставать в цеху rus_verbs:укрепить{}, // укрепить в земле rus_verbs:числиться{}, // числиться в списке rus_verbs:образовывать{}, // образовывать в смеси rus_verbs:екнуть{}, // екнуть в груди rus_verbs:одобрять{}, // одобрять в своей речи rus_verbs:запить{}, // запить в одиночестве rus_verbs:забыться{}, // забыться в тяжелом сне rus_verbs:чернеть{}, // чернеть в кислой среде rus_verbs:размещаться{}, // размещаться в гараже rus_verbs:соорудить{}, // соорудить в гараже rus_verbs:развивать{}, // развивать в себе rus_verbs:пастись{}, // пастись в пойме rus_verbs:формироваться{}, // формироваться в верхних слоях атмосферы rus_verbs:ослабнуть{}, // ослабнуть в сочленении rus_verbs:таить{}, // таить в себе инфинитив:пробегать{ вид:несоверш }, глагол:пробегать{ вид:несоверш }, // пробегать в спешке rus_verbs:приостановиться{}, // приостановиться в конце rus_verbs:топтаться{}, // топтаться в грязи rus_verbs:громить{}, // громить в финале rus_verbs:заменять{}, // заменять в основном составе rus_verbs:подъезжать{}, // подъезжать в колясках rus_verbs:вычислить{}, // вычислить в уме rus_verbs:заказывать{}, // заказывать в магазине rus_verbs:осуществить{}, // осуществить в реальных условиях rus_verbs:обосноваться{}, // обосноваться в дупле rus_verbs:пытать{}, // пытать в камере rus_verbs:поменять{}, // поменять в магазине rus_verbs:совершиться{}, // совершиться в суде rus_verbs:пролетать{}, // пролетать в вертолете rus_verbs:сбыться{}, // сбыться во сне rus_verbs:разговориться{}, // разговориться в отделении rus_verbs:преподнести{}, // преподнести в красивой упаковке rus_verbs:напечатать{}, // напечатать в типографии rus_verbs:прорвать{}, // прорвать в центре rus_verbs:раскачиваться{}, // раскачиваться в кресле rus_verbs:задерживаться{}, // задерживаться в дверях rus_verbs:угощать{}, // угощать в кафе rus_verbs:проступать{}, // проступать в глубине rus_verbs:шарить{}, // шарить в математике rus_verbs:увеличивать{}, // увеличивать в конце rus_verbs:расцвести{}, // расцвести в оранжерее rus_verbs:закипеть{}, // закипеть в баке rus_verbs:подлететь{}, // подлететь в вертолете rus_verbs:рыться{}, // рыться в куче rus_verbs:пожить{}, // пожить в гостинице rus_verbs:добираться{}, // добираться в попутном транспорте rus_verbs:перекрыть{}, // перекрыть в коридоре rus_verbs:продержаться{}, // продержаться в барокамере rus_verbs:разыскивать{}, // разыскивать в толпе rus_verbs:освобождать{}, // освобождать в зале суда rus_verbs:подметить{}, // подметить в человеке rus_verbs:передвигаться{}, // передвигаться в узкой юбке rus_verbs:продумать{}, // продумать в уме rus_verbs:извиваться{}, // извиваться в траве rus_verbs:процитировать{}, // процитировать в статье rus_verbs:прогуливаться{}, // прогуливаться в парке rus_verbs:защемить{}, // защемить в двери rus_verbs:увеличиться{}, // увеличиться в объеме rus_verbs:проявиться{}, // проявиться в результатах rus_verbs:заскользить{}, // заскользить в ботинках rus_verbs:пересказать{}, // пересказать в своем выступлении rus_verbs:протестовать{}, // протестовать в здании парламента rus_verbs:указываться{}, // указываться в путеводителе rus_verbs:копошиться{}, // копошиться в песке rus_verbs:проигнорировать{}, // проигнорировать в своей работе rus_verbs:купаться{}, // купаться в речке rus_verbs:подсчитать{}, // подсчитать в уме rus_verbs:разволноваться{}, // разволноваться в классе rus_verbs:придумывать{}, // придумывать в своем воображении rus_verbs:предусмотреть{}, // предусмотреть в программе rus_verbs:завертеться{}, // завертеться в колесе rus_verbs:зачерпнуть{}, // зачерпнуть в ручье rus_verbs:очистить{}, // очистить в химической лаборатории rus_verbs:прозвенеть{}, // прозвенеть в коридорах rus_verbs:уменьшиться{}, // уменьшиться в размере rus_verbs:колыхаться{}, // колыхаться в проточной воде rus_verbs:ознакомиться{}, // ознакомиться в автобусе rus_verbs:ржать{}, // ржать в аудитории rus_verbs:раскинуть{}, // раскинуть в микрорайоне rus_verbs:разлиться{}, // разлиться в воде rus_verbs:сквозить{}, // сквозить в словах rus_verbs:задушить{}, // задушить в объятиях rus_verbs:осудить{}, // осудить в особом порядке rus_verbs:разгромить{}, // разгромить в честном поединке rus_verbs:подслушать{}, // подслушать в кулуарах rus_verbs:проповедовать{}, // проповедовать в сельских районах rus_verbs:озарить{}, // озарить во сне rus_verbs:потирать{}, // потирать в предвкушении rus_verbs:описываться{}, // описываться в статье rus_verbs:качаться{}, // качаться в кроватке rus_verbs:усилить{}, // усилить в центре rus_verbs:прохаживаться{}, // прохаживаться в новом костюме rus_verbs:полечить{}, // полечить в больничке rus_verbs:сниматься{}, // сниматься в римейке rus_verbs:сыскать{}, // сыскать в наших краях rus_verbs:поприветствовать{}, // поприветствовать в коридоре rus_verbs:подтвердиться{}, // подтвердиться в эксперименте rus_verbs:плескаться{}, // плескаться в теплой водичке rus_verbs:расширяться{}, // расширяться в первом сегменте rus_verbs:мерещиться{}, // мерещиться в тумане rus_verbs:сгущаться{}, // сгущаться в воздухе rus_verbs:храпеть{}, // храпеть во сне rus_verbs:подержать{}, // подержать в руках rus_verbs:накинуться{}, // накинуться в подворотне rus_verbs:планироваться{}, // планироваться в закрытом режиме rus_verbs:пробудить{}, // пробудить в себе rus_verbs:побриться{}, // побриться в ванной rus_verbs:сгинуть{}, // сгинуть в пучине rus_verbs:окрестить{}, // окрестить в церкви инфинитив:резюмировать{ вид:соверш }, глагол:резюмировать{ вид:соверш }, // резюмировать в конце выступления rus_verbs:замкнуться{}, // замкнуться в себе rus_verbs:прибавлять{}, // прибавлять в весе rus_verbs:проплыть{}, // проплыть в лодке rus_verbs:растворяться{}, // растворяться в тумане rus_verbs:упрекать{}, // упрекать в небрежности rus_verbs:затеряться{}, // затеряться в лабиринте rus_verbs:перечитывать{}, // перечитывать в поезде rus_verbs:перелететь{}, // перелететь в вертолете rus_verbs:оживать{}, // оживать в теплой воде rus_verbs:заглохнуть{}, // заглохнуть в полете rus_verbs:кольнуть{}, // кольнуть в боку rus_verbs:копаться{}, // копаться в куче rus_verbs:развлекаться{}, // развлекаться в клубе rus_verbs:отливать{}, // отливать в кустах rus_verbs:зажить{}, // зажить в деревне rus_verbs:одолжить{}, // одолжить в соседнем кабинете rus_verbs:заклинать{}, // заклинать в своей речи rus_verbs:различаться{}, // различаться в мелочах rus_verbs:печататься{}, // печататься в типографии rus_verbs:угадываться{}, // угадываться в контурах rus_verbs:обрывать{}, // обрывать в начале rus_verbs:поглаживать{}, // поглаживать в кармане rus_verbs:подписывать{}, // подписывать в присутствии понятых rus_verbs:добывать{}, // добывать в разломе rus_verbs:скопиться{}, // скопиться в воротах rus_verbs:повстречать{}, // повстречать в бане rus_verbs:совпасть{}, // совпасть в упрощенном виде rus_verbs:разрываться{}, // разрываться в точке спайки rus_verbs:улавливать{}, // улавливать в датчике rus_verbs:повстречаться{}, // повстречаться в лифте rus_verbs:отразить{}, // отразить в отчете rus_verbs:пояснять{}, // пояснять в примечаниях rus_verbs:накормить{}, // накормить в столовке rus_verbs:поужинать{}, // поужинать в ресторане инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть в суде инфинитив:спеть{ вид:несоверш }, глагол:спеть{ вид:несоверш }, rus_verbs:топить{}, // топить в молоке rus_verbs:освоить{}, // освоить в работе rus_verbs:зародиться{}, // зародиться в голове rus_verbs:отплыть{}, // отплыть в старой лодке rus_verbs:отстаивать{}, // отстаивать в суде rus_verbs:осуждать{}, // осуждать в своем выступлении rus_verbs:переговорить{}, // переговорить в перерыве rus_verbs:разгораться{}, // разгораться в сердце rus_verbs:укрыть{}, // укрыть в шалаше rus_verbs:томиться{}, // томиться в застенках rus_verbs:клубиться{}, // клубиться в воздухе rus_verbs:сжигать{}, // сжигать в топке rus_verbs:позавтракать{}, // позавтракать в кафешке rus_verbs:функционировать{}, // функционировать в лабораторных условиях rus_verbs:смять{}, // смять в руке rus_verbs:разместить{}, // разместить в интернете rus_verbs:пронести{}, // пронести в потайном кармане rus_verbs:руководствоваться{}, // руководствоваться в работе rus_verbs:нашарить{}, // нашарить в потемках rus_verbs:закрутить{}, // закрутить в вихре rus_verbs:просматриваться{}, // просматриваться в дальней перспективе rus_verbs:распознать{}, // распознать в незнакомце rus_verbs:повеситься{}, // повеситься в камере rus_verbs:обшарить{}, // обшарить в поисках наркотиков rus_verbs:наполняться{}, // наполняется в карьере rus_verbs:засвистеть{}, // засвистеть в воздухе rus_verbs:процветать{}, // процветать в мягком климате rus_verbs:шуршать{}, // шуршать в простенке rus_verbs:подхватывать{}, // подхватывать в полете инфинитив:роиться{}, глагол:роиться{}, // роиться в воздухе прилагательное:роившийся{}, прилагательное:роящийся{}, // деепричастие:роясь{ aux stress="ро^ясь" }, rus_verbs:преобладать{}, // преобладать в тексте rus_verbs:посветлеть{}, // посветлеть в лице rus_verbs:игнорировать{}, // игнорировать в рекомендациях rus_verbs:обсуждаться{}, // обсуждаться в кулуарах rus_verbs:отказывать{}, // отказывать в визе rus_verbs:ощупывать{}, // ощупывать в кармане rus_verbs:разливаться{}, // разливаться в цеху rus_verbs:расписаться{}, // расписаться в получении rus_verbs:учинить{}, // учинить в казарме rus_verbs:плестись{}, // плестись в хвосте rus_verbs:объявляться{}, // объявляться в группе rus_verbs:повышаться{}, // повышаться в первой части rus_verbs:напрягать{}, // напрягать в паху rus_verbs:разрабатывать{}, // разрабатывать в студии rus_verbs:хлопотать{}, // хлопотать в мэрии rus_verbs:прерывать{}, // прерывать в самом начале rus_verbs:каяться{}, // каяться в грехах rus_verbs:освоиться{}, // освоиться в кабине rus_verbs:подплыть{}, // подплыть в лодке rus_verbs:замигать{}, // замигать в темноте rus_verbs:оскорблять{}, // оскорблять в выступлении rus_verbs:торжествовать{}, // торжествовать в душе rus_verbs:поправлять{}, // поправлять в прологе rus_verbs:угадывать{}, // угадывать в размытом изображении rus_verbs:потоптаться{}, // потоптаться в прихожей rus_verbs:переправиться{}, // переправиться в лодочке rus_verbs:увериться{}, // увериться в невиновности rus_verbs:забрезжить{}, // забрезжить в конце тоннеля rus_verbs:утвердиться{}, // утвердиться во мнении rus_verbs:завывать{}, // завывать в трубе rus_verbs:заварить{}, // заварить в заварнике rus_verbs:скомкать{}, // скомкать в руке rus_verbs:перемещаться{}, // перемещаться в капсуле инфинитив:писаться{ aux stress="пис^аться" }, глагол:писаться{ aux stress="пис^аться" }, // писаться в первом поле rus_verbs:праздновать{}, // праздновать в баре rus_verbs:мигать{}, // мигать в темноте rus_verbs:обучить{}, // обучить в мастерской rus_verbs:орудовать{}, // орудовать в кладовке rus_verbs:упорствовать{}, // упорствовать в заблуждении rus_verbs:переминаться{}, // переминаться в прихожей rus_verbs:подрасти{}, // подрасти в теплице rus_verbs:предписываться{}, // предписываться в законе rus_verbs:приписать{}, // приписать в конце rus_verbs:задаваться{}, // задаваться в своей статье rus_verbs:чинить{}, // чинить в домашних условиях rus_verbs:раздеваться{}, // раздеваться в пляжной кабинке rus_verbs:пообедать{}, // пообедать в ресторанчике rus_verbs:жрать{}, // жрать в чуланчике rus_verbs:исполняться{}, // исполняться в антракте rus_verbs:гнить{}, // гнить в тюрьме rus_verbs:глодать{}, // глодать в конуре rus_verbs:прослушать{}, // прослушать в дороге rus_verbs:истратить{}, // истратить в кабаке rus_verbs:стареть{}, // стареть в одиночестве rus_verbs:разжечь{}, // разжечь в сердце rus_verbs:совещаться{}, // совещаться в кабинете rus_verbs:покачивать{}, // покачивать в кроватке rus_verbs:отсидеть{}, // отсидеть в одиночке rus_verbs:формировать{}, // формировать в умах rus_verbs:захрапеть{}, // захрапеть во сне rus_verbs:петься{}, // петься в хоре rus_verbs:объехать{}, // объехать в автобусе rus_verbs:поселить{}, // поселить в гостинице rus_verbs:предаться{}, // предаться в книге rus_verbs:заворочаться{}, // заворочаться во сне rus_verbs:напрятать{}, // напрятать в карманах rus_verbs:очухаться{}, // очухаться в незнакомом месте rus_verbs:ограничивать{}, // ограничивать в движениях rus_verbs:завертеть{}, // завертеть в руках rus_verbs:печатать{}, // печатать в редакторе rus_verbs:теплиться{}, // теплиться в сердце rus_verbs:увязнуть{}, // увязнуть в зыбучем песке rus_verbs:усмотреть{}, // усмотреть в обращении rus_verbs:отыскаться{}, // отыскаться в запасах rus_verbs:потушить{}, // потушить в горле огонь rus_verbs:поубавиться{}, // поубавиться в размере rus_verbs:зафиксировать{}, // зафиксировать в постоянной памяти rus_verbs:смыть{}, // смыть в ванной rus_verbs:заместить{}, // заместить в кресле rus_verbs:угасать{}, // угасать в одиночестве rus_verbs:сразить{}, // сразить в споре rus_verbs:фигурировать{}, // фигурировать в бюллетене rus_verbs:расплываться{}, // расплываться в глазах rus_verbs:сосчитать{}, // сосчитать в уме rus_verbs:сгуститься{}, // сгуститься в воздухе rus_verbs:цитировать{}, // цитировать в своей статье rus_verbs:помяться{}, // помяться в давке rus_verbs:затрагивать{}, // затрагивать в процессе выполнения rus_verbs:обтереть{}, // обтереть в гараже rus_verbs:подстрелить{}, // подстрелить в пойме реки rus_verbs:растереть{}, // растереть в руке rus_verbs:подавлять{}, // подавлять в зародыше rus_verbs:смешиваться{}, // смешиваться в чане инфинитив:вычитать{ вид:соверш }, глагол:вычитать{ вид:соверш }, // вычитать в книжечке rus_verbs:сократиться{}, // сократиться в обхвате rus_verbs:занервничать{}, // занервничать в кабинете rus_verbs:соприкоснуться{}, // соприкоснуться в полете rus_verbs:обозначить{}, // обозначить в объявлении rus_verbs:обучаться{}, // обучаться в училище rus_verbs:снизиться{}, // снизиться в нижних слоях атмосферы rus_verbs:лелеять{}, // лелеять в сердце rus_verbs:поддерживаться{}, // поддерживаться в суде rus_verbs:уплыть{}, // уплыть в лодочке rus_verbs:резвиться{}, // резвиться в саду rus_verbs:поерзать{}, // поерзать в гамаке rus_verbs:оплатить{}, // оплатить в ресторане rus_verbs:похвастаться{}, // похвастаться в компании rus_verbs:знакомиться{}, // знакомиться в классе rus_verbs:приплыть{}, // приплыть в подводной лодке rus_verbs:зажигать{}, // зажигать в классе rus_verbs:смыслить{}, // смыслить в математике rus_verbs:закопать{}, // закопать в огороде rus_verbs:порхать{}, // порхать в зарослях rus_verbs:потонуть{}, // потонуть в бумажках rus_verbs:стирать{}, // стирать в холодной воде rus_verbs:подстерегать{}, // подстерегать в придорожных кустах rus_verbs:погулять{}, // погулять в парке rus_verbs:предвкушать{}, // предвкушать в воображении rus_verbs:ошеломить{}, // ошеломить в бою rus_verbs:удостовериться{}, // удостовериться в безопасности rus_verbs:огласить{}, // огласить в заключительной части rus_verbs:разбогатеть{}, // разбогатеть в деревне rus_verbs:грохотать{}, // грохотать в мастерской rus_verbs:реализоваться{}, // реализоваться в должности rus_verbs:красть{}, // красть в магазине rus_verbs:нарваться{}, // нарваться в коридоре rus_verbs:застывать{}, // застывать в неудобной позе rus_verbs:толкаться{}, // толкаться в тесной комнате rus_verbs:извлекать{}, // извлекать в аппарате rus_verbs:обжигать{}, // обжигать в печи rus_verbs:запечатлеть{}, // запечатлеть в кинохронике rus_verbs:тренироваться{}, // тренироваться в зале rus_verbs:поспорить{}, // поспорить в кабинете rus_verbs:рыскать{}, // рыскать в лесу rus_verbs:надрываться{}, // надрываться в шахте rus_verbs:сняться{}, // сняться в фильме rus_verbs:закружить{}, // закружить в танце rus_verbs:затонуть{}, // затонуть в порту rus_verbs:побыть{}, // побыть в гостях rus_verbs:почистить{}, // почистить в носу rus_verbs:сгорбиться{}, // сгорбиться в тесной конуре rus_verbs:подслушивать{}, // подслушивать в классе rus_verbs:сгорать{}, // сгорать в танке rus_verbs:разочароваться{}, // разочароваться в артисте инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать в кустиках rus_verbs:мять{}, // мять в руках rus_verbs:подраться{}, // подраться в классе rus_verbs:замести{}, // замести в прихожей rus_verbs:откладываться{}, // откладываться в печени rus_verbs:обозначаться{}, // обозначаться в перечне rus_verbs:просиживать{}, // просиживать в интернете rus_verbs:соприкасаться{}, // соприкасаться в точке rus_verbs:начертить{}, // начертить в тетрадке rus_verbs:уменьшать{}, // уменьшать в поперечнике rus_verbs:тормозить{}, // тормозить в облаке rus_verbs:затевать{}, // затевать в лаборатории rus_verbs:затопить{}, // затопить в бухте rus_verbs:задерживать{}, // задерживать в лифте rus_verbs:прогуляться{}, // прогуляться в лесу rus_verbs:прорубить{}, // прорубить во льду rus_verbs:очищать{}, // очищать в кислоте rus_verbs:полулежать{}, // полулежать в гамаке rus_verbs:исправить{}, // исправить в задании rus_verbs:предусматриваться{}, // предусматриваться в постановке задачи rus_verbs:замучить{}, // замучить в плену rus_verbs:разрушаться{}, // разрушаться в верхней части rus_verbs:ерзать{}, // ерзать в кресле rus_verbs:покопаться{}, // покопаться в залежах rus_verbs:раскаяться{}, // раскаяться в содеянном rus_verbs:пробежаться{}, // пробежаться в парке rus_verbs:полежать{}, // полежать в гамаке rus_verbs:позаимствовать{}, // позаимствовать в книге rus_verbs:снижать{}, // снижать в несколько раз rus_verbs:черпать{}, // черпать в поэзии rus_verbs:заверять{}, // заверять в своей искренности rus_verbs:проглядеть{}, // проглядеть в сумерках rus_verbs:припарковать{}, // припарковать во дворе rus_verbs:сверлить{}, // сверлить в стене rus_verbs:здороваться{}, // здороваться в аудитории rus_verbs:рожать{}, // рожать в воде rus_verbs:нацарапать{}, // нацарапать в тетрадке rus_verbs:затопать{}, // затопать в коридоре rus_verbs:прописать{}, // прописать в правилах rus_verbs:сориентироваться{}, // сориентироваться в обстоятельствах rus_verbs:снизить{}, // снизить в несколько раз rus_verbs:заблуждаться{}, // заблуждаться в своей теории rus_verbs:откопать{}, // откопать в отвалах rus_verbs:смастерить{}, // смастерить в лаборатории rus_verbs:замедлиться{}, // замедлиться в парафине rus_verbs:избивать{}, // избивать в участке rus_verbs:мыться{}, // мыться в бане rus_verbs:сварить{}, // сварить в кастрюльке rus_verbs:раскопать{}, // раскопать в снегу rus_verbs:крепиться{}, // крепиться в держателе rus_verbs:дробить{}, // дробить в мельнице rus_verbs:попить{}, // попить в ресторанчике rus_verbs:затронуть{}, // затронуть в душе rus_verbs:лязгнуть{}, // лязгнуть в тишине rus_verbs:заправлять{}, // заправлять в полете rus_verbs:размножаться{}, // размножаться в неволе rus_verbs:потопить{}, // потопить в Тихом Океане rus_verbs:кушать{}, // кушать в столовой rus_verbs:замолкать{}, // замолкать в замешательстве rus_verbs:измеряться{}, // измеряться в дюймах rus_verbs:сбываться{}, // сбываться в мечтах rus_verbs:задернуть{}, // задернуть в комнате rus_verbs:затихать{}, // затихать в темноте rus_verbs:прослеживаться{}, // прослеживается в журнале rus_verbs:прерываться{}, // прерывается в начале rus_verbs:изображаться{}, // изображается в любых фильмах rus_verbs:фиксировать{}, // фиксировать в данной точке rus_verbs:ослаблять{}, // ослаблять в поясе rus_verbs:зреть{}, // зреть в теплице rus_verbs:зеленеть{}, // зеленеть в огороде rus_verbs:критиковать{}, // критиковать в статье rus_verbs:облететь{}, // облететь в частном вертолете rus_verbs:разбросать{}, // разбросать в комнате rus_verbs:заразиться{}, // заразиться в людном месте rus_verbs:рассеять{}, // рассеять в бою rus_verbs:печься{}, // печься в духовке rus_verbs:поспать{}, // поспать в палатке rus_verbs:заступиться{}, // заступиться в драке rus_verbs:сплетаться{}, // сплетаться в середине rus_verbs:поместиться{}, // поместиться в мешке rus_verbs:спереть{}, // спереть в лавке // инфинитив:ликвидировать{ вид:несоверш }, глагол:ликвидировать{ вид:несоверш }, // ликвидировать в пригороде // инфинитив:ликвидировать{ вид:соверш }, глагол:ликвидировать{ вид:соверш }, rus_verbs:проваляться{}, // проваляться в постели rus_verbs:лечиться{}, // лечиться в стационаре rus_verbs:определиться{}, // определиться в честном бою rus_verbs:обработать{}, // обработать в растворе rus_verbs:пробивать{}, // пробивать в стене rus_verbs:перемешаться{}, // перемешаться в чане rus_verbs:чесать{}, // чесать в паху rus_verbs:пролечь{}, // пролечь в пустынной местности rus_verbs:скитаться{}, // скитаться в дальних странах rus_verbs:затрудняться{}, // затрудняться в выборе rus_verbs:отряхнуться{}, // отряхнуться в коридоре rus_verbs:разыгрываться{}, // разыгрываться в лотерее rus_verbs:помолиться{}, // помолиться в церкви rus_verbs:предписывать{}, // предписывать в рецепте rus_verbs:порваться{}, // порваться в слабом месте rus_verbs:греться{}, // греться в здании rus_verbs:опровергать{}, // опровергать в своем выступлении rus_verbs:помянуть{}, // помянуть в своем выступлении rus_verbs:допросить{}, // допросить в прокуратуре rus_verbs:материализоваться{}, // материализоваться в соседнем здании rus_verbs:рассеиваться{}, // рассеиваться в воздухе rus_verbs:перевозить{}, // перевозить в вагоне rus_verbs:отбывать{}, // отбывать в тюрьме rus_verbs:попахивать{}, // попахивать в отхожем месте rus_verbs:перечислять{}, // перечислять в заключении rus_verbs:зарождаться{}, // зарождаться в дебрях rus_verbs:предъявлять{}, // предъявлять в своем письме rus_verbs:распространять{}, // распространять в сети rus_verbs:пировать{}, // пировать в соседнем селе rus_verbs:начертать{}, // начертать в летописи rus_verbs:расцветать{}, // расцветать в подходящих условиях rus_verbs:царствовать{}, // царствовать в южной части материка rus_verbs:накопить{}, // накопить в буфере rus_verbs:закрутиться{}, // закрутиться в рутине rus_verbs:отработать{}, // отработать в забое rus_verbs:обокрасть{}, // обокрасть в автобусе rus_verbs:прокладывать{}, // прокладывать в снегу rus_verbs:ковырять{}, // ковырять в носу rus_verbs:копить{}, // копить в очереди rus_verbs:полечь{}, // полечь в степях rus_verbs:щебетать{}, // щебетать в кустиках rus_verbs:подчеркиваться{}, // подчеркиваться в сообщении rus_verbs:посеять{}, // посеять в огороде rus_verbs:разъезжать{}, // разъезжать в кабриолете rus_verbs:замечаться{}, // замечаться в лесу rus_verbs:просчитать{}, // просчитать в уме rus_verbs:маяться{}, // маяться в командировке rus_verbs:выхватывать{}, // выхватывать в тексте rus_verbs:креститься{}, // креститься в деревенской часовне rus_verbs:обрабатывать{}, // обрабатывать в растворе кислоты rus_verbs:настигать{}, // настигать в огороде rus_verbs:разгуливать{}, // разгуливать в роще rus_verbs:насиловать{}, // насиловать в квартире rus_verbs:побороть{}, // побороть в себе rus_verbs:учитывать{}, // учитывать в расчетах rus_verbs:искажать{}, // искажать в заметке rus_verbs:пропить{}, // пропить в кабаке rus_verbs:катать{}, // катать в лодочке rus_verbs:припрятать{}, // припрятать в кармашке rus_verbs:запаниковать{}, // запаниковать в бою rus_verbs:рассыпать{}, // рассыпать в траве rus_verbs:застревать{}, // застревать в ограде rus_verbs:зажигаться{}, // зажигаться в сумерках rus_verbs:жарить{}, // жарить в масле rus_verbs:накапливаться{}, // накапливаться в костях rus_verbs:распуститься{}, // распуститься в горшке rus_verbs:проголосовать{}, // проголосовать в передвижном пункте rus_verbs:странствовать{}, // странствовать в автомобиле rus_verbs:осматриваться{}, // осматриваться в хоромах rus_verbs:разворачивать{}, // разворачивать в спортзале rus_verbs:заскучать{}, // заскучать в самолете rus_verbs:напутать{}, // напутать в расчете rus_verbs:перекусить{}, // перекусить в столовой rus_verbs:спасаться{}, // спасаться в автономной капсуле rus_verbs:посовещаться{}, // посовещаться в комнате rus_verbs:доказываться{}, // доказываться в статье rus_verbs:познаваться{}, // познаваться в беде rus_verbs:загрустить{}, // загрустить в одиночестве rus_verbs:оживить{}, // оживить в памяти rus_verbs:переворачиваться{}, // переворачиваться в гробу rus_verbs:заприметить{}, // заприметить в лесу rus_verbs:отравиться{}, // отравиться в забегаловке rus_verbs:продержать{}, // продержать в клетке rus_verbs:выявить{}, // выявить в костях rus_verbs:заседать{}, // заседать в совете rus_verbs:расплачиваться{}, // расплачиваться в первой кассе rus_verbs:проломить{}, // проломить в двери rus_verbs:подражать{}, // подражать в мелочах rus_verbs:подсчитывать{}, // подсчитывать в уме rus_verbs:опережать{}, // опережать во всем rus_verbs:сформироваться{}, // сформироваться в облаке rus_verbs:укрепиться{}, // укрепиться в мнении rus_verbs:отстоять{}, // отстоять в очереди rus_verbs:развертываться{}, // развертываться в месте испытания rus_verbs:замерзать{}, // замерзать во льду rus_verbs:утопать{}, // утопать в снегу rus_verbs:раскаиваться{}, // раскаиваться в содеянном rus_verbs:организовывать{}, // организовывать в пионерлагере rus_verbs:перевестись{}, // перевестись в наших краях rus_verbs:смешивать{}, // смешивать в блендере rus_verbs:ютиться{}, // ютиться в тесной каморке rus_verbs:прождать{}, // прождать в аудитории rus_verbs:подыскивать{}, // подыскивать в женском общежитии rus_verbs:замочить{}, // замочить в сортире rus_verbs:мерзнуть{}, // мерзнуть в тонкой курточке rus_verbs:растирать{}, // растирать в ступке rus_verbs:замедлять{}, // замедлять в парафине rus_verbs:переспать{}, // переспать в палатке rus_verbs:рассекать{}, // рассекать в кабриолете rus_verbs:отыскивать{}, // отыскивать в залежах rus_verbs:опровергнуть{}, // опровергнуть в своем выступлении rus_verbs:дрыхнуть{}, // дрыхнуть в гамаке rus_verbs:укрываться{}, // укрываться в землянке rus_verbs:запечься{}, // запечься в золе rus_verbs:догорать{}, // догорать в темноте rus_verbs:застилать{}, // застилать в коридоре rus_verbs:сыскаться{}, // сыскаться в деревне rus_verbs:переделать{}, // переделать в мастерской rus_verbs:разъяснять{}, // разъяснять в своей лекции rus_verbs:селиться{}, // селиться в центре rus_verbs:оплачивать{}, // оплачивать в магазине rus_verbs:переворачивать{}, // переворачивать в закрытой банке rus_verbs:упражняться{}, // упражняться в остроумии rus_verbs:пометить{}, // пометить в списке rus_verbs:припомниться{}, // припомниться в завещании rus_verbs:приютить{}, // приютить в амбаре rus_verbs:натерпеться{}, // натерпеться в темнице rus_verbs:затеваться{}, // затеваться в клубе rus_verbs:уплывать{}, // уплывать в лодке rus_verbs:скиснуть{}, // скиснуть в бидоне rus_verbs:заколоть{}, // заколоть в боку rus_verbs:замерцать{}, // замерцать в темноте rus_verbs:фиксироваться{}, // фиксироваться в протоколе rus_verbs:запираться{}, // запираться в комнате rus_verbs:съезжаться{}, // съезжаться в каретах rus_verbs:толочься{}, // толочься в ступе rus_verbs:потанцевать{}, // потанцевать в клубе rus_verbs:побродить{}, // побродить в парке rus_verbs:назревать{}, // назревать в коллективе rus_verbs:дохнуть{}, // дохнуть в питомнике rus_verbs:крестить{}, // крестить в деревенской церквушке rus_verbs:рассчитаться{}, // рассчитаться в банке rus_verbs:припарковаться{}, // припарковаться во дворе rus_verbs:отхватить{}, // отхватить в магазинчике rus_verbs:остывать{}, // остывать в холодильнике rus_verbs:составляться{}, // составляться в атмосфере тайны rus_verbs:переваривать{}, // переваривать в тишине rus_verbs:хвастать{}, // хвастать в казино rus_verbs:отрабатывать{}, // отрабатывать в теплице rus_verbs:разлечься{}, // разлечься в кровати rus_verbs:прокручивать{}, // прокручивать в голове rus_verbs:очертить{}, // очертить в воздухе rus_verbs:сконфузиться{}, // сконфузиться в окружении незнакомых людей rus_verbs:выявлять{}, // выявлять в боевых условиях rus_verbs:караулить{}, // караулить в лифте rus_verbs:расставлять{}, // расставлять в бойницах rus_verbs:прокрутить{}, // прокрутить в голове rus_verbs:пересказывать{}, // пересказывать в первой главе rus_verbs:задавить{}, // задавить в зародыше rus_verbs:хозяйничать{}, // хозяйничать в холодильнике rus_verbs:хвалиться{}, // хвалиться в детском садике rus_verbs:оперировать{}, // оперировать в полевом госпитале rus_verbs:формулировать{}, // формулировать в следующей главе rus_verbs:застигнуть{}, // застигнуть в неприглядном виде rus_verbs:замурлыкать{}, // замурлыкать в тепле rus_verbs:поддакивать{}, // поддакивать в споре rus_verbs:прочертить{}, // прочертить в воздухе rus_verbs:отменять{}, // отменять в городе коменданский час rus_verbs:колдовать{}, // колдовать в лаборатории rus_verbs:отвозить{}, // отвозить в машине rus_verbs:трахать{}, // трахать в гамаке rus_verbs:повозиться{}, // повозиться в мешке rus_verbs:ремонтировать{}, // ремонтировать в центре rus_verbs:робеть{}, // робеть в гостях rus_verbs:перепробовать{}, // перепробовать в деле инфинитив:реализовать{ вид:соверш }, инфинитив:реализовать{ вид:несоверш }, // реализовать в новой версии глагол:реализовать{ вид:соверш }, глагол:реализовать{ вид:несоверш }, rus_verbs:покаяться{}, // покаяться в церкви rus_verbs:попрыгать{}, // попрыгать в бассейне rus_verbs:умалчивать{}, // умалчивать в своем докладе rus_verbs:ковыряться{}, // ковыряться в старой технике rus_verbs:расписывать{}, // расписывать в деталях rus_verbs:вязнуть{}, // вязнуть в песке rus_verbs:погрязнуть{}, // погрязнуть в скандалах rus_verbs:корениться{}, // корениться в неспособности выполнить поставленную задачу rus_verbs:зажимать{}, // зажимать в углу rus_verbs:стискивать{}, // стискивать в ладонях rus_verbs:практиковаться{}, // практиковаться в приготовлении соуса rus_verbs:израсходовать{}, // израсходовать в полете rus_verbs:клокотать{}, // клокотать в жерле rus_verbs:обвиняться{}, // обвиняться в растрате rus_verbs:уединиться{}, // уединиться в кладовке rus_verbs:подохнуть{}, // подохнуть в болоте rus_verbs:кипятиться{}, // кипятиться в чайнике rus_verbs:уродиться{}, // уродиться в лесу rus_verbs:продолжиться{}, // продолжиться в баре rus_verbs:расшифровать{}, // расшифровать в специальном устройстве rus_verbs:посапывать{}, // посапывать в кровати rus_verbs:скрючиться{}, // скрючиться в мешке rus_verbs:лютовать{}, // лютовать в отдаленных селах rus_verbs:расписать{}, // расписать в статье rus_verbs:публиковаться{}, // публиковаться в научном журнале rus_verbs:зарегистрировать{}, // зарегистрировать в комитете rus_verbs:прожечь{}, // прожечь в листе rus_verbs:переждать{}, // переждать в окопе rus_verbs:публиковать{}, // публиковать в журнале rus_verbs:морщить{}, // морщить в уголках глаз rus_verbs:спиться{}, // спиться в одиночестве rus_verbs:изведать{}, // изведать в гареме rus_verbs:обмануться{}, // обмануться в ожиданиях rus_verbs:сочетать{}, // сочетать в себе rus_verbs:подрабатывать{}, // подрабатывать в магазине rus_verbs:репетировать{}, // репетировать в студии rus_verbs:рябить{}, // рябить в глазах rus_verbs:намочить{}, // намочить в луже rus_verbs:скатать{}, // скатать в руке rus_verbs:одевать{}, // одевать в магазине rus_verbs:испечь{}, // испечь в духовке rus_verbs:сбрить{}, // сбрить в подмышках rus_verbs:зажужжать{}, // зажужжать в ухе rus_verbs:сберечь{}, // сберечь в тайном месте rus_verbs:согреться{}, // согреться в хижине инфинитив:дебютировать{ вид:несоверш }, инфинитив:дебютировать{ вид:соверш }, // дебютировать в спектакле глагол:дебютировать{ вид:несоверш }, глагол:дебютировать{ вид:соверш }, rus_verbs:переплыть{}, // переплыть в лодочке rus_verbs:передохнуть{}, // передохнуть в тени rus_verbs:отсвечивать{}, // отсвечивать в зеркалах rus_verbs:переправляться{}, // переправляться в лодках rus_verbs:накупить{}, // накупить в магазине rus_verbs:проторчать{}, // проторчать в очереди rus_verbs:проскальзывать{}, // проскальзывать в сообщениях rus_verbs:застукать{}, // застукать в солярии rus_verbs:наесть{}, // наесть в отпуске rus_verbs:подвизаться{}, // подвизаться в новом деле rus_verbs:вычистить{}, // вычистить в саду rus_verbs:кормиться{}, // кормиться в лесу rus_verbs:покурить{}, // покурить в саду rus_verbs:понизиться{}, // понизиться в ранге rus_verbs:зимовать{}, // зимовать в избушке rus_verbs:проверяться{}, // проверяться в службе безопасности rus_verbs:подпирать{}, // подпирать в первом забое rus_verbs:кувыркаться{}, // кувыркаться в постели rus_verbs:похрапывать{}, // похрапывать в постели rus_verbs:завязнуть{}, // завязнуть в песке rus_verbs:трактовать{}, // трактовать в исследовательской статье rus_verbs:замедляться{}, // замедляться в тяжелой воде rus_verbs:шастать{}, // шастать в здании rus_verbs:заночевать{}, // заночевать в пути rus_verbs:наметиться{}, // наметиться в исследованиях рака rus_verbs:освежить{}, // освежить в памяти rus_verbs:оспаривать{}, // оспаривать в суде rus_verbs:умещаться{}, // умещаться в ячейке rus_verbs:искупить{}, // искупить в бою rus_verbs:отсиживаться{}, // отсиживаться в тылу rus_verbs:мчать{}, // мчать в кабриолете rus_verbs:обличать{}, // обличать в своем выступлении rus_verbs:сгнить{}, // сгнить в тюряге rus_verbs:опробовать{}, // опробовать в деле rus_verbs:тренировать{}, // тренировать в зале rus_verbs:прославить{}, // прославить в академии rus_verbs:учитываться{}, // учитываться в дипломной работе rus_verbs:повеселиться{}, // повеселиться в лагере rus_verbs:поумнеть{}, // поумнеть в карцере rus_verbs:перестрелять{}, // перестрелять в воздухе rus_verbs:проведать{}, // проведать в больнице rus_verbs:измучиться{}, // измучиться в деревне rus_verbs:прощупать{}, // прощупать в глубине rus_verbs:изготовлять{}, // изготовлять в сарае rus_verbs:свирепствовать{}, // свирепствовать в популяции rus_verbs:иссякать{}, // иссякать в источнике rus_verbs:гнездиться{}, // гнездиться в дупле rus_verbs:разогнаться{}, // разогнаться в спортивной машине rus_verbs:опознавать{}, // опознавать в неизвестном rus_verbs:засвидетельствовать{}, // засвидетельствовать в суде rus_verbs:сконцентрировать{}, // сконцентрировать в своих руках rus_verbs:редактировать{}, // редактировать в редакторе rus_verbs:покупаться{}, // покупаться в магазине rus_verbs:промышлять{}, // промышлять в роще rus_verbs:растягиваться{}, // растягиваться в коридоре rus_verbs:приобретаться{}, // приобретаться в антикварных лавках инфинитив:подрезать{ вид:несоверш }, инфинитив:подрезать{ вид:соверш }, // подрезать в воде глагол:подрезать{ вид:несоверш }, глагол:подрезать{ вид:соверш }, rus_verbs:запечатлеться{}, // запечатлеться в мозгу rus_verbs:укрывать{}, // укрывать в подвале rus_verbs:закрепиться{}, // закрепиться в первой башне rus_verbs:освежать{}, // освежать в памяти rus_verbs:громыхать{}, // громыхать в ванной инфинитив:подвигаться{ вид:соверш }, инфинитив:подвигаться{ вид:несоверш }, // подвигаться в кровати глагол:подвигаться{ вид:соверш }, глагол:подвигаться{ вид:несоверш }, rus_verbs:добываться{}, // добываться в шахтах rus_verbs:растворить{}, // растворить в кислоте rus_verbs:приплясывать{}, // приплясывать в гримерке rus_verbs:доживать{}, // доживать в доме престарелых rus_verbs:отпраздновать{}, // отпраздновать в ресторане rus_verbs:сотрясаться{}, // сотрясаться в конвульсиях rus_verbs:помыть{}, // помыть в проточной воде инфинитив:увязать{ вид:несоверш }, инфинитив:увязать{ вид:соверш }, // увязать в песке глагол:увязать{ вид:несоверш }, глагол:увязать{ вид:соверш }, прилагательное:увязавший{ вид:несоверш }, rus_verbs:наличествовать{}, // наличествовать в запаснике rus_verbs:нащупывать{}, // нащупывать в кармане rus_verbs:повествоваться{}, // повествоваться в рассказе rus_verbs:отремонтировать{}, // отремонтировать в техцентре rus_verbs:покалывать{}, // покалывать в правом боку rus_verbs:сиживать{}, // сиживать в саду rus_verbs:разрабатываться{}, // разрабатываться в секретных лабораториях rus_verbs:укрепляться{}, // укрепляться в мнении rus_verbs:разниться{}, // разниться во взглядах rus_verbs:сполоснуть{}, // сполоснуть в водичке rus_verbs:скупать{}, // скупать в магазине rus_verbs:почесывать{}, // почесывать в паху rus_verbs:оформлять{}, // оформлять в конторе rus_verbs:распускаться{}, // распускаться в садах rus_verbs:зарябить{}, // зарябить в глазах rus_verbs:загореть{}, // загореть в Испании rus_verbs:очищаться{}, // очищаться в баке rus_verbs:остудить{}, // остудить в холодной воде rus_verbs:разбомбить{}, // разбомбить в горах rus_verbs:издохнуть{}, // издохнуть в бедности rus_verbs:проехаться{}, // проехаться в новой машине rus_verbs:задействовать{}, // задействовать в анализе rus_verbs:произрастать{}, // произрастать в степи rus_verbs:разуться{}, // разуться в прихожей rus_verbs:сооружать{}, // сооружать в огороде rus_verbs:зачитывать{}, // зачитывать в суде rus_verbs:состязаться{}, // состязаться в остроумии rus_verbs:ополоснуть{}, // ополоснуть в молоке rus_verbs:уместиться{}, // уместиться в кармане rus_verbs:совершенствоваться{}, // совершенствоваться в управлении мотоциклом rus_verbs:стираться{}, // стираться в стиральной машине rus_verbs:искупаться{}, // искупаться в прохладной реке rus_verbs:курировать{}, // курировать в правительстве rus_verbs:закупить{}, // закупить в магазине rus_verbs:плодиться{}, // плодиться в подходящих условиях rus_verbs:горланить{}, // горланить в парке rus_verbs:першить{}, // першить в горле rus_verbs:пригрезиться{}, // пригрезиться во сне rus_verbs:исправлять{}, // исправлять в тетрадке rus_verbs:расслабляться{}, // расслабляться в гамаке rus_verbs:скапливаться{}, // скапливаться в нижней части rus_verbs:сплетничать{}, // сплетничают в комнате rus_verbs:раздевать{}, // раздевать в кабинке rus_verbs:окопаться{}, // окопаться в лесу rus_verbs:загорать{}, // загорать в Испании rus_verbs:подпевать{}, // подпевать в церковном хоре rus_verbs:прожужжать{}, // прожужжать в динамике rus_verbs:изучаться{}, // изучаться в дикой природе rus_verbs:заклубиться{}, // заклубиться в воздухе rus_verbs:подметать{}, // подметать в зале rus_verbs:подозреваться{}, // подозреваться в совершении кражи rus_verbs:обогащать{}, // обогащать в специальном аппарате rus_verbs:издаться{}, // издаться в другом издательстве rus_verbs:справить{}, // справить в кустах нужду rus_verbs:помыться{}, // помыться в бане rus_verbs:проскакивать{}, // проскакивать в словах rus_verbs:попивать{}, // попивать в кафе чай rus_verbs:оформляться{}, // оформляться в регистратуре rus_verbs:чирикать{}, // чирикать в кустах rus_verbs:скупить{}, // скупить в магазинах rus_verbs:переночевать{}, // переночевать в гостинице rus_verbs:концентрироваться{}, // концентрироваться в пробирке rus_verbs:одичать{}, // одичать в лесу rus_verbs:ковырнуть{}, // ковырнуть в ухе rus_verbs:затеплиться{}, // затеплиться в глубине души rus_verbs:разгрести{}, // разгрести в задачах залежи rus_verbs:застопориться{}, // застопориться в начале списка rus_verbs:перечисляться{}, // перечисляться во введении rus_verbs:покататься{}, // покататься в парке аттракционов rus_verbs:изловить{}, // изловить в поле rus_verbs:прославлять{}, // прославлять в стихах rus_verbs:промочить{}, // промочить в луже rus_verbs:поделывать{}, // поделывать в отпуске rus_verbs:просуществовать{}, // просуществовать в первобытном состоянии rus_verbs:подстеречь{}, // подстеречь в подъезде rus_verbs:прикупить{}, // прикупить в магазине rus_verbs:перемешивать{}, // перемешивать в кастрюле rus_verbs:тискать{}, // тискать в углу rus_verbs:купать{}, // купать в теплой водичке rus_verbs:завариться{}, // завариться в стакане rus_verbs:притулиться{}, // притулиться в углу rus_verbs:пострелять{}, // пострелять в тире rus_verbs:навесить{}, // навесить в больнице инфинитив:изолировать{ вид:соверш }, инфинитив:изолировать{ вид:несоверш }, // изолировать в камере глагол:изолировать{ вид:соверш }, глагол:изолировать{ вид:несоверш }, rus_verbs:нежиться{}, // нежится в постельке rus_verbs:притомиться{}, // притомиться в школе rus_verbs:раздвоиться{}, // раздвоиться в глазах rus_verbs:навалить{}, // навалить в углу rus_verbs:замуровать{}, // замуровать в склепе rus_verbs:поселяться{}, // поселяться в кроне дуба rus_verbs:потягиваться{}, // потягиваться в кровати rus_verbs:укачать{}, // укачать в поезде rus_verbs:отлеживаться{}, // отлеживаться в гамаке rus_verbs:разменять{}, // разменять в кассе rus_verbs:прополоскать{}, // прополоскать в чистой теплой воде rus_verbs:ржаветь{}, // ржаветь в воде rus_verbs:уличить{}, // уличить в плагиате rus_verbs:мутиться{}, // мутиться в голове rus_verbs:растворять{}, // растворять в бензоле rus_verbs:двоиться{}, // двоиться в глазах rus_verbs:оговорить{}, // оговорить в договоре rus_verbs:подделать{}, // подделать в документе rus_verbs:зарегистрироваться{}, // зарегистрироваться в социальной сети rus_verbs:растолстеть{}, // растолстеть в талии rus_verbs:повоевать{}, // повоевать в городских условиях rus_verbs:прибраться{}, // гнушаться прибраться в хлеву rus_verbs:поглощаться{}, // поглощаться в металлической фольге rus_verbs:ухать{}, // ухать в лесу rus_verbs:подписываться{}, // подписываться в петиции rus_verbs:покатать{}, // покатать в машинке rus_verbs:излечиться{}, // излечиться в клинике rus_verbs:трепыхаться{}, // трепыхаться в мешке rus_verbs:кипятить{}, // кипятить в кастрюле rus_verbs:понастроить{}, // понастроить в прибрежной зоне rus_verbs:перебывать{}, // перебывать во всех европейских столицах rus_verbs:оглашать{}, // оглашать в итоговой части rus_verbs:преуспевать{}, // преуспевать в новом бизнесе rus_verbs:консультироваться{}, // консультироваться в техподдержке rus_verbs:накапливать{}, // накапливать в печени rus_verbs:перемешать{}, // перемешать в контейнере rus_verbs:наследить{}, // наследить в коридоре rus_verbs:выявиться{}, // выявиться в результе rus_verbs:забулькать{}, // забулькать в болоте rus_verbs:отваривать{}, // отваривать в молоке rus_verbs:запутываться{}, // запутываться в веревках rus_verbs:нагреться{}, // нагреться в микроволновой печке rus_verbs:рыбачить{}, // рыбачить в открытом море rus_verbs:укорениться{}, // укорениться в сознании широких народных масс rus_verbs:умывать{}, // умывать в тазике rus_verbs:защекотать{}, // защекотать в носу rus_verbs:заходиться{}, // заходиться в плаче инфинитив:искупать{ вид:соверш }, инфинитив:искупать{ вид:несоверш }, // искупать в прохладной водичке глагол:искупать{ вид:соверш }, глагол:искупать{ вид:несоверш }, деепричастие:искупав{}, деепричастие:искупая{}, rus_verbs:заморозить{}, // заморозить в холодильнике rus_verbs:закреплять{}, // закреплять в металлическом держателе rus_verbs:расхватать{}, // расхватать в магазине rus_verbs:истязать{}, // истязать в тюремном подвале rus_verbs:заржаветь{}, // заржаветь во влажной атмосфере rus_verbs:обжаривать{}, // обжаривать в подсолнечном масле rus_verbs:умереть{}, // Ты, подлый предатель, умрешь в нищете rus_verbs:подогреть{}, // подогрей в микроволновке rus_verbs:подогревать{}, rus_verbs:затянуть{}, // Кузнечики, сверчки, скрипачи и медведки затянули в траве свою трескучую музыку rus_verbs:проделать{}, // проделать в стене дыру инфинитив:жениться{ вид:соверш }, // жениться в Техасе инфинитив:жениться{ вид:несоверш }, глагол:жениться{ вид:соверш }, глагол:жениться{ вид:несоверш }, деепричастие:женившись{}, деепричастие:женясь{}, прилагательное:женатый{}, прилагательное:женившийся{вид:соверш}, прилагательное:женящийся{}, rus_verbs:всхрапнуть{}, // всхрапнуть во сне rus_verbs:всхрапывать{}, // всхрапывать во сне rus_verbs:ворочаться{}, // Собака ворочается во сне rus_verbs:воссоздаваться{}, // воссоздаваться в памяти rus_verbs:акклиматизироваться{}, // альпинисты готовятся акклиматизироваться в горах инфинитив:атаковать{ вид:несоверш }, // взвод был атакован в лесу инфинитив:атаковать{ вид:соверш }, глагол:атаковать{ вид:несоверш }, глагол:атаковать{ вид:соверш }, прилагательное:атакованный{}, прилагательное:атаковавший{}, прилагательное:атакующий{}, инфинитив:аккумулировать{вид:несоверш}, // энергия была аккумулирована в печени инфинитив:аккумулировать{вид:соверш}, глагол:аккумулировать{вид:несоверш}, глагол:аккумулировать{вид:соверш}, прилагательное:аккумулированный{}, прилагательное:аккумулирующий{}, //прилагательное:аккумулировавший{ вид:несоверш }, прилагательное:аккумулировавший{ вид:соверш }, rus_verbs:врисовывать{}, // врисовывать нового персонажа в анимацию rus_verbs:вырасти{}, // Он вырос в глазах коллег. rus_verbs:иметь{}, // Он всегда имел в резерве острое словцо. rus_verbs:убить{}, // убить в себе зверя инфинитив:абсорбироваться{ вид:соверш }, // жидкость абсорбируется в поглощающей ткани инфинитив:абсорбироваться{ вид:несоверш }, глагол:абсорбироваться{ вид:соверш }, глагол:абсорбироваться{ вид:несоверш }, rus_verbs:поставить{}, // поставить в углу rus_verbs:сжимать{}, // сжимать в кулаке rus_verbs:готовиться{}, // альпинисты готовятся акклиматизироваться в горах rus_verbs:аккумулироваться{}, // энергия аккумулируется в жировых отложениях инфинитив:активизироваться{ вид:несоверш }, // в горах активизировались повстанцы инфинитив:активизироваться{ вид:соверш }, глагол:активизироваться{ вид:несоверш }, глагол:активизироваться{ вид:соверш }, rus_verbs:апробировать{}, // пилот апробировал в ходе испытаний новый режим планера rus_verbs:арестовать{}, // наркодилер был арестован в помещении кафе rus_verbs:базировать{}, // установка будет базирована в лесу rus_verbs:барахтаться{}, // дети барахтались в воде rus_verbs:баррикадироваться{}, // преступники баррикадируются в помещении банка rus_verbs:барствовать{}, // Семен Семенович барствовал в своей деревне rus_verbs:бесчинствовать{}, // Боевики бесчинствовали в захваченном селе rus_verbs:блаженствовать{}, // Воробьи блаженствовали в кроне рябины rus_verbs:блуждать{}, // Туристы блуждали в лесу rus_verbs:брать{}, // Жена берет деньги в тумбочке rus_verbs:бродить{}, // парочки бродили в парке rus_verbs:обойти{}, // Бразилия обошла Россию в рейтинге rus_verbs:задержать{}, // Знаменитый советский фигурист задержан в США rus_verbs:бултыхаться{}, // Ноги бултыхаются в воде rus_verbs:вариться{}, // Курица варится в кастрюле rus_verbs:закончиться{}, // Эта рецессия закончилась в 2003 году rus_verbs:прокручиваться{}, // Ключ прокручивается в замке rus_verbs:прокрутиться{}, // Ключ трижды прокрутился в замке rus_verbs:храниться{}, // Настройки хранятся в текстовом файле rus_verbs:сохраняться{}, // Настройки сохраняются в текстовом файле rus_verbs:витать{}, // Мальчик витает в облаках rus_verbs:владычествовать{}, // Король владычествует в стране rus_verbs:властвовать{}, // Олигархи властвовали в стране rus_verbs:возбудить{}, // возбудить в сердце тоску rus_verbs:возбуждать{}, // возбуждать в сердце тоску rus_verbs:возвыситься{}, // возвыситься в глазах современников rus_verbs:возжечь{}, // возжечь в храме огонь rus_verbs:возжечься{}, // Огонь возжёгся в храме rus_verbs:возжигать{}, // возжигать в храме огонь rus_verbs:возжигаться{}, // Огонь возжигается в храме rus_verbs:вознамериваться{}, // вознамериваться уйти в монастырь rus_verbs:вознамериться{}, // вознамериться уйти в монастырь rus_verbs:возникать{}, // Новые идеи неожиданно возникают в колиной голове rus_verbs:возникнуть{}, // Новые идейки возникли в голове rus_verbs:возродиться{}, // возродиться в новом качестве rus_verbs:возрождать{}, // возрождать в новом качестве rus_verbs:возрождаться{}, // возрождаться в новом амплуа rus_verbs:ворошить{}, // ворошить в камине кочергой золу rus_verbs:воспевать{}, // Поэты воспевают героев в одах rus_verbs:воспеваться{}, // Герои воспеваются в одах поэтами rus_verbs:воспеть{}, // Поэты воспели в этой оде героев rus_verbs:воспретить{}, // воспретить в помещении азартные игры rus_verbs:восславить{}, // Поэты восславили в одах rus_verbs:восславлять{}, // Поэты восславляют в одах rus_verbs:восславляться{}, // Героя восславляются в одах rus_verbs:воссоздать{}, // воссоздает в памяти образ человека rus_verbs:воссоздавать{}, // воссоздать в памяти образ человека rus_verbs:воссоздаться{}, // воссоздаться в памяти rus_verbs:вскипятить{}, // вскипятить в чайнике воду rus_verbs:вскипятиться{}, // вскипятиться в чайнике rus_verbs:встретить{}, // встретить в классе старого приятеля rus_verbs:встретиться{}, // встретиться в классе rus_verbs:встречать{}, // встречать в лесу голодного медведя rus_verbs:встречаться{}, // встречаться в кафе rus_verbs:выбривать{}, // выбривать что-то в подмышках rus_verbs:выбрить{}, // выбрить что-то в паху rus_verbs:вывалять{}, // вывалять кого-то в грязи rus_verbs:вываляться{}, // вываляться в грязи rus_verbs:вываривать{}, // вываривать в молоке rus_verbs:вывариваться{}, // вывариваться в молоке rus_verbs:выварить{}, // выварить в молоке rus_verbs:вывариться{}, // вывариться в молоке rus_verbs:выгрызать{}, // выгрызать в сыре отверствие rus_verbs:выгрызть{}, // выгрызть в сыре отверстие rus_verbs:выгуливать{}, // выгуливать в парке собаку rus_verbs:выгулять{}, // выгулять в парке собаку rus_verbs:выдолбить{}, // выдолбить в стволе углубление rus_verbs:выжить{}, // выжить в пустыне rus_verbs:Выискать{}, // Выискать в программе ошибку rus_verbs:выискаться{}, // Ошибка выискалась в программе rus_verbs:выискивать{}, // выискивать в программе ошибку rus_verbs:выискиваться{}, // выискиваться в программе rus_verbs:выкраивать{}, // выкраивать в расписании время rus_verbs:выкраиваться{}, // выкраиваться в расписании инфинитив:выкупаться{aux stress="в^ыкупаться"}, // выкупаться в озере глагол:выкупаться{вид:соверш}, rus_verbs:выловить{}, // выловить в пруду rus_verbs:вымачивать{}, // вымачивать в молоке rus_verbs:вымачиваться{}, // вымачиваться в молоке rus_verbs:вынюхивать{}, // вынюхивать в траве следы rus_verbs:выпачкать{}, // выпачкать в смоле свою одежду rus_verbs:выпачкаться{}, // выпачкаться в грязи rus_verbs:вырастить{}, // вырастить в теплице ведро огурчиков rus_verbs:выращивать{}, // выращивать в теплице помидоры rus_verbs:выращиваться{}, // выращиваться в теплице rus_verbs:вырыть{}, // вырыть в земле глубокую яму rus_verbs:высадить{}, // высадить в пустынной местности rus_verbs:высадиться{}, // высадиться в пустынной местности rus_verbs:высаживать{}, // высаживать в пустыне rus_verbs:высверливать{}, // высверливать в доске отверствие rus_verbs:высверливаться{}, // высверливаться в стене rus_verbs:высверлить{}, // высверлить в стене отверствие rus_verbs:высверлиться{}, // высверлиться в стене rus_verbs:выскоблить{}, // выскоблить в столешнице канавку rus_verbs:высматривать{}, // высматривать в темноте rus_verbs:заметить{}, // заметить в помещении rus_verbs:оказаться{}, // оказаться в первых рядах rus_verbs:душить{}, // душить в объятиях rus_verbs:оставаться{}, // оставаться в классе rus_verbs:появиться{}, // впервые появиться в фильме rus_verbs:лежать{}, // лежать в футляре rus_verbs:раздаться{}, // раздаться в плечах rus_verbs:ждать{}, // ждать в здании вокзала rus_verbs:жить{}, // жить в трущобах rus_verbs:постелить{}, // постелить в прихожей rus_verbs:оказываться{}, // оказываться в неприятной ситуации rus_verbs:держать{}, // держать в голове rus_verbs:обнаружить{}, // обнаружить в себе способность rus_verbs:начинать{}, // начинать в лаборатории rus_verbs:рассказывать{}, // рассказывать в лицах rus_verbs:ожидать{}, // ожидать в помещении rus_verbs:продолжить{}, // продолжить в помещении rus_verbs:состоять{}, // состоять в группе rus_verbs:родиться{}, // родиться в рубашке rus_verbs:искать{}, // искать в кармане rus_verbs:иметься{}, // иметься в наличии rus_verbs:говориться{}, // говориться в среде панков rus_verbs:клясться{}, // клясться в верности rus_verbs:узнавать{}, // узнавать в нем своего сына rus_verbs:признаться{}, // признаться в ошибке rus_verbs:сомневаться{}, // сомневаться в искренности rus_verbs:толочь{}, // толочь в ступе rus_verbs:понадобиться{}, // понадобиться в суде rus_verbs:служить{}, // служить в пехоте rus_verbs:потолочь{}, // потолочь в ступе rus_verbs:появляться{}, // появляться в театре rus_verbs:сжать{}, // сжать в объятиях rus_verbs:действовать{}, // действовать в постановке rus_verbs:селить{}, // селить в гостинице rus_verbs:поймать{}, // поймать в лесу rus_verbs:увидать{}, // увидать в толпе rus_verbs:подождать{}, // подождать в кабинете rus_verbs:прочесть{}, // прочесть в глазах rus_verbs:тонуть{}, // тонуть в реке rus_verbs:ощущать{}, // ощущать в животе rus_verbs:ошибиться{}, // ошибиться в расчетах rus_verbs:отметить{}, // отметить в списке rus_verbs:показывать{}, // показывать в динамике rus_verbs:скрыться{}, // скрыться в траве rus_verbs:убедиться{}, // убедиться в корректности rus_verbs:прозвучать{}, // прозвучать в наушниках rus_verbs:разговаривать{}, // разговаривать в фойе rus_verbs:издать{}, // издать в России rus_verbs:прочитать{}, // прочитать в газете rus_verbs:попробовать{}, // попробовать в деле rus_verbs:замечать{}, // замечать в программе ошибку rus_verbs:нести{}, // нести в руках rus_verbs:пропасть{}, // пропасть в плену rus_verbs:носить{}, // носить в кармане rus_verbs:гореть{}, // гореть в аду rus_verbs:поправить{}, // поправить в программе rus_verbs:застыть{}, // застыть в неудобной позе rus_verbs:получать{}, // получать в кассе rus_verbs:потребоваться{}, // потребоваться в работе rus_verbs:спрятать{}, // спрятать в шкафу rus_verbs:учиться{}, // учиться в институте rus_verbs:развернуться{}, // развернуться в коридоре rus_verbs:подозревать{}, // подозревать в мошенничестве rus_verbs:играть{}, // играть в команде rus_verbs:сыграть{}, // сыграть в команде rus_verbs:строить{}, // строить в деревне rus_verbs:устроить{}, // устроить в доме вечеринку rus_verbs:находить{}, // находить в лесу rus_verbs:нуждаться{}, // нуждаться в деньгах rus_verbs:испытать{}, // испытать в рабочей обстановке rus_verbs:мелькнуть{}, // мелькнуть в прицеле rus_verbs:очутиться{}, // очутиться в закрытом помещении инфинитив:использовать{вид:соверш}, // использовать в работе инфинитив:использовать{вид:несоверш}, глагол:использовать{вид:несоверш}, глагол:использовать{вид:соверш}, rus_verbs:лететь{}, // лететь в самолете rus_verbs:смеяться{}, // смеяться в цирке rus_verbs:ездить{}, // ездить в лимузине rus_verbs:заснуть{}, // заснуть в неудобной позе rus_verbs:застать{}, // застать в неформальной обстановке rus_verbs:очнуться{}, // очнуться в незнакомой обстановке rus_verbs:твориться{}, // Что творится в закрытой зоне rus_verbs:разглядеть{}, // разглядеть в темноте rus_verbs:изучать{}, // изучать в естественных условиях rus_verbs:удержаться{}, // удержаться в седле rus_verbs:побывать{}, // побывать в зоопарке rus_verbs:уловить{}, // уловить в словах нотку отчаяния rus_verbs:приобрести{}, // приобрести в лавке rus_verbs:исчезать{}, // исчезать в тумане rus_verbs:уверять{}, // уверять в своей невиновности rus_verbs:продолжаться{}, // продолжаться в воздухе rus_verbs:открывать{}, // открывать в городе новый стадион rus_verbs:поддержать{}, // поддержать в парке порядок rus_verbs:солить{}, // солить в бочке rus_verbs:прожить{}, // прожить в деревне rus_verbs:создавать{}, // создавать в театре rus_verbs:обсуждать{}, // обсуждать в коллективе rus_verbs:заказать{}, // заказать в магазине rus_verbs:отыскать{}, // отыскать в гараже rus_verbs:уснуть{}, // уснуть в кресле rus_verbs:задержаться{}, // задержаться в театре rus_verbs:подобрать{}, // подобрать в коллекции rus_verbs:пробовать{}, // пробовать в работе rus_verbs:курить{}, // курить в закрытом помещении rus_verbs:устраивать{}, // устраивать в лесу засаду rus_verbs:установить{}, // установить в багажнике rus_verbs:запереть{}, // запереть в сарае rus_verbs:содержать{}, // содержать в достатке rus_verbs:синеть{}, // синеть в кислородной атмосфере rus_verbs:слышаться{}, // слышаться в голосе rus_verbs:закрыться{}, // закрыться в здании rus_verbs:скрываться{}, // скрываться в квартире rus_verbs:родить{}, // родить в больнице rus_verbs:описать{}, // описать в заметках rus_verbs:перехватить{}, // перехватить в коридоре rus_verbs:менять{}, // менять в магазине rus_verbs:скрывать{}, // скрывать в чужой квартире rus_verbs:стиснуть{}, // стиснуть в стальных объятиях rus_verbs:останавливаться{}, // останавливаться в гостинице rus_verbs:мелькать{}, // мелькать в телевизоре rus_verbs:присутствовать{}, // присутствовать в аудитории rus_verbs:украсть{}, // украсть в магазине rus_verbs:победить{}, // победить в войне rus_verbs:расположиться{}, // расположиться в гостинице rus_verbs:упомянуть{}, // упомянуть в своей книге rus_verbs:плыть{}, // плыть в старой бочке rus_verbs:нащупать{}, // нащупать в глубине rus_verbs:проявляться{}, // проявляться в работе rus_verbs:затихнуть{}, // затихнуть в норе rus_verbs:построить{}, // построить в гараже rus_verbs:поддерживать{}, // поддерживать в исправном состоянии rus_verbs:заработать{}, // заработать в стартапе rus_verbs:сломать{}, // сломать в суставе rus_verbs:снимать{}, // снимать в гардеробе rus_verbs:сохранить{}, // сохранить в коллекции rus_verbs:располагаться{}, // располагаться в отдельном кабинете rus_verbs:сражаться{}, // сражаться в честном бою rus_verbs:спускаться{}, // спускаться в батискафе rus_verbs:уничтожить{}, // уничтожить в схроне rus_verbs:изучить{}, // изучить в естественных условиях rus_verbs:рождаться{}, // рождаться в муках rus_verbs:пребывать{}, // пребывать в прострации rus_verbs:прилететь{}, // прилететь в аэробусе rus_verbs:догнать{}, // догнать в переулке rus_verbs:изобразить{}, // изобразить в танце rus_verbs:проехать{}, // проехать в легковушке rus_verbs:убедить{}, // убедить в разумности rus_verbs:приготовить{}, // приготовить в духовке rus_verbs:собирать{}, // собирать в лесу rus_verbs:поплыть{}, // поплыть в катере rus_verbs:доверять{}, // доверять в управлении rus_verbs:разобраться{}, // разобраться в законах rus_verbs:ловить{}, // ловить в озере rus_verbs:проесть{}, // проесть в куске металла отверстие rus_verbs:спрятаться{}, // спрятаться в подвале rus_verbs:провозгласить{}, // провозгласить в речи rus_verbs:изложить{}, // изложить в своём выступлении rus_verbs:замяться{}, // замяться в коридоре rus_verbs:раздаваться{}, // Крик ягуара раздается в джунглях rus_verbs:доказать{}, // Автор доказал в своей работе, что теорема верна rus_verbs:хранить{}, // хранить в шкатулке rus_verbs:шутить{}, // шутить в классе глагол:рассыпаться{ aux stress="рассып^аться" }, // рассыпаться в извинениях инфинитив:рассыпаться{ aux stress="рассып^аться" }, rus_verbs:чертить{}, // чертить в тетрадке rus_verbs:отразиться{}, // отразиться в аттестате rus_verbs:греть{}, // греть в микроволновке rus_verbs:зарычать{}, // Кто-то зарычал в глубине леса rus_verbs:рассуждать{}, // Автор рассуждает в своей статье rus_verbs:освободить{}, // Обвиняемые были освобождены в зале суда rus_verbs:окружать{}, // окружать в лесу rus_verbs:сопровождать{}, // сопровождать в операции rus_verbs:заканчиваться{}, // заканчиваться в дороге rus_verbs:поселиться{}, // поселиться в загородном доме rus_verbs:охватывать{}, // охватывать в хронологии rus_verbs:запеть{}, // запеть в кино инфинитив:провозить{вид:несоверш}, // провозить в багаже глагол:провозить{вид:несоверш}, rus_verbs:мочить{}, // мочить в сортире rus_verbs:перевернуться{}, // перевернуться в полёте rus_verbs:улететь{}, // улететь в теплые края rus_verbs:сдержать{}, // сдержать в руках rus_verbs:преследовать{}, // преследовать в любой другой стране rus_verbs:драться{}, // драться в баре rus_verbs:просидеть{}, // просидеть в классе rus_verbs:убираться{}, // убираться в квартире rus_verbs:содрогнуться{}, // содрогнуться в приступе отвращения rus_verbs:пугать{}, // пугать в прессе rus_verbs:отреагировать{}, // отреагировать в прессе rus_verbs:проверять{}, // проверять в аппарате rus_verbs:убеждать{}, // убеждать в отсутствии альтернатив rus_verbs:летать{}, // летать в комфортабельном частном самолёте rus_verbs:толпиться{}, // толпиться в фойе rus_verbs:плавать{}, // плавать в специальном костюме rus_verbs:пробыть{}, // пробыть в воде слишком долго rus_verbs:прикинуть{}, // прикинуть в уме rus_verbs:застрять{}, // застрять в лифте rus_verbs:метаться{}, // метаться в кровате rus_verbs:сжечь{}, // сжечь в печке rus_verbs:расслабиться{}, // расслабиться в ванной rus_verbs:услыхать{}, // услыхать в автобусе rus_verbs:удержать{}, // удержать в вертикальном положении rus_verbs:образоваться{}, // образоваться в верхних слоях атмосферы rus_verbs:рассмотреть{}, // рассмотреть в капле воды rus_verbs:просмотреть{}, // просмотреть в браузере rus_verbs:учесть{}, // учесть в планах rus_verbs:уезжать{}, // уезжать в чьей-то машине rus_verbs:похоронить{}, // похоронить в мерзлой земле rus_verbs:растянуться{}, // растянуться в расслабленной позе rus_verbs:обнаружиться{}, // обнаружиться в чужой сумке rus_verbs:гулять{}, // гулять в парке rus_verbs:утонуть{}, // утонуть в реке rus_verbs:зажать{}, // зажать в медвежьих объятиях rus_verbs:усомниться{}, // усомниться в объективности rus_verbs:танцевать{}, // танцевать в спортзале rus_verbs:проноситься{}, // проноситься в голове rus_verbs:трудиться{}, // трудиться в кооперативе глагол:засыпать{ aux stress="засып^ать" переходность:непереходный }, // засыпать в спальном мешке инфинитив:засыпать{ aux stress="засып^ать" переходность:непереходный }, rus_verbs:сушить{}, // сушить в сушильном шкафу rus_verbs:зашевелиться{}, // зашевелиться в траве rus_verbs:обдумывать{}, // обдумывать в спокойной обстановке rus_verbs:промелькнуть{}, // промелькнуть в окне rus_verbs:поучаствовать{}, // поучаствовать в обсуждении rus_verbs:закрыть{}, // закрыть в комнате rus_verbs:запирать{}, // запирать в комнате rus_verbs:закрывать{}, // закрывать в доме rus_verbs:заблокировать{}, // заблокировать в доме rus_verbs:зацвести{}, // В садах зацвела сирень rus_verbs:кричать{}, // Какое-то животное кричало в ночном лесу. rus_verbs:поглотить{}, // фотон, поглощенный в рецепторе rus_verbs:стоять{}, // войска, стоявшие в Риме rus_verbs:закалить{}, // ветераны, закаленные в боях rus_verbs:выступать{}, // пришлось выступать в тюрьме. rus_verbs:выступить{}, // пришлось выступить в тюрьме. rus_verbs:закопошиться{}, // Мыши закопошились в траве rus_verbs:воспламениться{}, // смесь, воспламенившаяся в цилиндре rus_verbs:воспламеняться{}, // смесь, воспламеняющаяся в цилиндре rus_verbs:закрываться{}, // закрываться в комнате rus_verbs:провалиться{}, // провалиться в прокате деепричастие:авторизируясь{ вид:несоверш }, глагол:авторизироваться{ вид:несоверш }, инфинитив:авторизироваться{ вид:несоверш }, // авторизироваться в системе rus_verbs:существовать{}, // существовать в вакууме деепричастие:находясь{}, прилагательное:находившийся{}, прилагательное:находящийся{}, глагол:находиться{ вид:несоверш }, инфинитив:находиться{ вид:несоверш }, // находиться в вакууме rus_verbs:регистрировать{}, // регистрировать в инспекции глагол:перерегистрировать{ вид:несоверш }, глагол:перерегистрировать{ вид:соверш }, инфинитив:перерегистрировать{ вид:несоверш }, инфинитив:перерегистрировать{ вид:соверш }, // перерегистрировать в инспекции rus_verbs:поковыряться{}, // поковыряться в носу rus_verbs:оттаять{}, // оттаять в кипятке rus_verbs:распинаться{}, // распинаться в проклятиях rus_verbs:отменить{}, // Министерство связи предлагает отменить внутренний роуминг в России rus_verbs:столкнуться{}, // Американский эсминец и японский танкер столкнулись в Персидском заливе rus_verbs:ценить{}, // Он очень ценил в статьях краткость изложения. прилагательное:несчастный{}, // Он очень несчастен в семейной жизни. rus_verbs:объясниться{}, // Он объяснился в любви. прилагательное:нетвердый{}, // Он нетвёрд в истории. rus_verbs:заниматься{}, // Он занимается в читальном зале. rus_verbs:вращаться{}, // Он вращается в учёных кругах. прилагательное:спокойный{}, // Он был спокоен и уверен в завтрашнем дне. rus_verbs:бегать{}, // Он бегал по городу в поисках квартиры. rus_verbs:заключать{}, // Письмо заключало в себе очень важные сведения. rus_verbs:срабатывать{}, // Алгоритм срабатывает в половине случаев. rus_verbs:специализироваться{}, // мы специализируемся в создании ядерного оружия rus_verbs:сравниться{}, // Никто не может сравниться с ним в знаниях. rus_verbs:продолжать{}, // Продолжайте в том же духе. rus_verbs:говорить{}, // Не говорите об этом в присутствии третьих лиц. rus_verbs:болтать{}, // Не болтай в присутствии начальника! rus_verbs:проболтаться{}, // Не проболтайся в присутствии начальника! rus_verbs:повторить{}, // Он должен повторить свои показания в присутствии свидетелей rus_verbs:получить{}, // ректор поздравил студентов, получивших в этом семестре повышенную стипендию rus_verbs:приобретать{}, // Эту еду мы приобретаем в соседнем магазине. rus_verbs:расходиться{}, // Маша и Петя расходятся во взглядах rus_verbs:сходиться{}, // Все дороги сходятся в Москве rus_verbs:убирать{}, // убирать в комнате rus_verbs:удостоверяться{}, // он удостоверяется в личности специалиста rus_verbs:уединяться{}, // уединяться в пустыне rus_verbs:уживаться{}, // уживаться в одном коллективе rus_verbs:укорять{}, // укорять друга в забывчивости rus_verbs:читать{}, // он читал об этом в журнале rus_verbs:состояться{}, // В Израиле состоятся досрочные парламентские выборы rus_verbs:погибнуть{}, // Список погибших в авиакатастрофе под Ярославлем rus_verbs:работать{}, // Я работаю в театре. rus_verbs:признать{}, // Я признал в нём старого друга. rus_verbs:преподавать{}, // Я преподаю в университете. rus_verbs:понимать{}, // Я плохо понимаю в живописи. rus_verbs:водиться{}, // неизвестный науке зверь, который водится в жарких тропических лесах rus_verbs:разразиться{}, // В Москве разразилась эпидемия гриппа rus_verbs:замереть{}, // вся толпа замерла в восхищении rus_verbs:сидеть{}, // Я люблю сидеть в этом удобном кресле. rus_verbs:идти{}, // Я иду в неопределённом направлении. rus_verbs:заболеть{}, // Я заболел в дороге. rus_verbs:ехать{}, // Я еду в автобусе rus_verbs:взять{}, // Я взял книгу в библиотеке на неделю. rus_verbs:провести{}, // Юные годы он провёл в Италии. rus_verbs:вставать{}, // Этот случай живо встаёт в моей памяти. rus_verbs:возвысить{}, // Это событие возвысило его в общественном мнении. rus_verbs:произойти{}, // Это произошло в одном городе в Японии. rus_verbs:привидеться{}, // Это мне привиделось во сне. rus_verbs:держаться{}, // Это дело держится в большом секрете. rus_verbs:привиться{}, // Это выражение не привилось в русском языке. rus_verbs:восстановиться{}, // Эти писатели восстановились в правах. rus_verbs:быть{}, // Эта книга есть в любом книжном магазине. прилагательное:популярный{}, // Эта идея очень популярна в массах. rus_verbs:шуметь{}, // Шумит в голове. rus_verbs:остаться{}, // Шляпа осталась в поезде. rus_verbs:выражаться{}, // Характер писателя лучше всего выражается в его произведениях. rus_verbs:воспитать{}, // Учительница воспитала в детях любовь к природе. rus_verbs:пересохнуть{}, // У меня в горле пересохло. rus_verbs:щекотать{}, // У меня в горле щекочет. rus_verbs:колоть{}, // У меня в боку колет. прилагательное:свежий{}, // Событие ещё свежо в памяти. rus_verbs:собрать{}, // Соберите всех учеников во дворе. rus_verbs:белеть{}, // Снег белеет в горах. rus_verbs:сделать{}, // Сколько орфографических ошибок ты сделал в диктанте? rus_verbs:таять{}, // Сахар тает в кипятке. rus_verbs:жать{}, // Сапог жмёт в подъёме. rus_verbs:возиться{}, // Ребята возятся в углу. rus_verbs:распоряжаться{}, // Прошу не распоряжаться в чужом доме. rus_verbs:кружиться{}, // Они кружились в вальсе. rus_verbs:выставлять{}, // Они выставляют его в смешном виде. rus_verbs:бывать{}, // Она часто бывает в обществе. rus_verbs:петь{}, // Она поёт в опере. rus_verbs:сойтись{}, // Все свидетели сошлись в своих показаниях. rus_verbs:валяться{}, // Вещи валялись в беспорядке. rus_verbs:пройти{}, // Весь день прошёл в беготне. rus_verbs:продавать{}, // В этом магазине продают обувь. rus_verbs:заключаться{}, // В этом заключается вся сущность. rus_verbs:звенеть{}, // В ушах звенит. rus_verbs:проступить{}, // В тумане проступили очертания корабля. rus_verbs:бить{}, // В саду бьёт фонтан. rus_verbs:проскользнуть{}, // В речи проскользнул упрёк. rus_verbs:оставить{}, // Не оставь товарища в опасности. rus_verbs:прогулять{}, // Мы прогуляли час в парке. rus_verbs:перебить{}, // Мы перебили врагов в бою. rus_verbs:остановиться{}, // Мы остановились в первой попавшейся гостинице. rus_verbs:видеть{}, // Он многое видел в жизни. // глагол:проходить{ вид:несоверш }, // Беседа проходила в дружественной атмосфере. rus_verbs:подать{}, // Автор подал своих героев в реалистических тонах. rus_verbs:кинуть{}, // Он кинул меня в беде. rus_verbs:приходить{}, // Приходи в сентябре rus_verbs:воскрешать{}, // воскрешать в памяти rus_verbs:соединять{}, // соединять в себе rus_verbs:разбираться{}, // умение разбираться в вещах rus_verbs:делать{}, // В её комнате делали обыск. rus_verbs:воцариться{}, // В зале воцарилась глубокая тишина. rus_verbs:начаться{}, // В деревне начались полевые работы. rus_verbs:блеснуть{}, // В голове блеснула хорошая мысль. rus_verbs:вертеться{}, // В голове вертится вчерашний разговор. rus_verbs:веять{}, // В воздухе веет прохладой. rus_verbs:висеть{}, // В воздухе висит зной. rus_verbs:носиться{}, // В воздухе носятся комары. rus_verbs:грести{}, // Грести в спокойной воде будет немного легче, но скучнее rus_verbs:воскресить{}, // воскресить в памяти rus_verbs:поплавать{}, // поплавать в 100-метровом бассейне rus_verbs:пострадать{}, // В массовой драке пострадал 23-летний мужчина прилагательное:уверенный{ причастие }, // Она уверена в своих силах. прилагательное:постоянный{}, // Она постоянна во вкусах. прилагательное:сильный{}, // Он не силён в математике. прилагательное:повинный{}, // Он не повинен в этом. прилагательное:возможный{}, // Ураганы, сильные грозы и даже смерчи возможны в конце периода сильной жары rus_verbs:вывести{}, // способный летать над землей крокодил был выведен в секретной лаборатории прилагательное:нужный{}, // сковородка тоже нужна в хозяйстве. rus_verbs:сесть{}, // Она села в тени rus_verbs:заливаться{}, // в нашем парке заливаются соловьи rus_verbs:разнести{}, // В лесу огонь пожара мгновенно разнесло rus_verbs:чувствоваться{}, // В тёплом, но сыром воздухе остро чувствовалось дыхание осени // rus_verbs:расти{}, // дерево, растущее в лесу rus_verbs:происходить{}, // что происходит в поликлиннике rus_verbs:спать{}, // кто спит в моей кровати rus_verbs:мыть{}, // мыть машину в саду ГЛ_ИНФ(царить), // В воздухе царило безмолвие ГЛ_ИНФ(мести), // мести в прихожей пол ГЛ_ИНФ(прятать), // прятать в яме ГЛ_ИНФ(увидеть), прилагательное:увидевший{}, деепричастие:увидев{}, // увидел периодическую таблицу элементов во сне. // ГЛ_ИНФ(собраться), // собраться в порту ГЛ_ИНФ(случиться), // что-то случилось в больнице ГЛ_ИНФ(зажечься), // в небе зажглись звёзды ГЛ_ИНФ(купить), // купи молока в магазине прилагательное:пропагандировавшийся{} // группа студентов университета дружбы народов, активно пропагандировавшейся в СССР } // Чтобы разрешить связывание в паттернах типа: пообедать в macdonalds fact гл_предл { if context { Гл_В_Предл предлог:в{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { Гл_В_Предл предлог:в{} *:*{ падеж:предл } } then return true } // С локативом: // собраться в порту fact гл_предл { if context { Гл_В_Предл предлог:в{} существительное:*{ падеж:мест } } then return true } #endregion Предложный #region Винительный // Для глаголов движения с выраженным направлением действия может присоединяться // предложный паттерн с винительным падежом. wordentry_set Гл_В_Вин = { rus_verbs:вдавиться{}, // Дуло больно вдавилось в позвонок. глагол:ввергнуть{}, // Двух прелестнейших дам он ввергнул в горе. глагол:ввергать{}, инфинитив:ввергнуть{}, инфинитив:ввергать{}, rus_verbs:двинуться{}, // Двинулись в путь и мы. rus_verbs:сплавать{}, // Сплавать в Россию! rus_verbs:уложиться{}, // Уложиться в воскресенье. rus_verbs:спешить{}, // Спешите в Лондон rus_verbs:кинуть{}, // Киньте в море. rus_verbs:проситься{}, // Просилась в Никарагуа. rus_verbs:притопать{}, // Притопал в Будапешт. rus_verbs:скататься{}, // Скатался в Красноярск. rus_verbs:соскользнуть{}, // Соскользнул в пике. rus_verbs:соскальзывать{}, rus_verbs:играть{}, // Играл в дутье. глагол:айда{}, // Айда в каморы. rus_verbs:отзывать{}, // Отзывали в Москву... rus_verbs:сообщаться{}, // Сообщается в Лондон. rus_verbs:вдуматься{}, // Вдумайтесь в них. rus_verbs:проехать{}, // Проехать в Лунево... rus_verbs:спрыгивать{}, // Спрыгиваем в него. rus_verbs:верить{}, // Верю в вас! rus_verbs:прибыть{}, // Прибыл в Подмосковье. rus_verbs:переходить{}, // Переходите в школу. rus_verbs:доложить{}, // Доложили в Москву. rus_verbs:подаваться{}, // Подаваться в Россию? rus_verbs:спрыгнуть{}, // Спрыгнул в него. rus_verbs:вывезти{}, // Вывезли в Китай. rus_verbs:пропихивать{}, // Я очень аккуратно пропихивал дуло в ноздрю. rus_verbs:пропихнуть{}, rus_verbs:транспортироваться{}, rus_verbs:закрадываться{}, // в голову начали закрадываться кое-какие сомнения и подозрения rus_verbs:дуть{}, rus_verbs:БОГАТЕТЬ{}, // rus_verbs:РАЗБОГАТЕТЬ{}, // rus_verbs:ВОЗРАСТАТЬ{}, // rus_verbs:ВОЗРАСТИ{}, // rus_verbs:ПОДНЯТЬ{}, // Он поднял половинку самолета в воздух и на всей скорости повел ее к горам. (ПОДНЯТЬ) rus_verbs:ОТКАТИТЬСЯ{}, // Услышав за спиной дыхание, он прыгнул вперед и откатился в сторону, рассчитывая ускользнуть от врага, нападавшего сзади (ОТКАТИТЬСЯ) rus_verbs:ВПЛЕТАТЬСЯ{}, // В общий смрад вплеталось зловонье пены, летевшей из пастей, и крови из легких (ВПЛЕТАТЬСЯ) rus_verbs:ЗАМАНИТЬ{}, // Они подумали, что Павел пытается заманить их в зону обстрела. (ЗАМАНИТЬ,ЗАМАНИВАТЬ) rus_verbs:ЗАМАНИВАТЬ{}, rus_verbs:ПРОТРУБИТЬ{}, // Эти врата откроются, когда он протрубит в рог, и пропустят его в другую вселенную. (ПРОТРУБИТЬ) rus_verbs:ВРУБИТЬСЯ{}, // Клинок сломался, не врубившись в металл. (ВРУБИТЬСЯ/ВРУБАТЬСЯ) rus_verbs:ВРУБАТЬСЯ{}, rus_verbs:ОТПРАВИТЬ{}, // Мы ищем благородного вельможу, который нанял бы нас или отправил в рыцарский поиск. (ОТПРАВИТЬ) rus_verbs:ОБЛАЧИТЬ{}, // Этот был облачен в сверкавшие красные доспехи с опущенным забралом и держал огромное копье, дожидаясь своей очереди. (ОБЛАЧИТЬ/ОБЛАЧАТЬ/ОБЛАЧИТЬСЯ/ОБЛАЧАТЬСЯ/НАРЯДИТЬСЯ/НАРЯЖАТЬСЯ) rus_verbs:ОБЛАЧАТЬ{}, rus_verbs:ОБЛАЧИТЬСЯ{}, rus_verbs:ОБЛАЧАТЬСЯ{}, rus_verbs:НАРЯДИТЬСЯ{}, rus_verbs:НАРЯЖАТЬСЯ{}, rus_verbs:ЗАХВАТИТЬ{}, // Кроме набранного рабского материала обычного типа, он захватил в плен группу очень странных созданий, а также женщину исключительной красоты (ЗАХВАТИТЬ/ЗАХВАТЫВАТЬ/ЗАХВАТ) rus_verbs:ЗАХВАТЫВАТЬ{}, rus_verbs:ПРОВЕСТИ{}, // Он провел их в маленькое святилище позади штурвала. (ПРОВЕСТИ) rus_verbs:ПОЙМАТЬ{}, // Их можно поймать в ловушку (ПОЙМАТЬ) rus_verbs:СТРОИТЬСЯ{}, // На вершине они остановились, строясь в круг. (СТРОИТЬСЯ,ПОСТРОИТЬСЯ,ВЫСТРОИТЬСЯ) rus_verbs:ПОСТРОИТЬСЯ{}, rus_verbs:ВЫСТРОИТЬСЯ{}, rus_verbs:ВЫПУСТИТЬ{}, // Несколько стрел, выпущенных в преследуемых, вонзились в траву (ВЫПУСТИТЬ/ВЫПУСКАТЬ) rus_verbs:ВЫПУСКАТЬ{}, rus_verbs:ВЦЕПЛЯТЬСЯ{}, // Они вцепляются тебе в горло. (ВЦЕПЛЯТЬСЯ/ВЦЕПИТЬСЯ) rus_verbs:ВЦЕПИТЬСЯ{}, rus_verbs:ПАЛЬНУТЬ{}, // Вольф вставил в тетиву новую стрелу и пальнул в белое брюхо (ПАЛЬНУТЬ) rus_verbs:ОТСТУПИТЬ{}, // Вольф отступил в щель. (ОТСТУПИТЬ/ОТСТУПАТЬ) rus_verbs:ОТСТУПАТЬ{}, rus_verbs:КРИКНУТЬ{}, // Вольф крикнул в ответ и медленно отступил от птицы. (КРИКНУТЬ) rus_verbs:ДЫХНУТЬ{}, // В лицо ему дыхнули винным перегаром. (ДЫХНУТЬ) rus_verbs:ПОТРУБИТЬ{}, // Я видел рог во время своих скитаний по дворцу и даже потрубил в него (ПОТРУБИТЬ) rus_verbs:ОТКРЫВАТЬСЯ{}, // Некоторые врата открывались в другие вселенные (ОТКРЫВАТЬСЯ) rus_verbs:ТРУБИТЬ{}, // А я трубил в рог (ТРУБИТЬ) rus_verbs:ПЫРНУТЬ{}, // Вольф пырнул его в бок. (ПЫРНУТЬ) rus_verbs:ПРОСКРЕЖЕТАТЬ{}, // Тот что-то проскрежетал в ответ, а затем наорал на него. (ПРОСКРЕЖЕТАТЬ В вин, НАОРАТЬ НА вин) rus_verbs:ИМПОРТИРОВАТЬ{}, // импортировать товары двойного применения только в Российскую Федерацию (ИМПОРТИРОВАТЬ) rus_verbs:ОТЪЕХАТЬ{}, // Легкий грохот катков заглушил рог, когда дверь отъехала в сторону. (ОТЪЕХАТЬ) rus_verbs:ПОПЛЕСТИСЬ{}, // Подобрав нижнее белье, носки и ботинки, он поплелся по песку обратно в джунгли. (ПОПЛЕЛСЯ) rus_verbs:СЖАТЬСЯ{}, // Желудок у него сжался в кулак. (СЖАТЬСЯ, СЖИМАТЬСЯ) rus_verbs:СЖИМАТЬСЯ{}, rus_verbs:проверять{}, // Школьников будут принудительно проверять на курение rus_verbs:ПОТЯНУТЬ{}, // Я потянул его в кино (ПОТЯНУТЬ) rus_verbs:ПЕРЕВЕСТИ{}, // Премьер-министр Казахстана поручил до конца года перевести все социально-значимые услуги в электронный вид (ПЕРЕВЕСТИ) rus_verbs:КРАСИТЬ{}, // Почему китайские партийные боссы красят волосы в черный цвет? (КРАСИТЬ/ПОКРАСИТЬ/ПЕРЕКРАСИТЬ/ОКРАСИТЬ/ЗАКРАСИТЬ) rus_verbs:ПОКРАСИТЬ{}, // rus_verbs:ПЕРЕКРАСИТЬ{}, // rus_verbs:ОКРАСИТЬ{}, // rus_verbs:ЗАКРАСИТЬ{}, // rus_verbs:СООБЩИТЬ{}, // Мужчина ранил человека в щеку и сам сообщил об этом в полицию (СООБЩИТЬ) rus_verbs:СТЯГИВАТЬ{}, // Но толщина пузыря постоянно меняется из-за гравитации, которая стягивает жидкость в нижнюю часть (СТЯГИВАТЬ/СТЯНУТЬ/ЗАТЯНУТЬ/ВТЯНУТЬ) rus_verbs:СТЯНУТЬ{}, // rus_verbs:ЗАТЯНУТЬ{}, // rus_verbs:ВТЯНУТЬ{}, // rus_verbs:СОХРАНИТЬ{}, // сохранить данные в файл (СОХРАНИТЬ) деепричастие:придя{}, // Немного придя в себя rus_verbs:наблюдать{}, // Судья , долго наблюдавший в трубу , вдруг вскричал rus_verbs:УЛЫБАТЬСЯ{}, // она улыбалась во весь рот (УЛЫБАТЬСЯ) rus_verbs:МЕТНУТЬСЯ{}, // она метнулась обратно во тьму (МЕТНУТЬСЯ) rus_verbs:ПОСЛЕДОВАТЬ{}, // большинство жителей города последовало за ним во дворец (ПОСЛЕДОВАТЬ) rus_verbs:ПЕРЕМЕЩАТЬСЯ{}, // экстремисты перемещаются из лесов в Сеть (ПЕРЕМЕЩАТЬСЯ) rus_verbs:ВЫТАЩИТЬ{}, // Алексей позволил вытащить себя через дверь во тьму (ВЫТАЩИТЬ) rus_verbs:СЫПАТЬСЯ{}, // внизу под ними камни градом сыпались во двор (СЫПАТЬСЯ) rus_verbs:выезжать{}, // заключенные сами шьют куклы и иногда выезжают с представлениями в детский дом неподалеку rus_verbs:КРИЧАТЬ{}, // ей хотелось кричать во весь голос (КРИЧАТЬ В вин) rus_verbs:ВЫПРЯМИТЬСЯ{}, // волк выпрямился во весь огромный рост (ВЫПРЯМИТЬСЯ В вин) rus_verbs:спрятать{}, // Джон спрятал очки во внутренний карман (спрятать в вин) rus_verbs:ЭКСТРАДИРОВАТЬ{}, // Украина экстрадирует в Таджикистан задержанного бывшего премьер-министра (ЭКСТРАДИРОВАТЬ В вин) rus_verbs:ВВОЗИТЬ{}, // лабораторный мониторинг ввозимой в Россию мясной продукции из США (ВВОЗИТЬ В вин) rus_verbs:УПАКОВАТЬ{}, // упакованных в несколько слоев полиэтилена (УПАКОВАТЬ В вин) rus_verbs:ОТТЯГИВАТЬ{}, // использовать естественную силу гравитации, оттягивая объекты в сторону и изменяя их орбиту (ОТТЯГИВАТЬ В вин) rus_verbs:ПОЗВОНИТЬ{}, // они позвонили в отдел экологии городской администрации (ПОЗВОНИТЬ В) rus_verbs:ПРИВЛЕЧЬ{}, // Открытость данных о лесе поможет привлечь инвестиции в отрасль (ПРИВЛЕЧЬ В) rus_verbs:ЗАПРОСИТЬСЯ{}, // набегавшись и наплясавшись, Стасик утомился и запросился в кроватку (ЗАПРОСИТЬСЯ В) rus_verbs:ОТСТАВИТЬ{}, // бутыль с ацетоном Витька отставил в сторонку (ОТСТАВИТЬ В) rus_verbs:ИСПОЛЬЗОВАТЬ{}, // ты использовал свою магию во зло. (ИСПОЛЬЗОВАТЬ В вин) rus_verbs:ВЫСЕВАТЬ{}, // В апреле редис возможно уже высевать в грунт (ВЫСЕВАТЬ В) rus_verbs:ЗАГНАТЬ{}, // Американский психолог загнал любовь в три угла (ЗАГНАТЬ В) rus_verbs:ЭВОЛЮЦИОНИРОВАТЬ{}, // Почему не все обезьяны эволюционировали в человека? (ЭВОЛЮЦИОНИРОВАТЬ В вин) rus_verbs:СФОТОГРАФИРОВАТЬСЯ{}, // Он сфотографировался во весь рост. (СФОТОГРАФИРОВАТЬСЯ В) rus_verbs:СТАВИТЬ{}, // Он ставит мне в упрёк свою ошибку. (СТАВИТЬ В) rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА) rus_verbs:ПЕРЕСЕЛЯТЬСЯ{}, // Греки переселяются в Германию (ПЕРЕСЕЛЯТЬСЯ В) rus_verbs:ФОРМИРОВАТЬСЯ{}, // Сахарная свекла относится к двулетним растениям, мясистый корнеплод формируется в первый год. (ФОРМИРОВАТЬСЯ В) rus_verbs:ПРОВОРЧАТЬ{}, // дедуля что-то проворчал в ответ (ПРОВОРЧАТЬ В) rus_verbs:БУРКНУТЬ{}, // нелюдимый парень что-то буркнул в ответ (БУРКНУТЬ В) rus_verbs:ВЕСТИ{}, // дверь вела во тьму. (ВЕСТИ В) rus_verbs:ВЫСКОЧИТЬ{}, // беглецы выскочили во двор. (ВЫСКОЧИТЬ В) rus_verbs:ДОСЫЛАТЬ{}, // Одним движением стрелок досылает патрон в ствол (ДОСЫЛАТЬ В) rus_verbs:СЪЕХАТЬСЯ{}, // Финалисты съехались на свои игры в Лос-Анжелес. (СЪЕХАТЬСЯ НА, В) rus_verbs:ВЫТЯНУТЬ{}, // Дым вытянуло в трубу. (ВЫТЯНУТЬ В) rus_verbs:торчать{}, // острые обломки бревен торчали во все стороны. rus_verbs:ОГЛЯДЫВАТЬ{}, // Она оглядывает себя в зеркало. (ОГЛЯДЫВАТЬ В) rus_verbs:ДЕЙСТВОВАТЬ{}, // Этот пакет законов действует в ущерб частным предпринимателям. rus_verbs:РАЗЛЕТЕТЬСЯ{}, // люди разлетелись во все стороны. (РАЗЛЕТЕТЬСЯ В) rus_verbs:брызнуть{}, // во все стороны брызнула кровь. (брызнуть в) rus_verbs:ТЯНУТЬСЯ{}, // провода тянулись во все углы. (ТЯНУТЬСЯ В) rus_verbs:валить{}, // валить все в одну кучу (валить в) rus_verbs:выдвинуть{}, // его выдвинули в палату представителей (выдвинуть в) rus_verbs:карабкаться{}, // карабкаться в гору (карабкаться в) rus_verbs:клониться{}, // он клонился в сторону (клониться в) rus_verbs:командировать{}, // мы командировали нашего представителя в Рим (командировать в) rus_verbs:запасть{}, // Эти слова запали мне в душу. rus_verbs:давать{}, // В этой лавке дают в долг? rus_verbs:ездить{}, // Каждый день грузовик ездит в город. rus_verbs:претвориться{}, // Замысел претворился в жизнь. rus_verbs:разойтись{}, // Они разошлись в разные стороны. rus_verbs:выйти{}, // Охотник вышел в поле с ружьём. rus_verbs:отозвать{}, // Отзовите его в сторону и скажите ему об этом. rus_verbs:расходиться{}, // Маша и Петя расходятся в разные стороны rus_verbs:переодеваться{}, // переодеваться в женское платье rus_verbs:перерастать{}, // перерастать в массовые беспорядки rus_verbs:завязываться{}, // завязываться в узел rus_verbs:похватать{}, // похватать в руки rus_verbs:увлечь{}, // увлечь в прогулку по парку rus_verbs:помещать{}, // помещать в изолятор rus_verbs:зыркнуть{}, // зыркнуть в окошко rus_verbs:закатать{}, // закатать в асфальт rus_verbs:усаживаться{}, // усаживаться в кресло rus_verbs:загонять{}, // загонять в сарай rus_verbs:подбрасывать{}, // подбрасывать в воздух rus_verbs:телеграфировать{}, // телеграфировать в центр rus_verbs:вязать{}, // вязать в стопы rus_verbs:подлить{}, // подлить в огонь rus_verbs:заполучить{}, // заполучить в распоряжение rus_verbs:подогнать{}, // подогнать в док rus_verbs:ломиться{}, // ломиться в открытую дверь rus_verbs:переправить{}, // переправить в деревню rus_verbs:затягиваться{}, // затягиваться в трубу rus_verbs:разлетаться{}, // разлетаться в стороны rus_verbs:кланяться{}, // кланяться в ножки rus_verbs:устремляться{}, // устремляться в открытое море rus_verbs:переместиться{}, // переместиться в другую аудиторию rus_verbs:ложить{}, // ложить в ящик rus_verbs:отвозить{}, // отвозить в аэропорт rus_verbs:напрашиваться{}, // напрашиваться в гости rus_verbs:напроситься{}, // напроситься в гости rus_verbs:нагрянуть{}, // нагрянуть в гости rus_verbs:заворачивать{}, // заворачивать в фольгу rus_verbs:заковать{}, // заковать в кандалы rus_verbs:свезти{}, // свезти в сарай rus_verbs:притащиться{}, // притащиться в дом rus_verbs:завербовать{}, // завербовать в разведку rus_verbs:рубиться{}, // рубиться в компьютерные игры rus_verbs:тыкаться{}, // тыкаться в материнскую грудь инфинитив:ссыпать{ вид:несоверш }, инфинитив:ссыпать{ вид:соверш }, // ссыпать в контейнер глагол:ссыпать{ вид:несоверш }, глагол:ссыпать{ вид:соверш }, деепричастие:ссыпав{}, деепричастие:ссыпая{}, rus_verbs:засасывать{}, // засасывать в себя rus_verbs:скакнуть{}, // скакнуть в будущее rus_verbs:подвозить{}, // подвозить в театр rus_verbs:переиграть{}, // переиграть в покер rus_verbs:мобилизовать{}, // мобилизовать в действующую армию rus_verbs:залетать{}, // залетать в закрытое воздушное пространство rus_verbs:подышать{}, // подышать в трубочку rus_verbs:смотаться{}, // смотаться в институт rus_verbs:рассовать{}, // рассовать в кармашки rus_verbs:захаживать{}, // захаживать в дом инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять в ломбард деепричастие:сгоняя{}, rus_verbs:посылаться{}, // посылаться в порт rus_verbs:отлить{}, // отлить в кастрюлю rus_verbs:преобразоваться{}, // преобразоваться в линейное уравнение rus_verbs:поплакать{}, // поплакать в платочек rus_verbs:обуться{}, // обуться в сапоги rus_verbs:закапать{}, // закапать в глаза инфинитив:свозить{ вид:несоверш }, инфинитив:свозить{ вид:соверш }, // свозить в центр утилизации глагол:свозить{ вид:несоверш }, глагол:свозить{ вид:соверш }, деепричастие:свозив{}, деепричастие:свозя{}, rus_verbs:преобразовать{}, // преобразовать в линейное уравнение rus_verbs:кутаться{}, // кутаться в плед rus_verbs:смещаться{}, // смещаться в сторону rus_verbs:зазывать{}, // зазывать в свой магазин инфинитив:трансформироваться{ вид:несоверш }, инфинитив:трансформироваться{ вид:соверш }, // трансформироваться в комбинезон глагол:трансформироваться{ вид:несоверш }, глагол:трансформироваться{ вид:соверш }, деепричастие:трансформируясь{}, деепричастие:трансформировавшись{}, rus_verbs:погружать{}, // погружать в кипящее масло rus_verbs:обыграть{}, // обыграть в теннис rus_verbs:закутать{}, // закутать в одеяло rus_verbs:изливаться{}, // изливаться в воду rus_verbs:закатывать{}, // закатывать в асфальт rus_verbs:мотнуться{}, // мотнуться в банк rus_verbs:избираться{}, // избираться в сенат rus_verbs:наниматься{}, // наниматься в услужение rus_verbs:настучать{}, // настучать в органы rus_verbs:запихивать{}, // запихивать в печку rus_verbs:закапывать{}, // закапывать в нос rus_verbs:засобираться{}, // засобираться в поход rus_verbs:копировать{}, // копировать в другую папку rus_verbs:замуровать{}, // замуровать в стену rus_verbs:упечь{}, // упечь в тюрьму rus_verbs:зрить{}, // зрить в корень rus_verbs:стягиваться{}, // стягиваться в одну точку rus_verbs:усаживать{}, // усаживать в тренажер rus_verbs:протолкнуть{}, // протолкнуть в отверстие rus_verbs:расшибиться{}, // расшибиться в лепешку rus_verbs:приглашаться{}, // приглашаться в кабинет rus_verbs:садить{}, // садить в телегу rus_verbs:уткнуть{}, // уткнуть в подушку rus_verbs:протечь{}, // протечь в подвал rus_verbs:перегнать{}, // перегнать в другую страну rus_verbs:переползти{}, // переползти в тень rus_verbs:зарываться{}, // зарываться в грунт rus_verbs:переодеть{}, // переодеть в сухую одежду rus_verbs:припуститься{}, // припуститься в пляс rus_verbs:лопотать{}, // лопотать в микрофон rus_verbs:прогнусавить{}, // прогнусавить в микрофон rus_verbs:мочиться{}, // мочиться в штаны rus_verbs:загружать{}, // загружать в патронник rus_verbs:радировать{}, // радировать в центр rus_verbs:промотать{}, // промотать в конец rus_verbs:помчать{}, // помчать в школу rus_verbs:съезжать{}, // съезжать в кювет rus_verbs:завозить{}, // завозить в магазин rus_verbs:заявляться{}, // заявляться в школу rus_verbs:наглядеться{}, // наглядеться в зеркало rus_verbs:сворачиваться{}, // сворачиваться в клубочек rus_verbs:устремлять{}, // устремлять взор в будущее rus_verbs:забредать{}, // забредать в глухие уголки rus_verbs:перемотать{}, // перемотать в самое начало диалога rus_verbs:сморкаться{}, // сморкаться в носовой платочек rus_verbs:перетекать{}, // перетекать в другой сосуд rus_verbs:закачать{}, // закачать в шарик rus_verbs:запрятать{}, // запрятать в сейф rus_verbs:пинать{}, // пинать в живот rus_verbs:затрубить{}, // затрубить в горн rus_verbs:подглядывать{}, // подглядывать в замочную скважину инфинитив:подсыпать{ вид:соверш }, инфинитив:подсыпать{ вид:несоверш }, // подсыпать в питье глагол:подсыпать{ вид:соверш }, глагол:подсыпать{ вид:несоверш }, деепричастие:подсыпав{}, деепричастие:подсыпая{}, rus_verbs:засовывать{}, // засовывать в пенал rus_verbs:отрядить{}, // отрядить в командировку rus_verbs:справлять{}, // справлять в кусты rus_verbs:поторапливаться{}, // поторапливаться в самолет rus_verbs:скопировать{}, // скопировать в кэш rus_verbs:подливать{}, // подливать в огонь rus_verbs:запрячь{}, // запрячь в повозку rus_verbs:окраситься{}, // окраситься в пурпур rus_verbs:уколоть{}, // уколоть в шею rus_verbs:слететься{}, // слететься в гнездо rus_verbs:резаться{}, // резаться в карты rus_verbs:затесаться{}, // затесаться в ряды оппозиционеров инфинитив:задвигать{ вид:несоверш }, глагол:задвигать{ вид:несоверш }, // задвигать в ячейку (несоверш) деепричастие:задвигая{}, rus_verbs:доставляться{}, // доставляться в ресторан rus_verbs:поплевать{}, // поплевать в чашку rus_verbs:попереться{}, // попереться в магазин rus_verbs:хаживать{}, // хаживать в церковь rus_verbs:преображаться{}, // преображаться в королеву rus_verbs:организоваться{}, // организоваться в группу rus_verbs:ужалить{}, // ужалить в руку rus_verbs:протискиваться{}, // протискиваться в аудиторию rus_verbs:препроводить{}, // препроводить в закуток rus_verbs:разъезжаться{}, // разъезжаться в разные стороны rus_verbs:пропыхтеть{}, // пропыхтеть в трубку rus_verbs:уволочь{}, // уволочь в нору rus_verbs:отодвигаться{}, // отодвигаться в сторону rus_verbs:разливать{}, // разливать в стаканы rus_verbs:сбегаться{}, // сбегаться в актовый зал rus_verbs:наведаться{}, // наведаться в кладовку rus_verbs:перекочевать{}, // перекочевать в горы rus_verbs:прощебетать{}, // прощебетать в трубку rus_verbs:перекладывать{}, // перекладывать в другой карман rus_verbs:углубляться{}, // углубляться в теорию rus_verbs:переименовать{}, // переименовать в город rus_verbs:переметнуться{}, // переметнуться в лагерь противника rus_verbs:разносить{}, // разносить в щепки rus_verbs:осыпаться{}, // осыпаться в холода rus_verbs:попроситься{}, // попроситься в туалет rus_verbs:уязвить{}, // уязвить в сердце rus_verbs:перетащить{}, // перетащить в дом rus_verbs:закутаться{}, // закутаться в плед // rus_verbs:упаковать{}, // упаковать в бумагу инфинитив:тикать{ aux stress="тик^ать" }, глагол:тикать{ aux stress="тик^ать" }, // тикать в крепость rus_verbs:хихикать{}, // хихикать в кулачок rus_verbs:объединить{}, // объединить в сеть инфинитив:слетать{ вид:соверш }, глагол:слетать{ вид:соверш }, // слетать в Калифорнию деепричастие:слетав{}, rus_verbs:заползти{}, // заползти в норку rus_verbs:перерасти{}, // перерасти в крупную аферу rus_verbs:списать{}, // списать в утиль rus_verbs:просачиваться{}, // просачиваться в бункер rus_verbs:пускаться{}, // пускаться в погоню rus_verbs:согревать{}, // согревать в мороз rus_verbs:наливаться{}, // наливаться в емкость rus_verbs:унестись{}, // унестись в небо rus_verbs:зашвырнуть{}, // зашвырнуть в шкаф rus_verbs:сигануть{}, // сигануть в воду rus_verbs:окунуть{}, // окунуть в ледяную воду rus_verbs:просочиться{}, // просочиться в сапог rus_verbs:соваться{}, // соваться в толпу rus_verbs:протолкаться{}, // протолкаться в гардероб rus_verbs:заложить{}, // заложить в ломбард rus_verbs:перекатить{}, // перекатить в сарай rus_verbs:поставлять{}, // поставлять в Китай rus_verbs:залезать{}, // залезать в долги rus_verbs:отлучаться{}, // отлучаться в туалет rus_verbs:сбиваться{}, // сбиваться в кучу rus_verbs:зарыть{}, // зарыть в землю rus_verbs:засадить{}, // засадить в тело rus_verbs:прошмыгнуть{}, // прошмыгнуть в дверь rus_verbs:переставить{}, // переставить в шкаф rus_verbs:отчалить{}, // отчалить в плавание rus_verbs:набираться{}, // набираться в команду rus_verbs:лягнуть{}, // лягнуть в живот rus_verbs:притворить{}, // притворить в жизнь rus_verbs:проковылять{}, // проковылять в гардероб rus_verbs:прикатить{}, // прикатить в гараж rus_verbs:залететь{}, // залететь в окно rus_verbs:переделать{}, // переделать в мопед rus_verbs:протащить{}, // протащить в совет rus_verbs:обмакнуть{}, // обмакнуть в воду rus_verbs:отклоняться{}, // отклоняться в сторону rus_verbs:запихать{}, // запихать в пакет rus_verbs:избирать{}, // избирать в совет rus_verbs:загрузить{}, // загрузить в буфер rus_verbs:уплывать{}, // уплывать в Париж rus_verbs:забивать{}, // забивать в мерзлоту rus_verbs:потыкать{}, // потыкать в безжизненную тушу rus_verbs:съезжаться{}, // съезжаться в санаторий rus_verbs:залепить{}, // залепить в рыло rus_verbs:набиться{}, // набиться в карманы rus_verbs:уползти{}, // уползти в нору rus_verbs:упрятать{}, // упрятать в камеру rus_verbs:переместить{}, // переместить в камеру анабиоза rus_verbs:закрасться{}, // закрасться в душу rus_verbs:сместиться{}, // сместиться в инфракрасную область rus_verbs:запускать{}, // запускать в серию rus_verbs:потрусить{}, // потрусить в чащобу rus_verbs:забрасывать{}, // забрасывать в чистую воду rus_verbs:переселить{}, // переселить в отдаленную деревню rus_verbs:переезжать{}, // переезжать в новую квартиру rus_verbs:приподнимать{}, // приподнимать в воздух rus_verbs:добавиться{}, // добавиться в конец очереди rus_verbs:убыть{}, // убыть в часть rus_verbs:передвигать{}, // передвигать в соседнюю клетку rus_verbs:добавляться{}, // добавляться в очередь rus_verbs:дописать{}, // дописать в перечень rus_verbs:записываться{}, // записываться в кружок rus_verbs:продаться{}, // продаться в кредитное рабство rus_verbs:переписывать{}, // переписывать в тетрадку rus_verbs:заплыть{}, // заплыть в территориальные воды инфинитив:пописать{ aux stress="поп^исать" }, инфинитив:пописать{ aux stress="попис^ать" }, // пописать в горшок глагол:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="попис^ать" }, rus_verbs:отбирать{}, // отбирать в гвардию rus_verbs:нашептывать{}, // нашептывать в микрофон rus_verbs:ковылять{}, // ковылять в стойло rus_verbs:прилетать{}, // прилетать в Париж rus_verbs:пролиться{}, // пролиться в канализацию rus_verbs:запищать{}, // запищать в микрофон rus_verbs:подвезти{}, // подвезти в больницу rus_verbs:припереться{}, // припереться в театр rus_verbs:утечь{}, // утечь в сеть rus_verbs:прорываться{}, // прорываться в буфет rus_verbs:увозить{}, // увозить в ремонт rus_verbs:съедать{}, // съедать в обед rus_verbs:просунуться{}, // просунуться в дверь rus_verbs:перенестись{}, // перенестись в прошлое rus_verbs:завезти{}, // завезти в магазин rus_verbs:проложить{}, // проложить в деревню rus_verbs:объединяться{}, // объединяться в профсоюз rus_verbs:развиться{}, // развиться в бабочку rus_verbs:засеменить{}, // засеменить в кабинку rus_verbs:скатываться{}, // скатываться в яму rus_verbs:завозиться{}, // завозиться в магазин rus_verbs:нанимать{}, // нанимать в рейс rus_verbs:поспеть{}, // поспеть в класс rus_verbs:кидаться{}, // кинаться в крайности rus_verbs:поспевать{}, // поспевать в оперу rus_verbs:обернуть{}, // обернуть в фольгу rus_verbs:обратиться{}, // обратиться в прокуратуру rus_verbs:истолковать{}, // истолковать в свою пользу rus_verbs:таращиться{}, // таращиться в дисплей rus_verbs:прыснуть{}, // прыснуть в кулачок rus_verbs:загнуть{}, // загнуть в другую сторону rus_verbs:раздать{}, // раздать в разные руки rus_verbs:назначить{}, // назначить в приемную комиссию rus_verbs:кидать{}, // кидать в кусты rus_verbs:увлекать{}, // увлекать в лес rus_verbs:переселиться{}, // переселиться в чужое тело rus_verbs:присылать{}, // присылать в город rus_verbs:уплыть{}, // уплыть в Европу rus_verbs:запричитать{}, // запричитать в полный голос rus_verbs:утащить{}, // утащить в логово rus_verbs:завернуться{}, // завернуться в плед rus_verbs:заносить{}, // заносить в блокнот rus_verbs:пятиться{}, // пятиться в дом rus_verbs:наведываться{}, // наведываться в больницу rus_verbs:нырять{}, // нырять в прорубь rus_verbs:зачастить{}, // зачастить в бар rus_verbs:назначаться{}, // назначается в комиссию rus_verbs:мотаться{}, // мотаться в областной центр rus_verbs:разыграть{}, // разыграть в карты rus_verbs:пропищать{}, // пропищать в микрофон rus_verbs:пихнуть{}, // пихнуть в бок rus_verbs:эмигрировать{}, // эмигрировать в Канаду rus_verbs:подключить{}, // подключить в сеть rus_verbs:упереть{}, // упереть в фундамент rus_verbs:уплатить{}, // уплатить в кассу rus_verbs:потащиться{}, // потащиться в медпункт rus_verbs:пригнать{}, // пригнать в стойло rus_verbs:оттеснить{}, // оттеснить в фойе rus_verbs:стучаться{}, // стучаться в ворота rus_verbs:перечислить{}, // перечислить в фонд rus_verbs:сомкнуть{}, // сомкнуть в круг rus_verbs:закачаться{}, // закачаться в резервуар rus_verbs:кольнуть{}, // кольнуть в бок rus_verbs:накрениться{}, // накрениться в сторону берега rus_verbs:подвинуться{}, // подвинуться в другую сторону rus_verbs:разнести{}, // разнести в клочья rus_verbs:отливать{}, // отливать в форму rus_verbs:подкинуть{}, // подкинуть в карман rus_verbs:уводить{}, // уводить в кабинет rus_verbs:ускакать{}, // ускакать в школу rus_verbs:ударять{}, // ударять в барабаны rus_verbs:даться{}, // даться в руки rus_verbs:поцеловаться{}, // поцеловаться в губы rus_verbs:посветить{}, // посветить в подвал rus_verbs:тыкать{}, // тыкать в арбуз rus_verbs:соединяться{}, // соединяться в кольцо rus_verbs:растянуть{}, // растянуть в тонкую ниточку rus_verbs:побросать{}, // побросать в пыль rus_verbs:стукнуться{}, // стукнуться в закрытую дверь rus_verbs:проигрывать{}, // проигрывать в теннис rus_verbs:дунуть{}, // дунуть в трубочку rus_verbs:улетать{}, // улетать в Париж rus_verbs:переводиться{}, // переводиться в филиал rus_verbs:окунуться{}, // окунуться в водоворот событий rus_verbs:попрятаться{}, // попрятаться в норы rus_verbs:перевезти{}, // перевезти в соседнюю палату rus_verbs:топать{}, // топать в школу rus_verbs:относить{}, // относить в помещение rus_verbs:укладывать{}, // укладывать в стопку rus_verbs:укатить{}, // укатил в турне rus_verbs:убирать{}, // убирать в сумку rus_verbs:помалкивать{}, // помалкивать в тряпочку rus_verbs:ронять{}, // ронять в грязь rus_verbs:глазеть{}, // глазеть в бинокль rus_verbs:преобразиться{}, // преобразиться в другого человека rus_verbs:запрыгнуть{}, // запрыгнуть в поезд rus_verbs:сгодиться{}, // сгодиться в суп rus_verbs:проползти{}, // проползти в нору rus_verbs:забираться{}, // забираться в коляску rus_verbs:сбежаться{}, // сбежались в класс rus_verbs:закатиться{}, // закатиться в угол rus_verbs:плевать{}, // плевать в душу rus_verbs:поиграть{}, // поиграть в демократию rus_verbs:кануть{}, // кануть в небытие rus_verbs:опаздывать{}, // опаздывать в школу rus_verbs:отползти{}, // отползти в сторону rus_verbs:стекаться{}, // стекаться в отстойник rus_verbs:запихнуть{}, // запихнуть в пакет rus_verbs:вышвырнуть{}, // вышвырнуть в коридор rus_verbs:связываться{}, // связываться в плотный узел rus_verbs:затолкать{}, // затолкать в ухо rus_verbs:скрутить{}, // скрутить в трубочку rus_verbs:сворачивать{}, // сворачивать в трубочку rus_verbs:сплестись{}, // сплестись в узел rus_verbs:заскочить{}, // заскочить в кабинет rus_verbs:проваливаться{}, // проваливаться в сон rus_verbs:уверовать{}, // уверовать в свою безнаказанность rus_verbs:переписать{}, // переписать в тетрадку rus_verbs:переноситься{}, // переноситься в мир фантазий rus_verbs:заводить{}, // заводить в помещение rus_verbs:сунуться{}, // сунуться в аудиторию rus_verbs:устраиваться{}, // устраиваться в автомастерскую rus_verbs:пропускать{}, // пропускать в зал инфинитив:сбегать{ вид:несоверш }, инфинитив:сбегать{ вид:соверш }, // сбегать в кино глагол:сбегать{ вид:несоверш }, глагол:сбегать{ вид:соверш }, деепричастие:сбегая{}, деепричастие:сбегав{}, rus_verbs:прибегать{}, // прибегать в школу rus_verbs:съездить{}, // съездить в лес rus_verbs:захлопать{}, // захлопать в ладошки rus_verbs:опрокинуться{}, // опрокинуться в грязь инфинитив:насыпать{ вид:несоверш }, инфинитив:насыпать{ вид:соверш }, // насыпать в стакан глагол:насыпать{ вид:несоверш }, глагол:насыпать{ вид:соверш }, деепричастие:насыпая{}, деепричастие:насыпав{}, rus_verbs:употреблять{}, // употреблять в пищу rus_verbs:приводиться{}, // приводиться в действие rus_verbs:пристроить{}, // пристроить в надежные руки rus_verbs:юркнуть{}, // юркнуть в нору rus_verbs:объединиться{}, // объединиться в банду rus_verbs:сажать{}, // сажать в одиночку rus_verbs:соединить{}, // соединить в кольцо rus_verbs:забрести{}, // забрести в кафешку rus_verbs:свернуться{}, // свернуться в клубочек rus_verbs:пересесть{}, // пересесть в другой автобус rus_verbs:постучаться{}, // постучаться в дверцу rus_verbs:соединять{}, // соединять в кольцо rus_verbs:приволочь{}, // приволочь в коморку rus_verbs:смахивать{}, // смахивать в ящик стола rus_verbs:забежать{}, // забежать в помещение rus_verbs:целиться{}, // целиться в беглеца rus_verbs:прокрасться{}, // прокрасться в хранилище rus_verbs:заковылять{}, // заковылять в травтамологию rus_verbs:прискакать{}, // прискакать в стойло rus_verbs:колотить{}, // колотить в дверь rus_verbs:смотреться{}, // смотреться в зеркало rus_verbs:подложить{}, // подложить в салон rus_verbs:пущать{}, // пущать в королевские покои rus_verbs:согнуть{}, // согнуть в дугу rus_verbs:забарабанить{}, // забарабанить в дверь rus_verbs:отклонить{}, // отклонить в сторону посадочной полосы rus_verbs:убраться{}, // убраться в специальную нишу rus_verbs:насмотреться{}, // насмотреться в зеркало rus_verbs:чмокнуть{}, // чмокнуть в щечку rus_verbs:усмехаться{}, // усмехаться в бороду rus_verbs:передвинуть{}, // передвинуть в конец очереди rus_verbs:допускаться{}, // допускаться в опочивальню rus_verbs:задвинуть{}, // задвинуть в дальний угол rus_verbs:отправлять{}, // отправлять в центр rus_verbs:сбрасывать{}, // сбрасывать в жерло rus_verbs:расстреливать{}, // расстреливать в момент обнаружения rus_verbs:заволочь{}, // заволочь в закуток rus_verbs:пролить{}, // пролить в воду rus_verbs:зарыться{}, // зарыться в сено rus_verbs:переливаться{}, // переливаться в емкость rus_verbs:затащить{}, // затащить в клуб rus_verbs:перебежать{}, // перебежать в лагерь врагов rus_verbs:одеть{}, // одеть в новое платье инфинитив:задвигаться{ вид:несоверш }, глагол:задвигаться{ вид:несоверш }, // задвигаться в нишу деепричастие:задвигаясь{}, rus_verbs:клюнуть{}, // клюнуть в темечко rus_verbs:наливать{}, // наливать в кружку rus_verbs:пролезть{}, // пролезть в ушко rus_verbs:откладывать{}, // откладывать в ящик rus_verbs:протянуться{}, // протянуться в соседний дом rus_verbs:шлепнуться{}, // шлепнуться лицом в грязь rus_verbs:устанавливать{}, // устанавливать в машину rus_verbs:употребляться{}, // употребляться в пищу rus_verbs:переключиться{}, // переключиться в реверсный режим rus_verbs:пискнуть{}, // пискнуть в микрофон rus_verbs:заявиться{}, // заявиться в класс rus_verbs:налиться{}, // налиться в стакан rus_verbs:заливать{}, // заливать в бак rus_verbs:ставиться{}, // ставиться в очередь инфинитив:писаться{ aux stress="п^исаться" }, глагол:писаться{ aux stress="п^исаться" }, // писаться в штаны деепричастие:писаясь{}, rus_verbs:целоваться{}, // целоваться в губы rus_verbs:наносить{}, // наносить в область сердца rus_verbs:посмеяться{}, // посмеяться в кулачок rus_verbs:употребить{}, // употребить в пищу rus_verbs:прорваться{}, // прорваться в столовую rus_verbs:укладываться{}, // укладываться в ровные стопки rus_verbs:пробиться{}, // пробиться в финал rus_verbs:забить{}, // забить в землю rus_verbs:переложить{}, // переложить в другой карман rus_verbs:опускать{}, // опускать в свежевырытую могилу rus_verbs:поторопиться{}, // поторопиться в школу rus_verbs:сдвинуться{}, // сдвинуться в сторону rus_verbs:капать{}, // капать в смесь rus_verbs:погружаться{}, // погружаться во тьму rus_verbs:направлять{}, // направлять в кабинку rus_verbs:погрузить{}, // погрузить во тьму rus_verbs:примчаться{}, // примчаться в школу rus_verbs:упираться{}, // упираться в дверь rus_verbs:удаляться{}, // удаляться в комнату совещаний rus_verbs:ткнуться{}, // ткнуться в окошко rus_verbs:убегать{}, // убегать в чащу rus_verbs:соединиться{}, // соединиться в необычную пространственную фигуру rus_verbs:наговорить{}, // наговорить в микрофон rus_verbs:переносить{}, // переносить в дом rus_verbs:прилечь{}, // прилечь в кроватку rus_verbs:поворачивать{}, // поворачивать в обратную сторону rus_verbs:проскочить{}, // проскочить в щель rus_verbs:совать{}, // совать в духовку rus_verbs:переодеться{}, // переодеться в чистую одежду rus_verbs:порвать{}, // порвать в лоскуты rus_verbs:завязать{}, // завязать в бараний рог rus_verbs:съехать{}, // съехать в кювет rus_verbs:литься{}, // литься в канистру rus_verbs:уклониться{}, // уклониться в левую сторону rus_verbs:смахнуть{}, // смахнуть в мусорное ведро rus_verbs:спускать{}, // спускать в шахту rus_verbs:плеснуть{}, // плеснуть в воду rus_verbs:подуть{}, // подуть в угольки rus_verbs:набирать{}, // набирать в команду rus_verbs:хлопать{}, // хлопать в ладошки rus_verbs:ранить{}, // ранить в самое сердце rus_verbs:посматривать{}, // посматривать в иллюминатор rus_verbs:превращать{}, // превращать воду в вино rus_verbs:толкать{}, // толкать в пучину rus_verbs:отбыть{}, // отбыть в расположение части rus_verbs:сгрести{}, // сгрести в карман rus_verbs:удрать{}, // удрать в тайгу rus_verbs:пристроиться{}, // пристроиться в хорошую фирму rus_verbs:сбиться{}, // сбиться в плотную группу rus_verbs:заключать{}, // заключать в объятия rus_verbs:отпускать{}, // отпускать в поход rus_verbs:устремить{}, // устремить взгляд в будущее rus_verbs:обронить{}, // обронить в траву rus_verbs:сливаться{}, // сливаться в речку rus_verbs:стекать{}, // стекать в канаву rus_verbs:свалить{}, // свалить в кучу rus_verbs:подтянуть{}, // подтянуть в кабину rus_verbs:скатиться{}, // скатиться в канаву rus_verbs:проскользнуть{}, // проскользнуть в приоткрытую дверь rus_verbs:заторопиться{}, // заторопиться в буфет rus_verbs:протиснуться{}, // протиснуться в центр толпы rus_verbs:прятать{}, // прятать в укромненькое местечко rus_verbs:пропеть{}, // пропеть в микрофон rus_verbs:углубиться{}, // углубиться в джунгли rus_verbs:сползти{}, // сползти в яму rus_verbs:записывать{}, // записывать в память rus_verbs:расстрелять{}, // расстрелять в упор (наречный оборот В УПОР) rus_verbs:колотиться{}, // колотиться в дверь rus_verbs:просунуть{}, // просунуть в отверстие rus_verbs:провожать{}, // провожать в армию rus_verbs:катить{}, // катить в гараж rus_verbs:поражать{}, // поражать в самое сердце rus_verbs:отлететь{}, // отлететь в дальний угол rus_verbs:закинуть{}, // закинуть в речку rus_verbs:катиться{}, // катиться в пропасть rus_verbs:забросить{}, // забросить в дальний угол rus_verbs:отвезти{}, // отвезти в лагерь rus_verbs:втопить{}, // втопить педаль в пол rus_verbs:втапливать{}, // втапливать педать в пол rus_verbs:утопить{}, // утопить кнопку в панель rus_verbs:напасть{}, // В Пекине участники антияпонских протестов напали на машину посла США rus_verbs:нанять{}, // Босс нанял в службу поддержки еще несколько девушек rus_verbs:переводить{}, // переводить в устойчивую к перегреву форму rus_verbs:баллотировать{}, // претендент был баллотирован в жюри (баллотирован?) rus_verbs:вбухать{}, // Власти вбухали в этой проект много денег rus_verbs:вбухивать{}, // Власти вбухивают в этот проект очень много денег rus_verbs:поскакать{}, // поскакать в атаку rus_verbs:прицелиться{}, // прицелиться в бегущего зайца rus_verbs:прыгать{}, // прыгать в кровать rus_verbs:приглашать{}, // приглашать в дом rus_verbs:понестись{}, // понестись в ворота rus_verbs:заехать{}, // заехать в гаражный бокс rus_verbs:опускаться{}, // опускаться в бездну rus_verbs:переехать{}, // переехать в коттедж rus_verbs:поместить{}, // поместить в карантин rus_verbs:ползти{}, // ползти в нору rus_verbs:добавлять{}, // добавлять в корзину rus_verbs:уткнуться{}, // уткнуться в подушку rus_verbs:продавать{}, // продавать в рабство rus_verbs:спрятаться{}, // Белка спрячется в дупло. rus_verbs:врисовывать{}, // врисовывать новый персонаж в анимацию rus_verbs:воткнуть{}, // воткни вилку в розетку rus_verbs:нести{}, // нести в больницу rus_verbs:воткнуться{}, // вилка воткнулась в сочную котлетку rus_verbs:впаивать{}, // впаивать деталь в плату rus_verbs:впаиваться{}, // деталь впаивается в плату rus_verbs:впархивать{}, // впархивать в помещение rus_verbs:впаять{}, // впаять деталь в плату rus_verbs:впендюривать{}, // впендюривать штукенцию в агрегат rus_verbs:впендюрить{}, // впендюрить штукенцию в агрегат rus_verbs:вперивать{}, // вперивать взгляд в экран rus_verbs:впериваться{}, // впериваться в экран rus_verbs:вперить{}, // вперить взгляд в экран rus_verbs:впериться{}, // впериться в экран rus_verbs:вперять{}, // вперять взгляд в экран rus_verbs:вперяться{}, // вперяться в экран rus_verbs:впечатать{}, // впечатать текст в первую главу rus_verbs:впечататься{}, // впечататься в стену rus_verbs:впечатывать{}, // впечатывать текст в первую главу rus_verbs:впечатываться{}, // впечатываться в стену rus_verbs:впиваться{}, // Хищник впивается в жертву мощными зубами rus_verbs:впитаться{}, // Жидкость впиталась в ткань rus_verbs:впитываться{}, // Жидкость впитывается в ткань rus_verbs:впихивать{}, // Мама впихивает в сумку кусок колбасы rus_verbs:впихиваться{}, // Кусок колбасы впихивается в сумку rus_verbs:впихнуть{}, // Мама впихнула кастрюлю в холодильник rus_verbs:впихнуться{}, // Кастрюля впихнулась в холодильник rus_verbs:вплавиться{}, // Провод вплавился в плату rus_verbs:вплеснуть{}, // вплеснуть краситель в бак rus_verbs:вплести{}, // вплести ленту в волосы rus_verbs:вплестись{}, // вплестись в волосы rus_verbs:вплетать{}, // вплетать ленты в волосы rus_verbs:вплывать{}, // корабль вплывает в порт rus_verbs:вплыть{}, // яхта вплыла в бухту rus_verbs:вползать{}, // дракон вползает в пещеру rus_verbs:вползти{}, // дракон вполз в свою пещеру rus_verbs:впорхнуть{}, // бабочка впорхнула в окно rus_verbs:впрессовать{}, // впрессовать деталь в плиту rus_verbs:впрессоваться{}, // впрессоваться в плиту rus_verbs:впрессовывать{}, // впрессовывать деталь в плиту rus_verbs:впрессовываться{}, // впрессовываться в плиту rus_verbs:впрыгивать{}, // Пассажир впрыгивает в вагон rus_verbs:впрыгнуть{}, // Пассажир впрыгнул в вагон rus_verbs:впрыскивать{}, // Форсунка впрыскивает топливо в цилиндр rus_verbs:впрыскиваться{}, // Топливо впрыскивается форсункой в цилиндр rus_verbs:впрыснуть{}, // Форсунка впрыснула топливную смесь в камеру сгорания rus_verbs:впрягать{}, // впрягать лошадь в телегу rus_verbs:впрягаться{}, // впрягаться в работу rus_verbs:впрячь{}, // впрячь лошадь в телегу rus_verbs:впрячься{}, // впрячься в работу rus_verbs:впускать{}, // впускать посетителей в музей rus_verbs:впускаться{}, // впускаться в помещение rus_verbs:впустить{}, // впустить посетителей в музей rus_verbs:впутать{}, // впутать кого-то во что-то rus_verbs:впутаться{}, // впутаться во что-то rus_verbs:впутывать{}, // впутывать кого-то во что-то rus_verbs:впутываться{}, // впутываться во что-то rus_verbs:врабатываться{}, // врабатываться в режим rus_verbs:вработаться{}, // вработаться в режим rus_verbs:врастать{}, // врастать в кожу rus_verbs:врасти{}, // врасти в кожу инфинитив:врезать{ вид:несоверш }, // врезать замок в дверь инфинитив:врезать{ вид:соверш }, глагол:врезать{ вид:несоверш }, глагол:врезать{ вид:соверш }, деепричастие:врезая{}, деепричастие:врезав{}, прилагательное:врезанный{}, инфинитив:врезаться{ вид:несоверш }, // врезаться в стену инфинитив:врезаться{ вид:соверш }, глагол:врезаться{ вид:несоверш }, деепричастие:врезаясь{}, деепричастие:врезавшись{}, rus_verbs:врубить{}, // врубить в нагрузку rus_verbs:врываться{}, // врываться в здание rus_verbs:закачивать{}, // Насос закачивает топливо в бак rus_verbs:ввезти{}, // Предприятие ввезло товар в страну rus_verbs:вверстать{}, // Дизайнер вверстал блок в страницу rus_verbs:вверстывать{}, // Дизайнер с трудом вверстывает блоки в страницу rus_verbs:вверстываться{}, // Блок тяжело вверстывается в эту страницу rus_verbs:ввивать{}, // Женщина ввивает полоску в косу rus_verbs:вволакиваться{}, // Пойманная мышь вволакивается котиком в дом rus_verbs:вволочь{}, // Кот вволок в дом пойманную крысу rus_verbs:вдергивать{}, // приспособление вдергивает нитку в игольное ушко rus_verbs:вдернуть{}, // приспособление вдернуло нитку в игольное ушко rus_verbs:вдувать{}, // Челоек вдувает воздух в легкие второго человека rus_verbs:вдуваться{}, // Воздух вдувается в легкие человека rus_verbs:вламываться{}, // Полиция вламывается в квартиру rus_verbs:вовлекаться{}, // трудные подростки вовлекаются в занятие спортом rus_verbs:вовлечь{}, // вовлечь трудных подростков в занятие спортом rus_verbs:вовлечься{}, // вовлечься в занятие спортом rus_verbs:спуститься{}, // спуститься в подвал rus_verbs:спускаться{}, // спускаться в подвал rus_verbs:отправляться{}, // отправляться в дальнее плавание инфинитив:эмитировать{ вид:соверш }, // Поверхность эмитирует электроны в пространство инфинитив:эмитировать{ вид:несоверш }, глагол:эмитировать{ вид:соверш }, глагол:эмитировать{ вид:несоверш }, деепричастие:эмитируя{}, деепричастие:эмитировав{}, прилагательное:эмитировавший{ вид:несоверш }, // прилагательное:эмитировавший{ вид:соверш }, прилагательное:эмитирующий{}, прилагательное:эмитируемый{}, прилагательное:эмитированный{}, инфинитив:этапировать{вид:несоверш}, // Преступника этапировали в колонию инфинитив:этапировать{вид:соверш}, глагол:этапировать{вид:несоверш}, глагол:этапировать{вид:соверш}, деепричастие:этапируя{}, прилагательное:этапируемый{}, прилагательное:этапированный{}, rus_verbs:этапироваться{}, // Преступники этапируются в колонию rus_verbs:баллотироваться{}, // они баллотировались в жюри rus_verbs:бежать{}, // Олигарх с семьей любовницы бежал в другую страну rus_verbs:бросать{}, // Они бросали в фонтан медные монетки rus_verbs:бросаться{}, // Дети бросались в воду с моста rus_verbs:бросить{}, // Он бросил в фонтан медную монетку rus_verbs:броситься{}, // самоубийца бросился с моста в воду rus_verbs:превратить{}, // Найден белок, который превратит человека в супергероя rus_verbs:буксировать{}, // Буксир буксирует танкер в порт rus_verbs:буксироваться{}, // Сухогруз буксируется в порт rus_verbs:вбегать{}, // Курьер вбегает в дверь rus_verbs:вбежать{}, // Курьер вбежал в дверь rus_verbs:вбетонировать{}, // Опора была вбетонирована в пол rus_verbs:вбивать{}, // Мастер вбивает штырь в плиту rus_verbs:вбиваться{}, // Штырь вбивается в плиту rus_verbs:вбирать{}, // Вата вбирает в себя влагу rus_verbs:вбить{}, // Ученик вбил в доску маленький гвоздь rus_verbs:вбрасывать{}, // Арбитр вбрасывает мяч в игру rus_verbs:вбрасываться{}, // Мяч вбрасывается в игру rus_verbs:вбросить{}, // Судья вбросил мяч в игру rus_verbs:вбуравиться{}, // Сверло вбуравилось в бетон rus_verbs:вбуравливаться{}, // Сверло вбуравливается в бетон rus_verbs:вбухиваться{}, // Много денег вбухиваются в этот проект rus_verbs:вваливаться{}, // Человек вваливается в кабинет врача rus_verbs:ввалить{}, // Грузчики ввалили мешок в квартиру rus_verbs:ввалиться{}, // Человек ввалился в кабинет терапевта rus_verbs:вваривать{}, // Робот вваривает арматурину в плиту rus_verbs:ввариваться{}, // Арматура вваривается в плиту rus_verbs:вварить{}, // Робот вварил арматурину в плиту rus_verbs:влезть{}, // Предприятие ввезло товар в страну rus_verbs:ввернуть{}, // Вверни новую лампочку в люстру rus_verbs:ввернуться{}, // Лампочка легко ввернулась в патрон rus_verbs:ввертывать{}, // Электрик ввертывает лампочку в патрон rus_verbs:ввертываться{}, // Лампочка легко ввертывается в патрон rus_verbs:вверять{}, // Пациент вверяет свою жизнь в руки врача rus_verbs:вверяться{}, // Пациент вверяется в руки врача rus_verbs:ввести{}, // Агенство ввело своего представителя в совет директоров rus_verbs:ввиваться{}, // полоска ввивается в косу rus_verbs:ввинтить{}, // Отвертка ввинтила шуруп в дерево rus_verbs:ввинтиться{}, // Шуруп ввинтился в дерево rus_verbs:ввинчивать{}, // Рука ввинчивает саморез в стену rus_verbs:ввинчиваться{}, // Саморез ввинчивается в стену rus_verbs:вводить{}, // Агенство вводит своего представителя в совет директоров rus_verbs:вводиться{}, // Представитель агенства вводится в совет директоров // rus_verbs:ввозить{}, // Фирма ввозит в страну станки и сырье rus_verbs:ввозиться{}, // Станки и сырье ввозятся в страну rus_verbs:вволакивать{}, // Пойманная мышь вволакивается котиком в дом rus_verbs:вворачивать{}, // Электрик вворачивает новую лампочку в патрон rus_verbs:вворачиваться{}, // Новая лампочка легко вворачивается в патрон rus_verbs:ввязаться{}, // Разведрота ввязалась в бой rus_verbs:ввязываться{}, // Передовые части ввязываются в бой rus_verbs:вглядеться{}, // Охранник вгляделся в темный коридор rus_verbs:вглядываться{}, // Охранник внимательно вглядывается в монитор rus_verbs:вгонять{}, // Эта музыка вгоняет меня в депрессию rus_verbs:вгрызаться{}, // Зонд вгрызается в поверхность астероида rus_verbs:вгрызться{}, // Зонд вгрызся в поверхность астероида rus_verbs:вдаваться{}, // Вы не должны вдаваться в юридические детали rus_verbs:вдвигать{}, // Робот вдвигает контейнер в ячейку rus_verbs:вдвигаться{}, // Контейнер вдвигается в ячейку rus_verbs:вдвинуть{}, // манипулятор вдвинул деталь в печь rus_verbs:вдвинуться{}, // деталь вдвинулась в печь rus_verbs:вдевать{}, // портниха быстро вдевает нитку в иголку rus_verbs:вдеваться{}, // нитка быстро вдевается в игольное ушко rus_verbs:вдеть{}, // портниха быстро вдела нитку в игольное ушко rus_verbs:вдеться{}, // нитка быстро вделась в игольное ушко rus_verbs:вделать{}, // мастер вделал розетку в стену rus_verbs:вделывать{}, // мастер вделывает выключатель в стену rus_verbs:вделываться{}, // кронштейн вделывается в стену rus_verbs:вдергиваться{}, // нитка легко вдергивается в игольное ушко rus_verbs:вдернуться{}, // нитка легко вдернулась в игольное ушко rus_verbs:вдолбить{}, // Американцы обещали вдолбить страну в каменный век rus_verbs:вдумываться{}, // Мальчик обычно не вдумывался в сюжет фильмов rus_verbs:вдыхать{}, // мы вдыхаем в себя весь этот смог rus_verbs:вдыхаться{}, // Весь этот смог вдыхается в легкие rus_verbs:вернуть{}, // Книгу надо вернуть в библиотеку rus_verbs:вернуться{}, // Дети вернулись в библиотеку rus_verbs:вжаться{}, // Водитель вжался в кресло rus_verbs:вживаться{}, // Актер вживается в новую роль rus_verbs:вживить{}, // Врачи вживили стимулятор в тело пациента rus_verbs:вживиться{}, // Стимулятор вживился в тело пациента rus_verbs:вживлять{}, // Врачи вживляют стимулятор в тело пациента rus_verbs:вживляться{}, // Стимулятор вживляется в тело rus_verbs:вжиматься{}, // Видитель инстинктивно вжимается в кресло rus_verbs:вжиться{}, // Актер вжился в свою новую роль rus_verbs:взвиваться{}, // Воздушный шарик взвивается в небо rus_verbs:взвинтить{}, // Кризис взвинтил цены в небо rus_verbs:взвинтиться{}, // Цены взвинтились в небо rus_verbs:взвинчивать{}, // Кризис взвинчивает цены в небо rus_verbs:взвинчиваться{}, // Цены взвинчиваются в небо rus_verbs:взвиться{}, // Шарики взвились в небо rus_verbs:взлетать{}, // Экспериментальный аппарат взлетает в воздух rus_verbs:взлететь{}, // Экспериментальный аппарат взлетел в небо rus_verbs:взмывать{}, // шарики взмывают в небо rus_verbs:взмыть{}, // Шарики взмыли в небо rus_verbs:вильнуть{}, // Машина вильнула в левую сторону rus_verbs:вкалывать{}, // Медсестра вкалывает иглу в вену rus_verbs:вкалываться{}, // Игла вкалываться прямо в вену rus_verbs:вкапывать{}, // рабочий вкапывает сваю в землю rus_verbs:вкапываться{}, // Свая вкапывается в землю rus_verbs:вкатить{}, // рабочие вкатили бочку в гараж rus_verbs:вкатиться{}, // машина вкатилась в гараж rus_verbs:вкатывать{}, // рабочик вкатывают бочку в гараж rus_verbs:вкатываться{}, // машина вкатывается в гараж rus_verbs:вкачать{}, // Механики вкачали в бак много топлива rus_verbs:вкачивать{}, // Насос вкачивает топливо в бак rus_verbs:вкачиваться{}, // Топливо вкачивается в бак rus_verbs:вкидать{}, // Манипулятор вкидал груз в контейнер rus_verbs:вкидывать{}, // Манипулятор вкидывает груз в контейнер rus_verbs:вкидываться{}, // Груз вкидывается в контейнер rus_verbs:вкладывать{}, // Инвестор вкладывает деньги в акции rus_verbs:вкладываться{}, // Инвестор вкладывается в акции rus_verbs:вклеивать{}, // Мальчик вклеивает картинку в тетрадь rus_verbs:вклеиваться{}, // Картинка вклеивается в тетрадь rus_verbs:вклеить{}, // Мальчик вклеил картинку в тетрадь rus_verbs:вклеиться{}, // Картинка вклеилась в тетрадь rus_verbs:вклепать{}, // Молоток вклепал заклепку в лист rus_verbs:вклепывать{}, // Молоток вклепывает заклепку в лист rus_verbs:вклиниваться{}, // Машина вклинивается в поток rus_verbs:вклиниться{}, // машина вклинилась в поток rus_verbs:включать{}, // Команда включает компьютер в сеть rus_verbs:включаться{}, // Машина включается в глобальную сеть rus_verbs:включить{}, // Команда включила компьютер в сеть rus_verbs:включиться{}, // Компьютер включился в сеть rus_verbs:вколачивать{}, // Столяр вколачивает гвоздь в доску rus_verbs:вколачиваться{}, // Гвоздь вколачивается в доску rus_verbs:вколотить{}, // Столяр вколотил гвоздь в доску rus_verbs:вколоть{}, // Медсестра вколола в мышцу лекарство rus_verbs:вкопать{}, // Рабочие вкопали сваю в землю rus_verbs:вкрадываться{}, // Ошибка вкрадывается в расчеты rus_verbs:вкраивать{}, // Портниха вкраивает вставку в юбку rus_verbs:вкраиваться{}, // Вставка вкраивается в юбку rus_verbs:вкрасться{}, // Ошибка вкралась в расчеты rus_verbs:вкрутить{}, // Электрик вкрутил лампочку в патрон rus_verbs:вкрутиться{}, // лампочка легко вкрутилась в патрон rus_verbs:вкручивать{}, // Электрик вкручивает лампочку в патрон rus_verbs:вкручиваться{}, // Лампочка легко вкручивается в патрон rus_verbs:влазить{}, // Разъем влазит в отверствие rus_verbs:вламывать{}, // Полиция вламывается в квартиру rus_verbs:влетать{}, // Самолет влетает в грозовой фронт rus_verbs:влететь{}, // Самолет влетел в грозовой фронт rus_verbs:вливать{}, // Механик вливает масло в картер rus_verbs:вливаться{}, // Масло вливается в картер rus_verbs:влипать{}, // Эти неудачники постоянно влипают в разные происшествия rus_verbs:влипнуть{}, // Эти неудачники опять влипли в неприятности rus_verbs:влить{}, // Механик влил свежее масло в картер rus_verbs:влиться{}, // Свежее масло влилось в бак rus_verbs:вложить{}, // Инвесторы вложили в эти акции большие средства rus_verbs:вложиться{}, // Инвесторы вложились в эти акции rus_verbs:влюбиться{}, // Коля влюбился в Олю rus_verbs:влюблять{}, // Оля постоянно влюбляла в себя мальчиков rus_verbs:влюбляться{}, // Оля влюбляется в спортсменов rus_verbs:вляпаться{}, // Коля вляпался в неприятность rus_verbs:вляпываться{}, // Коля постоянно вляпывается в неприятности rus_verbs:вменить{}, // вменить в вину rus_verbs:вменять{}, // вменять в обязанность rus_verbs:вмерзать{}, // Колеса вмерзают в лед rus_verbs:вмерзнуть{}, // Колеса вмерзли в лед rus_verbs:вмести{}, // вмести в дом rus_verbs:вместить{}, // вместить в ёмкость rus_verbs:вместиться{}, // Прибор не вместился в зонд rus_verbs:вмешаться{}, // Начальник вмешался в конфликт rus_verbs:вмешивать{}, // Не вмешивай меня в это дело rus_verbs:вмешиваться{}, // Начальник вмешивается в переговоры rus_verbs:вмещаться{}, // Приборы не вмещаются в корпус rus_verbs:вминать{}, // вминать в корпус rus_verbs:вминаться{}, // кронштейн вминается в корпус rus_verbs:вмонтировать{}, // Конструкторы вмонтировали в корпус зонда новые приборы rus_verbs:вмонтироваться{}, // Новые приборы легко вмонтировались в корпус зонда rus_verbs:вмораживать{}, // Установка вмораживает сваи в грунт rus_verbs:вмораживаться{}, // Сваи вмораживаются в грунт rus_verbs:вморозить{}, // Установка вморозила сваи в грунт rus_verbs:вмуровать{}, // Сейф был вмурован в стену rus_verbs:вмуровывать{}, // вмуровывать сейф в стену rus_verbs:вмуровываться{}, // сейф вмуровывается в бетонную стену rus_verbs:внедрить{}, // внедрить инновацию в производство rus_verbs:внедриться{}, // Шпион внедрился в руководство rus_verbs:внедрять{}, // внедрять инновации в производство rus_verbs:внедряться{}, // Шпионы внедряются в руководство rus_verbs:внести{}, // внести коробку в дом rus_verbs:внестись{}, // внестись в список приглашенных гостей rus_verbs:вникать{}, // Разработчик вникает в детали задачи rus_verbs:вникнуть{}, // Дизайнер вник в детали задачи rus_verbs:вносить{}, // вносить новое действующее лицо в список главных героев rus_verbs:вноситься{}, // вноситься в список главных персонажей rus_verbs:внюхаться{}, // Пёс внюхался в ароматы леса rus_verbs:внюхиваться{}, // Пёс внюхивается в ароматы леса rus_verbs:вобрать{}, // вобрать в себя лучшие методы борьбы с вредителями rus_verbs:вовлекать{}, // вовлекать трудных подростков в занятие спортом rus_verbs:вогнать{}, // вогнал человека в тоску rus_verbs:водворить{}, // водворить преступника в тюрьму rus_verbs:возвернуть{}, // возвернуть в родную стихию rus_verbs:возвернуться{}, // возвернуться в родную стихию rus_verbs:возвести{}, // возвести число в четную степень rus_verbs:возводить{}, // возводить число в четную степень rus_verbs:возводиться{}, // число возводится в четную степень rus_verbs:возвратить{}, // возвратить коров в стойло rus_verbs:возвратиться{}, // возвратиться в родной дом rus_verbs:возвращать{}, // возвращать коров в стойло rus_verbs:возвращаться{}, // возвращаться в родной дом rus_verbs:войти{}, // войти в галерею славы rus_verbs:вонзать{}, // Коля вонзает вилку в котлету rus_verbs:вонзаться{}, // Вилка вонзается в котлету rus_verbs:вонзить{}, // Коля вонзил вилку в котлету rus_verbs:вонзиться{}, // Вилка вонзилась в сочную котлету rus_verbs:воплотить{}, // Коля воплотил свои мечты в реальность rus_verbs:воплотиться{}, // Мечты воплотились в реальность rus_verbs:воплощать{}, // Коля воплощает мечты в реальность rus_verbs:воплощаться{}, // Мечты иногда воплощаются в реальность rus_verbs:ворваться{}, // Перемены неожиданно ворвались в размеренную жизнь rus_verbs:воспарить{}, // Душа воспарила в небо rus_verbs:воспарять{}, // Душа воспаряет в небо rus_verbs:врыть{}, // врыть опору в землю rus_verbs:врыться{}, // врыться в землю rus_verbs:всадить{}, // всадить пулю в сердце rus_verbs:всаживать{}, // всаживать нож в бок rus_verbs:всасывать{}, // всасывать воду в себя rus_verbs:всасываться{}, // всасываться в ёмкость rus_verbs:вселить{}, // вселить надежду в кого-либо rus_verbs:вселиться{}, // вселиться в пустующее здание rus_verbs:вселять{}, // вселять надежду в кого-то rus_verbs:вселяться{}, // вселяться в пустующее здание rus_verbs:вскидывать{}, // вскидывать руку в небо rus_verbs:вскинуть{}, // вскинуть руку в небо rus_verbs:вслушаться{}, // вслушаться в звуки rus_verbs:вслушиваться{}, // вслушиваться в шорох rus_verbs:всматриваться{}, // всматриваться в темноту rus_verbs:всмотреться{}, // всмотреться в темень rus_verbs:всовывать{}, // всовывать палец в отверстие rus_verbs:всовываться{}, // всовываться в форточку rus_verbs:всосать{}, // всосать жидкость в себя rus_verbs:всосаться{}, // всосаться в кожу rus_verbs:вставить{}, // вставить ключ в замок rus_verbs:вставлять{}, // вставлять ключ в замок rus_verbs:встраивать{}, // встраивать черный ход в систему защиты rus_verbs:встраиваться{}, // встраиваться в систему безопасности rus_verbs:встревать{}, // встревать в разговор rus_verbs:встроить{}, // встроить секретный модуль в систему безопасности rus_verbs:встроиться{}, // встроиться в систему безопасности rus_verbs:встрять{}, // встрять в разговор rus_verbs:вступать{}, // вступать в действующую армию rus_verbs:вступить{}, // вступить в действующую армию rus_verbs:всунуть{}, // всунуть палец в отверстие rus_verbs:всунуться{}, // всунуться в форточку инфинитив:всыпать{вид:соверш}, // всыпать порошок в контейнер инфинитив:всыпать{вид:несоверш}, глагол:всыпать{вид:соверш}, глагол:всыпать{вид:несоверш}, деепричастие:всыпав{}, деепричастие:всыпая{}, прилагательное:всыпавший{ вид:соверш }, // прилагательное:всыпавший{ вид:несоверш }, прилагательное:всыпанный{}, // прилагательное:всыпающий{}, инфинитив:всыпаться{ вид:несоверш}, // всыпаться в контейнер // инфинитив:всыпаться{ вид:соверш}, // глагол:всыпаться{ вид:соверш}, глагол:всыпаться{ вид:несоверш}, // деепричастие:всыпавшись{}, деепричастие:всыпаясь{}, // прилагательное:всыпавшийся{ вид:соверш }, // прилагательное:всыпавшийся{ вид:несоверш }, // прилагательное:всыпающийся{}, rus_verbs:вталкивать{}, // вталкивать деталь в ячейку rus_verbs:вталкиваться{}, // вталкиваться в ячейку rus_verbs:втаптывать{}, // втаптывать в грязь rus_verbs:втаптываться{}, // втаптываться в грязь rus_verbs:втаскивать{}, // втаскивать мешок в комнату rus_verbs:втаскиваться{}, // втаскиваться в комнату rus_verbs:втащить{}, // втащить мешок в комнату rus_verbs:втащиться{}, // втащиться в комнату rus_verbs:втекать{}, // втекать в бутылку rus_verbs:втемяшивать{}, // втемяшивать в голову rus_verbs:втемяшиваться{}, // втемяшиваться в голову rus_verbs:втемяшить{}, // втемяшить в голову rus_verbs:втемяшиться{}, // втемяшиться в голову rus_verbs:втереть{}, // втереть крем в кожу rus_verbs:втереться{}, // втереться в кожу rus_verbs:втесаться{}, // втесаться в группу rus_verbs:втесывать{}, // втесывать в группу rus_verbs:втесываться{}, // втесываться в группу rus_verbs:втечь{}, // втечь в бак rus_verbs:втирать{}, // втирать крем в кожу rus_verbs:втираться{}, // втираться в кожу rus_verbs:втискивать{}, // втискивать сумку в вагон rus_verbs:втискиваться{}, // втискиваться в переполненный вагон rus_verbs:втиснуть{}, // втиснуть сумку в вагон rus_verbs:втиснуться{}, // втиснуться в переполненный вагон метро rus_verbs:втолкать{}, // втолкать коляску в лифт rus_verbs:втолкаться{}, // втолкаться в вагон метро rus_verbs:втолкнуть{}, // втолкнуть коляску в лифт rus_verbs:втолкнуться{}, // втолкнуться в вагон метро rus_verbs:втолочь{}, // втолочь в смесь rus_verbs:втоптать{}, // втоптать цветы в землю rus_verbs:вторгаться{}, // вторгаться в чужую зону rus_verbs:вторгнуться{}, // вторгнуться в частную жизнь rus_verbs:втравить{}, // втравить кого-то в неприятности rus_verbs:втравливать{}, // втравливать кого-то в неприятности rus_verbs:втрамбовать{}, // втрамбовать камни в землю rus_verbs:втрамбовывать{}, // втрамбовывать камни в землю rus_verbs:втрамбовываться{}, // втрамбовываться в землю rus_verbs:втрескаться{}, // втрескаться в кого-то rus_verbs:втрескиваться{}, // втрескиваться в кого-либо rus_verbs:втыкать{}, // втыкать вилку в котлетку rus_verbs:втыкаться{}, // втыкаться в розетку rus_verbs:втюриваться{}, // втюриваться в кого-либо rus_verbs:втюриться{}, // втюриться в кого-либо rus_verbs:втягивать{}, // втягивать что-то в себя rus_verbs:втягиваться{}, // втягиваться в себя rus_verbs:втянуться{}, // втянуться в себя rus_verbs:вцементировать{}, // вцементировать сваю в фундамент rus_verbs:вчеканить{}, // вчеканить надпись в лист rus_verbs:вчитаться{}, // вчитаться внимательнее в текст rus_verbs:вчитываться{}, // вчитываться внимательнее в текст rus_verbs:вчувствоваться{}, // вчувствоваться в роль rus_verbs:вшагивать{}, // вшагивать в новую жизнь rus_verbs:вшагнуть{}, // вшагнуть в новую жизнь rus_verbs:вшивать{}, // вшивать заплату в рубашку rus_verbs:вшиваться{}, // вшиваться в ткань rus_verbs:вшить{}, // вшить заплату в ткань rus_verbs:въедаться{}, // въедаться в мякоть rus_verbs:въезжать{}, // въезжать в гараж rus_verbs:въехать{}, // въехать в гараж rus_verbs:выиграть{}, // Коля выиграл в шахматы rus_verbs:выигрывать{}, // Коля часто выигрывает у меня в шахматы rus_verbs:выкладывать{}, // выкладывать в общий доступ rus_verbs:выкладываться{}, // выкладываться в общий доступ rus_verbs:выкрасить{}, // выкрасить машину в розовый цвет rus_verbs:выкраситься{}, // выкраситься в дерзкий розовый цвет rus_verbs:выкрашивать{}, // выкрашивать волосы в красный цвет rus_verbs:выкрашиваться{}, // выкрашиваться в красный цвет rus_verbs:вылезать{}, // вылезать в открытое пространство rus_verbs:вылезти{}, // вылезти в открытое пространство rus_verbs:выливать{}, // выливать в бутылку rus_verbs:выливаться{}, // выливаться в ёмкость rus_verbs:вылить{}, // вылить отходы в канализацию rus_verbs:вылиться{}, // Топливо вылилось в воду rus_verbs:выложить{}, // выложить в общий доступ rus_verbs:выпадать{}, // выпадать в осадок rus_verbs:выпрыгивать{}, // выпрыгивать в окно rus_verbs:выпрыгнуть{}, // выпрыгнуть в окно rus_verbs:выродиться{}, // выродиться в жалкое подобие rus_verbs:вырождаться{}, // вырождаться в жалкое подобие славных предков rus_verbs:высеваться{}, // высеваться в землю rus_verbs:высеять{}, // высеять в землю rus_verbs:выслать{}, // выслать в страну постоянного пребывания rus_verbs:высморкаться{}, // высморкаться в платок rus_verbs:высморкнуться{}, // высморкнуться в платок rus_verbs:выстреливать{}, // выстреливать в цель rus_verbs:выстреливаться{}, // выстреливаться в цель rus_verbs:выстрелить{}, // выстрелить в цель rus_verbs:вытекать{}, // вытекать в озеро rus_verbs:вытечь{}, // вытечь в воду rus_verbs:смотреть{}, // смотреть в будущее rus_verbs:подняться{}, // подняться в лабораторию rus_verbs:послать{}, // послать в магазин rus_verbs:слать{}, // слать в неизвестность rus_verbs:добавить{}, // добавить в суп rus_verbs:пройти{}, // пройти в лабораторию rus_verbs:положить{}, // положить в ящик rus_verbs:прислать{}, // прислать в полицию rus_verbs:упасть{}, // упасть в пропасть инфинитив:писать{ aux stress="пис^ать" }, // писать в газету инфинитив:писать{ aux stress="п^исать" }, // писать в штанишки глагол:писать{ aux stress="п^исать" }, глагол:писать{ aux stress="пис^ать" }, деепричастие:писая{}, прилагательное:писавший{ aux stress="п^исавший" }, // писавший в штанишки прилагательное:писавший{ aux stress="пис^авший" }, // писавший в газету rus_verbs:собираться{}, // собираться в поход rus_verbs:звать{}, // звать в ресторан rus_verbs:направиться{}, // направиться в ресторан rus_verbs:отправиться{}, // отправиться в ресторан rus_verbs:поставить{}, // поставить в угол rus_verbs:целить{}, // целить в мишень rus_verbs:попасть{}, // попасть в переплет rus_verbs:ударить{}, // ударить в больное место rus_verbs:закричать{}, // закричать в микрофон rus_verbs:опустить{}, // опустить в воду rus_verbs:принести{}, // принести в дом бездомного щенка rus_verbs:отдать{}, // отдать в хорошие руки rus_verbs:ходить{}, // ходить в школу rus_verbs:уставиться{}, // уставиться в экран rus_verbs:приходить{}, // приходить в бешенство rus_verbs:махнуть{}, // махнуть в Италию rus_verbs:сунуть{}, // сунуть в замочную скважину rus_verbs:явиться{}, // явиться в расположение части rus_verbs:уехать{}, // уехать в город rus_verbs:целовать{}, // целовать в лобик rus_verbs:повести{}, // повести в бой rus_verbs:опуститься{}, // опуститься в кресло rus_verbs:передать{}, // передать в архив rus_verbs:побежать{}, // побежать в школу rus_verbs:стечь{}, // стечь в воду rus_verbs:уходить{}, // уходить добровольцем в армию rus_verbs:привести{}, // привести в дом rus_verbs:шагнуть{}, // шагнуть в неизвестность rus_verbs:собраться{}, // собраться в поход rus_verbs:заглянуть{}, // заглянуть в основу rus_verbs:поспешить{}, // поспешить в церковь rus_verbs:поцеловать{}, // поцеловать в лоб rus_verbs:перейти{}, // перейти в высшую лигу rus_verbs:поверить{}, // поверить в искренность rus_verbs:глянуть{}, // глянуть в оглавление rus_verbs:зайти{}, // зайти в кафетерий rus_verbs:подобрать{}, // подобрать в лесу rus_verbs:проходить{}, // проходить в помещение rus_verbs:глядеть{}, // глядеть в глаза rus_verbs:пригласить{}, // пригласить в театр rus_verbs:позвать{}, // позвать в класс rus_verbs:усесться{}, // усесться в кресло rus_verbs:поступить{}, // поступить в институт rus_verbs:лечь{}, // лечь в постель rus_verbs:поклониться{}, // поклониться в пояс rus_verbs:потянуться{}, // потянуться в лес rus_verbs:колоть{}, // колоть в ягодицу rus_verbs:присесть{}, // присесть в кресло rus_verbs:оглядеться{}, // оглядеться в зеркало rus_verbs:поглядеть{}, // поглядеть в зеркало rus_verbs:превратиться{}, // превратиться в лягушку rus_verbs:принимать{}, // принимать во внимание rus_verbs:звонить{}, // звонить в колокола rus_verbs:привезти{}, // привезти в гостиницу rus_verbs:рухнуть{}, // рухнуть в пропасть rus_verbs:пускать{}, // пускать в дело rus_verbs:отвести{}, // отвести в больницу rus_verbs:сойти{}, // сойти в ад rus_verbs:набрать{}, // набрать в команду rus_verbs:собрать{}, // собрать в кулак rus_verbs:двигаться{}, // двигаться в каюту rus_verbs:падать{}, // падать в область нуля rus_verbs:полезть{}, // полезть в драку rus_verbs:направить{}, // направить в стационар rus_verbs:приводить{}, // приводить в чувство rus_verbs:толкнуть{}, // толкнуть в бок rus_verbs:кинуться{}, // кинуться в драку rus_verbs:ткнуть{}, // ткнуть в глаз rus_verbs:заключить{}, // заключить в объятия rus_verbs:подниматься{}, // подниматься в небо rus_verbs:расти{}, // расти в глубину rus_verbs:налить{}, // налить в кружку rus_verbs:швырнуть{}, // швырнуть в бездну rus_verbs:прыгнуть{}, // прыгнуть в дверь rus_verbs:промолчать{}, // промолчать в тряпочку rus_verbs:садиться{}, // садиться в кресло rus_verbs:лить{}, // лить в кувшин rus_verbs:дослать{}, // дослать деталь в держатель rus_verbs:переслать{}, // переслать в обработчик rus_verbs:удалиться{}, // удалиться в совещательную комнату rus_verbs:разглядывать{}, // разглядывать в бинокль rus_verbs:повесить{}, // повесить в шкаф инфинитив:походить{ вид:соверш }, // походить в институт глагол:походить{ вид:соверш }, деепричастие:походив{}, // прилагательное:походивший{вид:соверш}, rus_verbs:помчаться{}, // помчаться в класс rus_verbs:свалиться{}, // свалиться в яму rus_verbs:сбежать{}, // сбежать в Англию rus_verbs:стрелять{}, // стрелять в цель rus_verbs:обращать{}, // обращать в свою веру rus_verbs:завести{}, // завести в дом rus_verbs:приобрести{}, // приобрести в рассрочку rus_verbs:сбросить{}, // сбросить в яму rus_verbs:устроиться{}, // устроиться в крупную корпорацию rus_verbs:погрузиться{}, // погрузиться в пучину rus_verbs:течь{}, // течь в канаву rus_verbs:произвести{}, // произвести в звание майора rus_verbs:метать{}, // метать в цель rus_verbs:пустить{}, // пустить в дело rus_verbs:полететь{}, // полететь в Европу rus_verbs:пропустить{}, // пропустить в здание rus_verbs:рвануть{}, // рвануть в отпуск rus_verbs:заходить{}, // заходить в каморку rus_verbs:нырнуть{}, // нырнуть в прорубь rus_verbs:рвануться{}, // рвануться в атаку rus_verbs:приподняться{}, // приподняться в воздух rus_verbs:превращаться{}, // превращаться в крупную величину rus_verbs:прокричать{}, // прокричать в ухо rus_verbs:записать{}, // записать в блокнот rus_verbs:забраться{}, // забраться в шкаф rus_verbs:приезжать{}, // приезжать в деревню rus_verbs:продать{}, // продать в рабство rus_verbs:проникнуть{}, // проникнуть в центр rus_verbs:устремиться{}, // устремиться в открытое море rus_verbs:посадить{}, // посадить в кресло rus_verbs:упереться{}, // упереться в пол rus_verbs:ринуться{}, // ринуться в буфет rus_verbs:отдавать{}, // отдавать в кадетское училище rus_verbs:отложить{}, // отложить в долгий ящик rus_verbs:убежать{}, // убежать в приют rus_verbs:оценить{}, // оценить в миллион долларов rus_verbs:поднимать{}, // поднимать в стратосферу rus_verbs:отослать{}, // отослать в квалификационную комиссию rus_verbs:отодвинуть{}, // отодвинуть в дальний угол rus_verbs:торопиться{}, // торопиться в школу rus_verbs:попадаться{}, // попадаться в руки rus_verbs:поразить{}, // поразить в самое сердце rus_verbs:доставить{}, // доставить в квартиру rus_verbs:заслать{}, // заслать в тыл rus_verbs:сослать{}, // сослать в изгнание rus_verbs:запустить{}, // запустить в космос rus_verbs:удариться{}, // удариться в запой rus_verbs:ударяться{}, // ударяться в крайность rus_verbs:шептать{}, // шептать в лицо rus_verbs:уронить{}, // уронить в унитаз rus_verbs:прорычать{}, // прорычать в микрофон rus_verbs:засунуть{}, // засунуть в глотку rus_verbs:плыть{}, // плыть в открытое море rus_verbs:перенести{}, // перенести в духовку rus_verbs:светить{}, // светить в лицо rus_verbs:мчаться{}, // мчаться в ремонт rus_verbs:стукнуть{}, // стукнуть в лоб rus_verbs:обрушиться{}, // обрушиться в котлован rus_verbs:поглядывать{}, // поглядывать в экран rus_verbs:уложить{}, // уложить в кроватку инфинитив:попадать{ вид:несоверш }, // попадать в черный список глагол:попадать{ вид:несоверш }, прилагательное:попадающий{ вид:несоверш }, прилагательное:попадавший{ вид:несоверш }, деепричастие:попадая{}, rus_verbs:провалиться{}, // провалиться в яму rus_verbs:жаловаться{}, // жаловаться в комиссию rus_verbs:опоздать{}, // опоздать в школу rus_verbs:посылать{}, // посылать в парикмахерскую rus_verbs:погнать{}, // погнать в хлев rus_verbs:поступать{}, // поступать в институт rus_verbs:усадить{}, // усадить в кресло rus_verbs:проиграть{}, // проиграть в рулетку rus_verbs:прилететь{}, // прилететь в страну rus_verbs:повалиться{}, // повалиться в траву rus_verbs:огрызнуться{}, // Собака огрызнулась в ответ rus_verbs:лезть{}, // лезть в чужие дела rus_verbs:потащить{}, // потащить в суд rus_verbs:направляться{}, // направляться в порт rus_verbs:поползти{}, // поползти в другую сторону rus_verbs:пуститься{}, // пуститься в пляс rus_verbs:забиться{}, // забиться в нору rus_verbs:залезть{}, // залезть в конуру rus_verbs:сдать{}, // сдать в утиль rus_verbs:тронуться{}, // тронуться в путь rus_verbs:сыграть{}, // сыграть в шахматы rus_verbs:перевернуть{}, // перевернуть в более удобную позу rus_verbs:сжимать{}, // сжимать пальцы в кулак rus_verbs:подтолкнуть{}, // подтолкнуть в бок rus_verbs:отнести{}, // отнести животное в лечебницу rus_verbs:одеться{}, // одеться в зимнюю одежду rus_verbs:плюнуть{}, // плюнуть в колодец rus_verbs:передавать{}, // передавать в прокуратуру rus_verbs:отскочить{}, // отскочить в лоб rus_verbs:призвать{}, // призвать в армию rus_verbs:увезти{}, // увезти в деревню rus_verbs:улечься{}, // улечься в кроватку rus_verbs:отшатнуться{}, // отшатнуться в сторону rus_verbs:ложиться{}, // ложиться в постель rus_verbs:пролететь{}, // пролететь в конец rus_verbs:класть{}, // класть в сейф rus_verbs:доставлять{}, // доставлять в кабинет rus_verbs:приобретать{}, // приобретать в кредит rus_verbs:сводить{}, // сводить в театр rus_verbs:унести{}, // унести в могилу rus_verbs:покатиться{}, // покатиться в яму rus_verbs:сходить{}, // сходить в магазинчик rus_verbs:спустить{}, // спустить в канализацию rus_verbs:проникать{}, // проникать в сердцевину rus_verbs:метнуть{}, // метнуть в болвана гневный взгляд rus_verbs:пожаловаться{}, // пожаловаться в администрацию rus_verbs:стучать{}, // стучать в металлическую дверь rus_verbs:тащить{}, // тащить в ремонт rus_verbs:заглядывать{}, // заглядывать в ответы rus_verbs:плюхнуться{}, // плюхнуться в стол ароматного сена rus_verbs:увести{}, // увести в следующий кабинет rus_verbs:успевать{}, // успевать в школу rus_verbs:пробраться{}, // пробраться в собачью конуру rus_verbs:подавать{}, // подавать в суд rus_verbs:прибежать{}, // прибежать в конюшню rus_verbs:рассмотреть{}, // рассмотреть в микроскоп rus_verbs:пнуть{}, // пнуть в живот rus_verbs:завернуть{}, // завернуть в декоративную пленку rus_verbs:уезжать{}, // уезжать в деревню rus_verbs:привлекать{}, // привлекать в свои ряды rus_verbs:перебраться{}, // перебраться в прибрежный город rus_verbs:долить{}, // долить в коктейль rus_verbs:палить{}, // палить в нападающих rus_verbs:отобрать{}, // отобрать в коллекцию rus_verbs:улететь{}, // улететь в неизвестность rus_verbs:выглянуть{}, // выглянуть в окно rus_verbs:выглядывать{}, // выглядывать в окно rus_verbs:пробираться{}, // грабитель, пробирающийся в дом инфинитив:написать{ aux stress="напис^ать"}, // читатель, написавший в блог глагол:написать{ aux stress="напис^ать"}, прилагательное:написавший{ aux stress="напис^авший"}, rus_verbs:свернуть{}, // свернуть в колечко инфинитив:сползать{ вид:несоверш }, // сползать в овраг глагол:сползать{ вид:несоверш }, прилагательное:сползающий{ вид:несоверш }, прилагательное:сползавший{ вид:несоверш }, rus_verbs:барабанить{}, // барабанить в дверь rus_verbs:дописывать{}, // дописывать в конец rus_verbs:меняться{}, // меняться в лучшую сторону rus_verbs:измениться{}, // измениться в лучшую сторону rus_verbs:изменяться{}, // изменяться в лучшую сторону rus_verbs:вписаться{}, // вписаться в поворот rus_verbs:вписываться{}, // вписываться в повороты rus_verbs:переработать{}, // переработать в удобрение rus_verbs:перерабатывать{}, // перерабатывать в удобрение rus_verbs:уползать{}, // уползать в тень rus_verbs:заползать{}, // заползать в нору rus_verbs:перепрятать{}, // перепрятать в укромное место rus_verbs:заталкивать{}, // заталкивать в вагон rus_verbs:преобразовывать{}, // преобразовывать в список инфинитив:конвертировать{ вид:несоверш }, // конвертировать в список глагол:конвертировать{ вид:несоверш }, инфинитив:конвертировать{ вид:соверш }, глагол:конвертировать{ вид:соверш }, деепричастие:конвертировав{}, деепричастие:конвертируя{}, rus_verbs:изорвать{}, // Он изорвал газету в клочки. rus_verbs:выходить{}, // Окна выходят в сад. rus_verbs:говорить{}, // Он говорил в защиту своего отца. rus_verbs:вырастать{}, // Он вырастает в большого художника. rus_verbs:вывести{}, // Он вывел детей в сад. // инфинитив:всыпать{ вид:соверш }, инфинитив:всыпать{ вид:несоверш }, // глагол:всыпать{ вид:соверш }, глагол:всыпать{ вид:несоверш }, // Он всыпал в воду две ложки соли. // прилагательное:раненый{}, // Он был ранен в левую руку. // прилагательное:одетый{}, // Он был одет в толстое осеннее пальто. rus_verbs:бухнуться{}, // Он бухнулся в воду. rus_verbs:склонять{}, // склонять защиту в свою пользу rus_verbs:впиться{}, // Пиявка впилась в тело. rus_verbs:сходиться{}, // Интеллигенты начала века часто сходились в разные союзы rus_verbs:сохранять{}, // сохранить данные в файл rus_verbs:собирать{}, // собирать игрушки в ящик rus_verbs:упаковывать{}, // упаковывать вещи в чемодан rus_verbs:обращаться{}, // Обращайтесь ко мне в любое время rus_verbs:стрельнуть{}, // стрельни в толпу! rus_verbs:пулять{}, // пуляй в толпу rus_verbs:пульнуть{}, // пульни в толпу rus_verbs:становиться{}, // Становитесь в очередь. rus_verbs:вписать{}, // Юля вписала свое имя в список. rus_verbs:вписывать{}, // Мы вписывали свои имена в список прилагательное:видный{}, // Планета Марс видна в обычный бинокль rus_verbs:пойти{}, // Девочка рано пошла в школу rus_verbs:отойти{}, // Эти обычаи отошли в историю. rus_verbs:бить{}, // Холодный ветер бил ему в лицо. rus_verbs:входить{}, // Это входит в его обязанности. rus_verbs:принять{}, // меня приняли в пионеры rus_verbs:уйти{}, // Правительство РФ ушло в отставку rus_verbs:допустить{}, // Япония была допущена в Организацию Объединённых Наций в 1956 году. rus_verbs:посвятить{}, // Я посвятил друга в свою тайну. инфинитив:экспортировать{ вид:несоверш }, глагол:экспортировать{ вид:несоверш }, // экспортировать нефть в страны Востока rus_verbs:взглянуть{}, // Я не смел взглянуть ему в глаза. rus_verbs:идти{}, // Я иду гулять в парк. rus_verbs:вскочить{}, // Я вскочил в трамвай и помчался в институт. rus_verbs:получить{}, // Эту мебель мы получили в наследство от родителей. rus_verbs:везти{}, // Учитель везёт детей в лагерь. rus_verbs:качать{}, // Судно качает во все стороны. rus_verbs:заезжать{}, // Сегодня вечером я заезжал в магазин за книгами. rus_verbs:связать{}, // Свяжите свои вещи в узелок. rus_verbs:пронести{}, // Пронесите стол в дверь. rus_verbs:вынести{}, // Надо вынести примечания в конец. rus_verbs:устроить{}, // Она устроила сына в школу. rus_verbs:угодить{}, // Она угодила головой в дверь. rus_verbs:отвернуться{}, // Она резко отвернулась в сторону. rus_verbs:рассматривать{}, // Она рассматривала сцену в бинокль. rus_verbs:обратить{}, // Война обратила город в развалины. rus_verbs:сойтись{}, // Мы сошлись в школьные годы. rus_verbs:приехать{}, // Мы приехали в положенный час. rus_verbs:встать{}, // Дети встали в круг. rus_verbs:впасть{}, // Из-за болезни он впал в нужду. rus_verbs:придти{}, // придти в упадок rus_verbs:заявить{}, // Надо заявить в милицию о краже. rus_verbs:заявлять{}, // заявлять в полицию rus_verbs:ехать{}, // Мы будем ехать в Орёл rus_verbs:окрашиваться{}, // окрашиваться в красный цвет rus_verbs:решить{}, // Дело решено в пользу истца. rus_verbs:сесть{}, // Она села в кресло rus_verbs:посмотреть{}, // Она посмотрела на себя в зеркало. rus_verbs:влезать{}, // он влезает в мою квартирку rus_verbs:попасться{}, // в мою ловушку попалась мышь rus_verbs:лететь{}, // Мы летим в Орёл ГЛ_ИНФ(брать), // он берет в свою правую руку очень тяжелый шершавый камень ГЛ_ИНФ(взять), // Коля взял в руку камень ГЛ_ИНФ(поехать), // поехать в круиз ГЛ_ИНФ(подать), // подать в отставку инфинитив:засыпать{ вид:соверш }, глагол:засыпать{ вид:соверш }, // засыпать песок в ящик инфинитив:засыпать{ вид:несоверш переходность:переходный }, глагол:засыпать{ вид:несоверш переходность:переходный }, // засыпать песок в ящик ГЛ_ИНФ(впадать), прилагательное:впадающий{}, прилагательное:впадавший{}, деепричастие:впадая{}, // впадать в море ГЛ_ИНФ(постучать) // постучать в дверь } // Чтобы разрешить связывание в паттернах типа: уйти в BEA Systems fact гл_предл { if context { Гл_В_Вин предлог:в{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { Гл_В_Вин предлог:в{} *:*{ падеж:вин } } then return true } fact гл_предл { if context { глагол:подвывать{} предлог:в{} существительное:такт{ падеж:вин } } then return true } #endregion Винительный // Все остальные варианты по умолчанию запрещаем. fact гл_предл { if context { * предлог:в{} *:*{ падеж:предл } } then return false,-3 } fact гл_предл { if context { * предлог:в{} *:*{ падеж:мест } } then return false,-3 } fact гл_предл { if context { * предлог:в{} *:*{ падеж:вин } } then return false,-4 } fact гл_предл { if context { * предлог:в{} * } then return false,-5 } #endregion Предлог_В #region Предлог_НА // ------------------- С ПРЕДЛОГОМ 'НА' --------------------------- #region ПРЕДЛОЖНЫЙ // НА+предложный падеж: // ЛЕЖАТЬ НА СТОЛЕ #region VerbList wordentry_set Гл_НА_Предл= { rus_verbs:заслушать{}, // Вопрос заслушали на сессии облсовета rus_verbs:ПРОСТУПАТЬ{}, // На лбу, носу и щеке проступало черное пятно кровоподтека. (ПРОСТУПАТЬ/ПРОСТУПИТЬ) rus_verbs:ПРОСТУПИТЬ{}, // rus_verbs:ВИДНЕТЬСЯ{}, // На другой стороне Океана виднелась полоска суши, окружавшая нижний ярус планеты. (ВИДНЕТЬСЯ) rus_verbs:ЗАВИСАТЬ{}, // Машина умела зависать в воздухе на любой высоте (ЗАВИСАТЬ) rus_verbs:ЗАМЕРЕТЬ{}, // Скользнув по траве, он замер на боку (ЗАМЕРЕТЬ, локатив) rus_verbs:ЗАМИРАТЬ{}, // rus_verbs:ЗАКРЕПИТЬ{}, // Он вручил ей лишний кинжал, который она воткнула в рубаху и закрепила на подоле. (ЗАКРЕПИТЬ) rus_verbs:УПОЛЗТИ{}, // Зверь завизжал и попытался уползти на двух невредимых передних ногах. (УПОЛЗТИ/УПОЛЗАТЬ) rus_verbs:УПОЛЗАТЬ{}, // rus_verbs:БОЛТАТЬСЯ{}, // Тело его будет болтаться на пространственных ветрах, пока не сгниет веревка. (БОЛТАТЬСЯ) rus_verbs:РАЗВЕРНУТЬ{}, // Филиппины разрешат США развернуть военные базы на своей территории (РАЗВЕРНУТЬ) rus_verbs:ПОЛУЧИТЬ{}, // Я пытался узнать секреты и получить советы на официальном русскоязычном форуме (ПОЛУЧИТЬ) rus_verbs:ЗАСИЯТЬ{}, // Он активировал управление, и на экране снова засияло изображение полумесяца. (ЗАСИЯТЬ) rus_verbs:ВЗОРВАТЬСЯ{}, // Смертник взорвался на предвыборном митинге в Пакистане (ВЗОРВАТЬСЯ) rus_verbs:искриться{}, rus_verbs:ОДЕРЖИВАТЬ{}, // На выборах в иранский парламент победу одерживают противники действующего президента (ОДЕРЖИВАТЬ) rus_verbs:ПРЕСЕЧЬ{}, // На Украине пресекли дерзкий побег заключенных на вертолете (ПРЕСЕЧЬ) rus_verbs:УЛЕТЕТЬ{}, // Голый норвежец улетел на лыжах с трамплина на 60 метров (УЛЕТЕТЬ) rus_verbs:ПРОХОДИТЬ{}, // укрывающийся в лесу американский подросток проходил инициацию на охоте, выпив кружку крови первого убитого им оленя (ПРОХОДИТЬ) rus_verbs:СУЩЕСТВОВАТЬ{}, // На Марсе существовали условия для жизни (СУЩЕСТВОВАТЬ) rus_verbs:УКАЗАТЬ{}, // Победу в Лиге чемпионов укажут на часах (УКАЗАТЬ) rus_verbs:отвести{}, // отвести душу на людях rus_verbs:сходиться{}, // Оба профессора сходились на том, что в черепной коробке динозавра rus_verbs:сойтись{}, rus_verbs:ОБНАРУЖИТЬ{}, // Доказательство наличия подповерхностного океана на Европе обнаружено на её поверхности (ОБНАРУЖИТЬ) rus_verbs:НАБЛЮДАТЬСЯ{}, // Редкий зодиакальный свет вскоре будет наблюдаться на ночном небе (НАБЛЮДАТЬСЯ) rus_verbs:ДОСТИГНУТЬ{}, // На всех аварийных реакторах достигнуто состояние так называемой холодной остановки (ДОСТИГНУТЬ/ДОСТИЧЬ) глагол:ДОСТИЧЬ{}, инфинитив:ДОСТИЧЬ{}, rus_verbs:завершить{}, // Российские биатлонисты завершили чемпионат мира на мажорной ноте rus_verbs:РАСКЛАДЫВАТЬ{}, rus_verbs:ФОКУСИРОВАТЬСЯ{}, // Инвесторы предпочитают фокусироваться на среднесрочных ожиданиях (ФОКУСИРОВАТЬСЯ) rus_verbs:ВОСПРИНИМАТЬ{}, // как несерьезно воспринимали его на выборах мэра (ВОСПРИНИМАТЬ) rus_verbs:БУШЕВАТЬ{}, // на территории Тверской области бушевала гроза , в результате которой произошло отключение электроснабжения в ряде муниципальных образований региона (БУШЕВАТЬ) rus_verbs:УЧАСТИТЬСЯ{}, // В последние месяцы в зоне ответственности бундесвера на севере Афганистана участились случаи обстрелов полевых лагерей немецких миротворцев (УЧАСТИТЬСЯ) rus_verbs:ВЫИГРАТЬ{}, // Почему женская сборная России не может выиграть медаль на чемпионате мира (ВЫИГРАТЬ) rus_verbs:ПРОПАСТЬ{}, // Пропавшим на прогулке актером заинтересовались следователи (ПРОПАСТЬ) rus_verbs:УБИТЬ{}, // Силовики убили двух боевиков на административной границе Ингушетии и Чечни (УБИТЬ) rus_verbs:подпрыгнуть{}, // кобель нелепо подпрыгнул на трех ногах , а его хозяин отправил струю пива мимо рта rus_verbs:подпрыгивать{}, rus_verbs:высветиться{}, // на компьютере высветится твоя подпись rus_verbs:фигурировать{}, // его портрет фигурирует на страницах печати и телеэкранах rus_verbs:действовать{}, // выявленный контрабандный канал действовал на постоянной основе rus_verbs:СОХРАНИТЬСЯ{}, // На рынке международных сделок IPO сохранится высокая активность (СОХРАНИТЬСЯ НА) rus_verbs:ПРОЙТИ{}, // Необычный конкурс прошёл на севере Швеции (ПРОЙТИ НА предл) rus_verbs:НАЧАТЬСЯ{}, // На северо-востоке США началась сильная снежная буря. (НАЧАТЬСЯ НА предл) rus_verbs:ВОЗНИКНУТЬ{}, // Конфликт возник на почве совместной коммерческой деятельности по выращиванию овощей и зелени (ВОЗНИКНУТЬ НА) rus_verbs:СВЕТИТЬСЯ{}, // она по-прежнему светится на лицах людей (СВЕТИТЬСЯ НА предл) rus_verbs:ОРГАНИЗОВАТЬ{}, // Власти Москвы намерены организовать масленичные гуляния на 100 площадках (ОРГАНИЗОВАТЬ НА предл) rus_verbs:ИМЕТЬ{}, // Имея власть на низовом уровне, оказывать самое непосредственное и определяющее влияние на верховную власть (ИМЕТЬ НА предл) rus_verbs:ОПРОБОВАТЬ{}, // Опробовать и отточить этот инструмент на местных и региональных выборах (ОПРОБОВАТЬ, ОТТОЧИТЬ НА предл) rus_verbs:ОТТОЧИТЬ{}, rus_verbs:ДОЛОЖИТЬ{}, // Участникам совещания предложено подготовить по этому вопросу свои предложения и доложить на повторной встрече (ДОЛОЖИТЬ НА предл) rus_verbs:ОБРАЗОВЫВАТЬСЯ{}, // Солевые и пылевые бури , образующиеся на поверхности обнаженной площади моря , уничтожают урожаи и растительность (ОБРАЗОВЫВАТЬСЯ НА) rus_verbs:СОБРАТЬ{}, // использует собранные на местном рынке депозиты (СОБРАТЬ НА предл) инфинитив:НАХОДИТЬСЯ{ вид:несоверш}, // находившихся на борту самолета (НАХОДИТЬСЯ НА предл) глагол:НАХОДИТЬСЯ{ вид:несоверш }, прилагательное:находившийся{ вид:несоверш }, прилагательное:находящийся{ вид:несоверш }, деепричастие:находясь{}, rus_verbs:ГОТОВИТЬ{}, // пищу готовят сами на примусах (ГОТОВИТЬ НА предл) rus_verbs:РАЗДАТЬСЯ{}, // Они сообщили о сильном хлопке , который раздался на территории нефтебазы (РАЗДАТЬСЯ НА) rus_verbs:ПОДСКАЛЬЗЫВАТЬСЯ{}, // подскальзываться на той же апельсиновой корке (ПОДСКАЛЬЗЫВАТЬСЯ НА) rus_verbs:СКРЫТЬСЯ{}, // Германия: латвиец ограбил магазин и попытался скрыться на такси (СКРЫТЬСЯ НА предл) rus_verbs:ВЫРАСТИТЬ{}, // Пациенту вырастили новый нос на руке (ВЫРАСТИТЬ НА) rus_verbs:ПРОДЕМОНСТРИРОВАТЬ{}, // Они хотят подчеркнуть эмоциональную тонкость оппозиционера и на этом фоне продемонстрировать бездушность российской власти (ПРОДЕМОНСТРИРОВАТЬ НА предл) rus_verbs:ОСУЩЕСТВЛЯТЬСЯ{}, // первичный анализ смеси запахов может осуществляться уже на уровне рецепторных нейронов благодаря механизму латерального торможения (ОСУЩЕСТВЛЯТЬСЯ НА) rus_verbs:ВЫДЕЛЯТЬСЯ{}, // Ягоды брусники, резко выделяющиеся своим красным цветом на фоне зелёной листвы, поедаются животными и птицами (ВЫДЕЛЯТЬСЯ НА) rus_verbs:РАСКРЫТЬ{}, // На Украине раскрыто крупное мошенничество в сфере туризма (РАСКРЫТЬ НА) rus_verbs:ОБЖАРИВАТЬСЯ{}, // Омлет обжаривается на сливочном масле с одной стороны, пока он почти полностью не загустеет (ОБЖАРИВАТЬСЯ НА) rus_verbs:ПРИГОТОВЛЯТЬ{}, // Яичница — блюдо европейской кухни, приготовляемое на сковороде из разбитых яиц (ПРИГОТОВЛЯТЬ НА) rus_verbs:РАССАДИТЬ{}, // Женька рассадил игрушки на скамеечке (РАССАДИТЬ НА) rus_verbs:ОБОЖДАТЬ{}, // обожди Анжелу на остановке троллейбуса (ОБОЖДАТЬ НА) rus_verbs:УЧИТЬСЯ{}, // Марина учится на факультете журналистики (УЧИТЬСЯ НА предл) rus_verbs:раскладываться{}, // Созревшие семенные экземпляры раскладывают на солнце или в теплом месте, где они делаются мягкими (РАСКЛАДЫВАТЬСЯ В, НА) rus_verbs:ПОСЛУШАТЬ{}, // Послушайте друзей и врагов на расстоянии! (ПОСЛУШАТЬ НА) rus_verbs:ВЕСТИСЬ{}, // На стороне противника всю ночь велась перегруппировка сил. (ВЕСТИСЬ НА) rus_verbs:ПОИНТЕРЕСОВАТЬСЯ{}, // корреспондент поинтересовался у людей на улице (ПОИНТЕРЕСОВАТЬСЯ НА) rus_verbs:ОТКРЫВАТЬСЯ{}, // Российские биржи открываются на негативном фоне (ОТКРЫВАТЬСЯ НА) rus_verbs:СХОДИТЬ{}, // Вы сходите на следующей остановке? (СХОДИТЬ НА) rus_verbs:ПОГИБНУТЬ{}, // Её отец погиб на войне. (ПОГИБНУТЬ НА) rus_verbs:ВЫЙТИ{}, // Книга выйдет на будущей неделе. (ВЫЙТИ НА предл) rus_verbs:НЕСТИСЬ{}, // Корабль несётся на всех парусах. (НЕСТИСЬ НА предл) rus_verbs:вкалывать{}, // Папа вкалывает на работе, чтобы прокормить семью (вкалывать на) rus_verbs:доказать{}, // разработчики доказали на практике применимость данного подхода к обсчету сцен (доказать на, применимость к) rus_verbs:хулиганить{}, // дозволять кому-то хулиганить на кладбище (хулиганить на) глагол:вычитать{вид:соверш}, инфинитив:вычитать{вид:соверш}, // вычитать на сайте (вычитать на сайте) деепричастие:вычитав{}, rus_verbs:аккомпанировать{}, // он аккомпанировал певцу на губной гармошке (аккомпанировать на) rus_verbs:набрать{}, // статья с заголовком, набранным на компьютере rus_verbs:сделать{}, // книга с иллюстрацией, сделанной на компьютере rus_verbs:развалиться{}, // Антонио развалился на диване rus_verbs:улечься{}, // Антонио улегся на полу rus_verbs:зарубить{}, // Заруби себе на носу. rus_verbs:ценить{}, // Его ценят на заводе. rus_verbs:вернуться{}, // Отец вернулся на закате. rus_verbs:шить{}, // Вы умеете шить на машинке? rus_verbs:бить{}, // Скот бьют на бойне. rus_verbs:выехать{}, // Мы выехали на рассвете. rus_verbs:валяться{}, // На полу валяется бумага. rus_verbs:разложить{}, // она разложила полотенце на песке rus_verbs:заниматься{}, // я занимаюсь на тренажере rus_verbs:позаниматься{}, rus_verbs:порхать{}, // порхать на лугу rus_verbs:пресекать{}, // пресекать на корню rus_verbs:изъясняться{}, // изъясняться на непонятном языке rus_verbs:развесить{}, // развесить на столбах rus_verbs:обрасти{}, // обрасти на южной части rus_verbs:откладываться{}, // откладываться на стенках артерий rus_verbs:уносить{}, // уносить на носилках rus_verbs:проплыть{}, // проплыть на плоту rus_verbs:подъезжать{}, // подъезжать на повозках rus_verbs:пульсировать{}, // пульсировать на лбу rus_verbs:рассесться{}, // птицы расселись на ветках rus_verbs:застопориться{}, // застопориться на первом пункте rus_verbs:изловить{}, // изловить на окраинах rus_verbs:покататься{}, // покататься на машинках rus_verbs:залопотать{}, // залопотать на неизвестном языке rus_verbs:растягивать{}, // растягивать на станке rus_verbs:поделывать{}, // поделывать на пляже rus_verbs:подстеречь{}, // подстеречь на площадке rus_verbs:проектировать{}, // проектировать на компьютере rus_verbs:притулиться{}, // притулиться на кушетке rus_verbs:дозволять{}, // дозволять кому-то хулиганить на кладбище rus_verbs:пострелять{}, // пострелять на испытательном полигоне rus_verbs:засиживаться{}, // засиживаться на работе rus_verbs:нежиться{}, // нежиться на солнышке rus_verbs:притомиться{}, // притомиться на рабочем месте rus_verbs:поселяться{}, // поселяться на чердаке rus_verbs:потягиваться{}, // потягиваться на земле rus_verbs:отлеживаться{}, // отлеживаться на койке rus_verbs:протаранить{}, // протаранить на танке rus_verbs:гарцевать{}, // гарцевать на коне rus_verbs:облупиться{}, // облупиться на носу rus_verbs:оговорить{}, // оговорить на собеседовании rus_verbs:зарегистрироваться{}, // зарегистрироваться на сайте rus_verbs:отпечатать{}, // отпечатать на картоне rus_verbs:сэкономить{}, // сэкономить на мелочах rus_verbs:покатать{}, // покатать на пони rus_verbs:колесить{}, // колесить на старой машине rus_verbs:понастроить{}, // понастроить на участках rus_verbs:поджарить{}, // поджарить на костре rus_verbs:узнаваться{}, // узнаваться на фотографии rus_verbs:отощать{}, // отощать на казенных харчах rus_verbs:редеть{}, // редеть на макушке rus_verbs:оглашать{}, // оглашать на общем собрании rus_verbs:лопотать{}, // лопотать на иврите rus_verbs:пригреть{}, // пригреть на груди rus_verbs:консультироваться{}, // консультироваться на форуме rus_verbs:приноситься{}, // приноситься на одежде rus_verbs:сушиться{}, // сушиться на балконе rus_verbs:наследить{}, // наследить на полу rus_verbs:нагреться{}, // нагреться на солнце rus_verbs:рыбачить{}, // рыбачить на озере rus_verbs:прокатить{}, // прокатить на выборах rus_verbs:запинаться{}, // запинаться на ровном месте rus_verbs:отрубиться{}, // отрубиться на мягкой подушке rus_verbs:заморозить{}, // заморозить на улице rus_verbs:промерзнуть{}, // промерзнуть на открытом воздухе rus_verbs:просохнуть{}, // просохнуть на батарее rus_verbs:развозить{}, // развозить на велосипеде rus_verbs:прикорнуть{}, // прикорнуть на диванчике rus_verbs:отпечататься{}, // отпечататься на коже rus_verbs:выявлять{}, // выявлять на таможне rus_verbs:расставлять{}, // расставлять на башнях rus_verbs:прокрутить{}, // прокрутить на пальце rus_verbs:умываться{}, // умываться на улице rus_verbs:пересказывать{}, // пересказывать на страницах романа rus_verbs:удалять{}, // удалять на пуховике rus_verbs:хозяйничать{}, // хозяйничать на складе rus_verbs:оперировать{}, // оперировать на поле боя rus_verbs:поносить{}, // поносить на голове rus_verbs:замурлыкать{}, // замурлыкать на коленях rus_verbs:передвигать{}, // передвигать на тележке rus_verbs:прочертить{}, // прочертить на земле rus_verbs:колдовать{}, // колдовать на кухне rus_verbs:отвозить{}, // отвозить на казенном транспорте rus_verbs:трахать{}, // трахать на природе rus_verbs:мастерить{}, // мастерить на кухне rus_verbs:ремонтировать{}, // ремонтировать на коленке rus_verbs:развезти{}, // развезти на велосипеде rus_verbs:робеть{}, // робеть на сцене инфинитив:реализовать{ вид:несоверш }, инфинитив:реализовать{ вид:соверш }, // реализовать на сайте глагол:реализовать{ вид:несоверш }, глагол:реализовать{ вид:соверш }, деепричастие:реализовав{}, деепричастие:реализуя{}, rus_verbs:покаяться{}, // покаяться на смертном одре rus_verbs:специализироваться{}, // специализироваться на тестировании rus_verbs:попрыгать{}, // попрыгать на батуте rus_verbs:переписывать{}, // переписывать на столе rus_verbs:расписывать{}, // расписывать на доске rus_verbs:зажимать{}, // зажимать на запястье rus_verbs:практиковаться{}, // практиковаться на мышах rus_verbs:уединиться{}, // уединиться на чердаке rus_verbs:подохнуть{}, // подохнуть на чужбине rus_verbs:приподниматься{}, // приподниматься на руках rus_verbs:уродиться{}, // уродиться на полях rus_verbs:продолжиться{}, // продолжиться на улице rus_verbs:посапывать{}, // посапывать на диване rus_verbs:ободрать{}, // ободрать на спине rus_verbs:скрючиться{}, // скрючиться на песке rus_verbs:тормознуть{}, // тормознуть на перекрестке rus_verbs:лютовать{}, // лютовать на хуторе rus_verbs:зарегистрировать{}, // зарегистрировать на сайте rus_verbs:переждать{}, // переждать на вершине холма rus_verbs:доминировать{}, // доминировать на территории rus_verbs:публиковать{}, // публиковать на сайте rus_verbs:морщить{}, // морщить на лбу rus_verbs:сконцентрироваться{}, // сконцентрироваться на главном rus_verbs:подрабатывать{}, // подрабатывать на рынке rus_verbs:репетировать{}, // репетировать на заднем дворе rus_verbs:подвернуть{}, // подвернуть на брусчатке rus_verbs:зашелестеть{}, // зашелестеть на ветру rus_verbs:расчесывать{}, // расчесывать на спине rus_verbs:одевать{}, // одевать на рынке rus_verbs:испечь{}, // испечь на углях rus_verbs:сбрить{}, // сбрить на затылке rus_verbs:согреться{}, // согреться на печке rus_verbs:замаячить{}, // замаячить на горизонте rus_verbs:пересчитывать{}, // пересчитывать на пальцах rus_verbs:галдеть{}, // галдеть на крыльце rus_verbs:переплыть{}, // переплыть на плоту rus_verbs:передохнуть{}, // передохнуть на скамейке rus_verbs:прижиться{}, // прижиться на ферме rus_verbs:переправляться{}, // переправляться на плотах rus_verbs:накупить{}, // накупить на блошином рынке rus_verbs:проторчать{}, // проторчать на виду rus_verbs:мокнуть{}, // мокнуть на улице rus_verbs:застукать{}, // застукать на камбузе rus_verbs:завязывать{}, // завязывать на ботинках rus_verbs:повисать{}, // повисать на ветке rus_verbs:подвизаться{}, // подвизаться на государственной службе rus_verbs:кормиться{}, // кормиться на болоте rus_verbs:покурить{}, // покурить на улице rus_verbs:зимовать{}, // зимовать на болотах rus_verbs:застегивать{}, // застегивать на гимнастерке rus_verbs:поигрывать{}, // поигрывать на гитаре rus_verbs:погореть{}, // погореть на махинациях с землей rus_verbs:кувыркаться{}, // кувыркаться на батуте rus_verbs:похрапывать{}, // похрапывать на диване rus_verbs:пригревать{}, // пригревать на груди rus_verbs:завязнуть{}, // завязнуть на болоте rus_verbs:шастать{}, // шастать на втором этаже rus_verbs:заночевать{}, // заночевать на сеновале rus_verbs:отсиживаться{}, // отсиживаться на чердаке rus_verbs:мчать{}, // мчать на байке rus_verbs:сгнить{}, // сгнить на урановых рудниках rus_verbs:тренировать{}, // тренировать на манекенах rus_verbs:повеселиться{}, // повеселиться на празднике rus_verbs:измучиться{}, // измучиться на болоте rus_verbs:увянуть{}, // увянуть на подоконнике rus_verbs:раскрутить{}, // раскрутить на оси rus_verbs:выцвести{}, // выцвести на солнечном свету rus_verbs:изготовлять{}, // изготовлять на коленке rus_verbs:гнездиться{}, // гнездиться на вершине дерева rus_verbs:разогнаться{}, // разогнаться на мотоцикле rus_verbs:излагаться{}, // излагаться на страницах доклада rus_verbs:сконцентрировать{}, // сконцентрировать на левом фланге rus_verbs:расчесать{}, // расчесать на макушке rus_verbs:плавиться{}, // плавиться на солнце rus_verbs:редактировать{}, // редактировать на ноутбуке rus_verbs:подскакивать{}, // подскакивать на месте rus_verbs:покупаться{}, // покупаться на рынке rus_verbs:промышлять{}, // промышлять на мелководье rus_verbs:приобретаться{}, // приобретаться на распродажах rus_verbs:наигрывать{}, // наигрывать на банджо rus_verbs:маневрировать{}, // маневрировать на флангах rus_verbs:запечатлеться{}, // запечатлеться на записях камер rus_verbs:укрывать{}, // укрывать на чердаке rus_verbs:подорваться{}, // подорваться на фугасе rus_verbs:закрепиться{}, // закрепиться на занятых позициях rus_verbs:громыхать{}, // громыхать на кухне инфинитив:подвигаться{ вид:соверш }, глагол:подвигаться{ вид:соверш }, // подвигаться на полу деепричастие:подвигавшись{}, rus_verbs:добываться{}, // добываться на территории Анголы rus_verbs:приплясывать{}, // приплясывать на сцене rus_verbs:доживать{}, // доживать на больничной койке rus_verbs:отпраздновать{}, // отпраздновать на работе rus_verbs:сгубить{}, // сгубить на корню rus_verbs:схоронить{}, // схоронить на кладбище rus_verbs:тускнеть{}, // тускнеть на солнце rus_verbs:скопить{}, // скопить на счету rus_verbs:помыть{}, // помыть на своем этаже rus_verbs:пороть{}, // пороть на конюшне rus_verbs:наличествовать{}, // наличествовать на складе rus_verbs:нащупывать{}, // нащупывать на полке rus_verbs:змеиться{}, // змеиться на дне rus_verbs:пожелтеть{}, // пожелтеть на солнце rus_verbs:заостриться{}, // заостриться на конце rus_verbs:свезти{}, // свезти на поле rus_verbs:прочувствовать{}, // прочувствовать на своей шкуре rus_verbs:подкрутить{}, // подкрутить на приборной панели rus_verbs:рубиться{}, // рубиться на мечах rus_verbs:сиживать{}, // сиживать на крыльце rus_verbs:тараторить{}, // тараторить на иностранном языке rus_verbs:теплеть{}, // теплеть на сердце rus_verbs:покачаться{}, // покачаться на ветке rus_verbs:сосредоточиваться{}, // сосредоточиваться на главной задаче rus_verbs:развязывать{}, // развязывать на ботинках rus_verbs:подвозить{}, // подвозить на мотороллере rus_verbs:вышивать{}, // вышивать на рубашке rus_verbs:скупать{}, // скупать на открытом рынке rus_verbs:оформлять{}, // оформлять на встрече rus_verbs:распускаться{}, // распускаться на клумбах rus_verbs:прогореть{}, // прогореть на спекуляциях rus_verbs:приползти{}, // приползти на коленях rus_verbs:загореть{}, // загореть на пляже rus_verbs:остудить{}, // остудить на балконе rus_verbs:нарвать{}, // нарвать на поляне rus_verbs:издохнуть{}, // издохнуть на болоте rus_verbs:разгружать{}, // разгружать на дороге rus_verbs:произрастать{}, // произрастать на болотах rus_verbs:разуться{}, // разуться на коврике rus_verbs:сооружать{}, // сооружать на площади rus_verbs:зачитывать{}, // зачитывать на митинге rus_verbs:уместиться{}, // уместиться на ладони rus_verbs:закупить{}, // закупить на рынке rus_verbs:горланить{}, // горланить на улице rus_verbs:экономить{}, // экономить на спичках rus_verbs:исправлять{}, // исправлять на доске rus_verbs:расслабляться{}, // расслабляться на лежаке rus_verbs:скапливаться{}, // скапливаться на крыше rus_verbs:сплетничать{}, // сплетничать на скамеечке rus_verbs:отъезжать{}, // отъезжать на лимузине rus_verbs:отчитывать{}, // отчитывать на собрании rus_verbs:сфокусировать{}, // сфокусировать на удаленной точке rus_verbs:потчевать{}, // потчевать на лаврах rus_verbs:окопаться{}, // окопаться на окраине rus_verbs:загорать{}, // загорать на пляже rus_verbs:обгореть{}, // обгореть на солнце rus_verbs:распознавать{}, // распознавать на фотографии rus_verbs:заплетаться{}, // заплетаться на макушке rus_verbs:перегреться{}, // перегреться на жаре rus_verbs:подметать{}, // подметать на крыльце rus_verbs:нарисоваться{}, // нарисоваться на горизонте rus_verbs:проскакивать{}, // проскакивать на экране rus_verbs:попивать{}, // попивать на балконе чай rus_verbs:отплывать{}, // отплывать на лодке rus_verbs:чирикать{}, // чирикать на ветках rus_verbs:скупить{}, // скупить на оптовых базах rus_verbs:наколоть{}, // наколоть на коже картинку rus_verbs:созревать{}, // созревать на ветке rus_verbs:проколоться{}, // проколоться на мелочи rus_verbs:крутнуться{}, // крутнуться на заднем колесе rus_verbs:переночевать{}, // переночевать на постоялом дворе rus_verbs:концентрироваться{}, // концентрироваться на фильтре rus_verbs:одичать{}, // одичать на хуторе rus_verbs:спасаться{}, // спасаются на лодке rus_verbs:доказываться{}, // доказываться на страницах книги rus_verbs:познаваться{}, // познаваться на ринге rus_verbs:замыкаться{}, // замыкаться на металлическом предмете rus_verbs:заприметить{}, // заприметить на пригорке rus_verbs:продержать{}, // продержать на морозе rus_verbs:форсировать{}, // форсировать на плотах rus_verbs:сохнуть{}, // сохнуть на солнце rus_verbs:выявить{}, // выявить на поверхности rus_verbs:заседать{}, // заседать на кафедре rus_verbs:расплачиваться{}, // расплачиваться на выходе rus_verbs:светлеть{}, // светлеть на горизонте rus_verbs:залепетать{}, // залепетать на незнакомом языке rus_verbs:подсчитывать{}, // подсчитывать на пальцах rus_verbs:зарыть{}, // зарыть на пустыре rus_verbs:сформироваться{}, // сформироваться на месте rus_verbs:развертываться{}, // развертываться на площадке rus_verbs:набивать{}, // набивать на манекенах rus_verbs:замерзать{}, // замерзать на ветру rus_verbs:схватывать{}, // схватывать на лету rus_verbs:перевестись{}, // перевестись на Руси rus_verbs:смешивать{}, // смешивать на блюдце rus_verbs:прождать{}, // прождать на входе rus_verbs:мерзнуть{}, // мерзнуть на ветру rus_verbs:растирать{}, // растирать на коже rus_verbs:переспать{}, // переспал на сеновале rus_verbs:рассекать{}, // рассекать на скутере rus_verbs:опровергнуть{}, // опровергнуть на высшем уровне rus_verbs:дрыхнуть{}, // дрыхнуть на диване rus_verbs:распять{}, // распять на кресте rus_verbs:запечься{}, // запечься на костре rus_verbs:застилать{}, // застилать на балконе rus_verbs:сыскаться{}, // сыскаться на огороде rus_verbs:разориться{}, // разориться на продаже спичек rus_verbs:переделать{}, // переделать на станке rus_verbs:разъяснять{}, // разъяснять на страницах газеты rus_verbs:поседеть{}, // поседеть на висках rus_verbs:протащить{}, // протащить на спине rus_verbs:осуществиться{}, // осуществиться на деле rus_verbs:селиться{}, // селиться на окраине rus_verbs:оплачивать{}, // оплачивать на первой кассе rus_verbs:переворачивать{}, // переворачивать на сковородке rus_verbs:упражняться{}, // упражняться на батуте rus_verbs:испробовать{}, // испробовать на себе rus_verbs:разгладиться{}, // разгладиться на спине rus_verbs:рисоваться{}, // рисоваться на стекле rus_verbs:продрогнуть{}, // продрогнуть на морозе rus_verbs:пометить{}, // пометить на доске rus_verbs:приютить{}, // приютить на чердаке rus_verbs:избирать{}, // избирать на первых свободных выборах rus_verbs:затеваться{}, // затеваться на матче rus_verbs:уплывать{}, // уплывать на катере rus_verbs:замерцать{}, // замерцать на рекламном щите rus_verbs:фиксироваться{}, // фиксироваться на достигнутом уровне rus_verbs:запираться{}, // запираться на чердаке rus_verbs:загубить{}, // загубить на корню rus_verbs:развеяться{}, // развеяться на природе rus_verbs:съезжаться{}, // съезжаться на лимузинах rus_verbs:потанцевать{}, // потанцевать на могиле rus_verbs:дохнуть{}, // дохнуть на солнце rus_verbs:припарковаться{}, // припарковаться на газоне rus_verbs:отхватить{}, // отхватить на распродаже rus_verbs:остывать{}, // остывать на улице rus_verbs:переваривать{}, // переваривать на высокой ветке rus_verbs:подвесить{}, // подвесить на веревке rus_verbs:хвастать{}, // хвастать на работе rus_verbs:отрабатывать{}, // отрабатывать на уборке урожая rus_verbs:разлечься{}, // разлечься на полу rus_verbs:очертить{}, // очертить на полу rus_verbs:председательствовать{}, // председательствовать на собрании rus_verbs:сконфузиться{}, // сконфузиться на сцене rus_verbs:выявляться{}, // выявляться на ринге rus_verbs:крутануться{}, // крутануться на заднем колесе rus_verbs:караулить{}, // караулить на входе rus_verbs:перечислять{}, // перечислять на пальцах rus_verbs:обрабатывать{}, // обрабатывать на станке rus_verbs:настигать{}, // настигать на берегу rus_verbs:разгуливать{}, // разгуливать на берегу rus_verbs:насиловать{}, // насиловать на пляже rus_verbs:поредеть{}, // поредеть на макушке rus_verbs:учитывать{}, // учитывать на балансе rus_verbs:зарождаться{}, // зарождаться на большой глубине rus_verbs:распространять{}, // распространять на сайтах rus_verbs:пировать{}, // пировать на вершине холма rus_verbs:начертать{}, // начертать на стене rus_verbs:расцветать{}, // расцветать на подоконнике rus_verbs:умнеть{}, // умнеть на глазах rus_verbs:царствовать{}, // царствовать на окраине rus_verbs:закрутиться{}, // закрутиться на работе rus_verbs:отработать{}, // отработать на шахте rus_verbs:полечь{}, // полечь на поле брани rus_verbs:щебетать{}, // щебетать на ветке rus_verbs:подчеркиваться{}, // подчеркиваться на сайте rus_verbs:посеять{}, // посеять на другом поле rus_verbs:замечаться{}, // замечаться на пастбище rus_verbs:просчитать{}, // просчитать на пальцах rus_verbs:голосовать{}, // голосовать на трассе rus_verbs:маяться{}, // маяться на пляже rus_verbs:сколотить{}, // сколотить на службе rus_verbs:обретаться{}, // обретаться на чужбине rus_verbs:обливаться{}, // обливаться на улице rus_verbs:катать{}, // катать на лошадке rus_verbs:припрятать{}, // припрятать на теле rus_verbs:запаниковать{}, // запаниковать на экзамене инфинитив:слетать{ вид:соверш }, глагол:слетать{ вид:соверш }, // слетать на частном самолете деепричастие:слетав{}, rus_verbs:срубить{}, // срубить денег на спекуляциях rus_verbs:зажигаться{}, // зажигаться на улице rus_verbs:жарить{}, // жарить на углях rus_verbs:накапливаться{}, // накапливаться на счету rus_verbs:распуститься{}, // распуститься на грядке rus_verbs:рассаживаться{}, // рассаживаться на местах rus_verbs:странствовать{}, // странствовать на лошади rus_verbs:осматриваться{}, // осматриваться на месте rus_verbs:разворачивать{}, // разворачивать на завоеванной территории rus_verbs:согревать{}, // согревать на вершине горы rus_verbs:заскучать{}, // заскучать на вахте rus_verbs:перекусить{}, // перекусить на бегу rus_verbs:приплыть{}, // приплыть на тримаране rus_verbs:зажигать{}, // зажигать на танцах rus_verbs:закопать{}, // закопать на поляне rus_verbs:стирать{}, // стирать на берегу rus_verbs:подстерегать{}, // подстерегать на подходе rus_verbs:погулять{}, // погулять на свадьбе rus_verbs:огласить{}, // огласить на митинге rus_verbs:разбогатеть{}, // разбогатеть на прииске rus_verbs:грохотать{}, // грохотать на чердаке rus_verbs:расположить{}, // расположить на границе rus_verbs:реализоваться{}, // реализоваться на новой работе rus_verbs:застывать{}, // застывать на морозе rus_verbs:запечатлеть{}, // запечатлеть на пленке rus_verbs:тренироваться{}, // тренироваться на манекене rus_verbs:поспорить{}, // поспорить на совещании rus_verbs:затягивать{}, // затягивать на поясе rus_verbs:зиждиться{}, // зиждиться на твердой основе rus_verbs:построиться{}, // построиться на песке rus_verbs:надрываться{}, // надрываться на работе rus_verbs:закипать{}, // закипать на плите rus_verbs:затонуть{}, // затонуть на мелководье rus_verbs:побыть{}, // побыть на фазенде rus_verbs:сгорать{}, // сгорать на солнце инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать на улице деепричастие:пописав{ aux stress="поп^исав" }, rus_verbs:подраться{}, // подраться на сцене rus_verbs:заправить{}, // заправить на последней заправке rus_verbs:обозначаться{}, // обозначаться на карте rus_verbs:просиживать{}, // просиживать на берегу rus_verbs:начертить{}, // начертить на листке rus_verbs:тормозить{}, // тормозить на льду rus_verbs:затевать{}, // затевать на космической базе rus_verbs:задерживать{}, // задерживать на таможне rus_verbs:прилетать{}, // прилетать на частном самолете rus_verbs:полулежать{}, // полулежать на травке rus_verbs:ерзать{}, // ерзать на табуретке rus_verbs:покопаться{}, // покопаться на складе rus_verbs:подвезти{}, // подвезти на машине rus_verbs:полежать{}, // полежать на водном матрасе rus_verbs:стыть{}, // стыть на улице rus_verbs:стынуть{}, // стынуть на улице rus_verbs:скреститься{}, // скреститься на груди rus_verbs:припарковать{}, // припарковать на стоянке rus_verbs:здороваться{}, // здороваться на кафедре rus_verbs:нацарапать{}, // нацарапать на парте rus_verbs:откопать{}, // откопать на поляне rus_verbs:смастерить{}, // смастерить на коленках rus_verbs:довезти{}, // довезти на машине rus_verbs:избивать{}, // избивать на крыше rus_verbs:сварить{}, // сварить на костре rus_verbs:истребить{}, // истребить на корню rus_verbs:раскопать{}, // раскопать на болоте rus_verbs:попить{}, // попить на кухне rus_verbs:заправлять{}, // заправлять на базе rus_verbs:кушать{}, // кушать на кухне rus_verbs:замолкать{}, // замолкать на половине фразы rus_verbs:измеряться{}, // измеряться на весах rus_verbs:сбываться{}, // сбываться на самом деле rus_verbs:изображаться{}, // изображается на сцене rus_verbs:фиксировать{}, // фиксировать на данной высоте rus_verbs:ослаблять{}, // ослаблять на шее rus_verbs:зреть{}, // зреть на грядке rus_verbs:зеленеть{}, // зеленеть на грядке rus_verbs:критиковать{}, // критиковать на страницах газеты rus_verbs:облететь{}, // облететь на самолете rus_verbs:заразиться{}, // заразиться на работе rus_verbs:рассеять{}, // рассеять на территории rus_verbs:печься{}, // печься на костре rus_verbs:поспать{}, // поспать на земле rus_verbs:сплетаться{}, // сплетаться на макушке rus_verbs:удерживаться{}, // удерживаться на расстоянии rus_verbs:помешаться{}, // помешаться на чистоте rus_verbs:ликвидировать{}, // ликвидировать на полигоне rus_verbs:проваляться{}, // проваляться на диване rus_verbs:лечиться{}, // лечиться на дому rus_verbs:обработать{}, // обработать на станке rus_verbs:защелкнуть{}, // защелкнуть на руках rus_verbs:разносить{}, // разносить на одежде rus_verbs:чесать{}, // чесать на груди rus_verbs:наладить{}, // наладить на конвейере выпуск rus_verbs:отряхнуться{}, // отряхнуться на улице rus_verbs:разыгрываться{}, // разыгрываться на скачках rus_verbs:обеспечиваться{}, // обеспечиваться на выгодных условиях rus_verbs:греться{}, // греться на вокзале rus_verbs:засидеться{}, // засидеться на одном месте rus_verbs:материализоваться{}, // материализоваться на границе rus_verbs:рассеиваться{}, // рассеиваться на высоте вершин rus_verbs:перевозить{}, // перевозить на платформе rus_verbs:поиграть{}, // поиграть на скрипке rus_verbs:потоптаться{}, // потоптаться на одном месте rus_verbs:переправиться{}, // переправиться на плоту rus_verbs:забрезжить{}, // забрезжить на горизонте rus_verbs:завывать{}, // завывать на опушке rus_verbs:заваривать{}, // заваривать на кухоньке rus_verbs:перемещаться{}, // перемещаться на спасательном плоту инфинитив:писаться{ aux stress="пис^аться" }, глагол:писаться{ aux stress="пис^аться" }, // писаться на бланке rus_verbs:праздновать{}, // праздновать на улицах rus_verbs:обучить{}, // обучить на корте rus_verbs:орудовать{}, // орудовать на складе rus_verbs:подрасти{}, // подрасти на глядке rus_verbs:шелестеть{}, // шелестеть на ветру rus_verbs:раздеваться{}, // раздеваться на публике rus_verbs:пообедать{}, // пообедать на газоне rus_verbs:жрать{}, // жрать на помойке rus_verbs:исполняться{}, // исполняться на флейте rus_verbs:похолодать{}, // похолодать на улице rus_verbs:гнить{}, // гнить на каторге rus_verbs:прослушать{}, // прослушать на концерте rus_verbs:совещаться{}, // совещаться на заседании rus_verbs:покачивать{}, // покачивать на волнах rus_verbs:отсидеть{}, // отсидеть на гаупвахте rus_verbs:формировать{}, // формировать на секретной базе rus_verbs:захрапеть{}, // захрапеть на кровати rus_verbs:объехать{}, // объехать на попутке rus_verbs:поселить{}, // поселить на верхних этажах rus_verbs:заворочаться{}, // заворочаться на сене rus_verbs:напрятать{}, // напрятать на теле rus_verbs:очухаться{}, // очухаться на земле rus_verbs:полистать{}, // полистать на досуге rus_verbs:завертеть{}, // завертеть на шесте rus_verbs:печатать{}, // печатать на ноуте rus_verbs:отыскаться{}, // отыскаться на складе rus_verbs:зафиксировать{}, // зафиксировать на пленке rus_verbs:расстилаться{}, // расстилаться на столе rus_verbs:заместить{}, // заместить на посту rus_verbs:угасать{}, // угасать на неуправляемом корабле rus_verbs:сразить{}, // сразить на ринге rus_verbs:расплываться{}, // расплываться на жаре rus_verbs:сосчитать{}, // сосчитать на пальцах rus_verbs:сгуститься{}, // сгуститься на небольшой высоте rus_verbs:цитировать{}, // цитировать на плите rus_verbs:ориентироваться{}, // ориентироваться на местности rus_verbs:расширить{}, // расширить на другом конце rus_verbs:обтереть{}, // обтереть на стоянке rus_verbs:подстрелить{}, // подстрелить на охоте rus_verbs:растереть{}, // растереть на твердой поверхности rus_verbs:подавлять{}, // подавлять на первом этапе rus_verbs:смешиваться{}, // смешиваться на поверхности // инфинитив:вычитать{ aux stress="в^ычитать" }, глагол:вычитать{ aux stress="в^ычитать" }, // вычитать на сайте // деепричастие:вычитав{}, rus_verbs:сократиться{}, // сократиться на втором этапе rus_verbs:занервничать{}, // занервничать на экзамене rus_verbs:соприкоснуться{}, // соприкоснуться на трассе rus_verbs:обозначить{}, // обозначить на плане rus_verbs:обучаться{}, // обучаться на производстве rus_verbs:снизиться{}, // снизиться на большой высоте rus_verbs:простудиться{}, // простудиться на ветру rus_verbs:поддерживаться{}, // поддерживается на встрече rus_verbs:уплыть{}, // уплыть на лодочке rus_verbs:резвиться{}, // резвиться на песочке rus_verbs:поерзать{}, // поерзать на скамеечке rus_verbs:похвастаться{}, // похвастаться на встрече rus_verbs:знакомиться{}, // знакомиться на уроке rus_verbs:проплывать{}, // проплывать на катере rus_verbs:засесть{}, // засесть на чердаке rus_verbs:подцепить{}, // подцепить на дискотеке rus_verbs:обыскать{}, // обыскать на входе rus_verbs:оправдаться{}, // оправдаться на суде rus_verbs:раскрываться{}, // раскрываться на сцене rus_verbs:одеваться{}, // одеваться на вещевом рынке rus_verbs:засветиться{}, // засветиться на фотографиях rus_verbs:употребляться{}, // употребляться на птицефабриках rus_verbs:грабить{}, // грабить на пустыре rus_verbs:гонять{}, // гонять на повышенных оборотах rus_verbs:развеваться{}, // развеваться на древке rus_verbs:основываться{}, // основываться на безусловных фактах rus_verbs:допрашивать{}, // допрашивать на базе rus_verbs:проработать{}, // проработать на стройке rus_verbs:сосредоточить{}, // сосредоточить на месте rus_verbs:сочинять{}, // сочинять на ходу rus_verbs:ползать{}, // ползать на камне rus_verbs:раскинуться{}, // раскинуться на пустыре rus_verbs:уставать{}, // уставать на работе rus_verbs:укрепить{}, // укрепить на конце rus_verbs:образовывать{}, // образовывать на открытом воздухе взрывоопасную смесь rus_verbs:одобрять{}, // одобрять на словах rus_verbs:приговорить{}, // приговорить на заседании тройки rus_verbs:чернеть{}, // чернеть на свету rus_verbs:гнуть{}, // гнуть на станке rus_verbs:размещаться{}, // размещаться на бирже rus_verbs:соорудить{}, // соорудить на даче rus_verbs:пастись{}, // пастись на лугу rus_verbs:формироваться{}, // формироваться на дне rus_verbs:таить{}, // таить на дне rus_verbs:приостановиться{}, // приостановиться на середине rus_verbs:топтаться{}, // топтаться на месте rus_verbs:громить{}, // громить на подступах rus_verbs:вычислить{}, // вычислить на бумажке rus_verbs:заказывать{}, // заказывать на сайте rus_verbs:осуществить{}, // осуществить на практике rus_verbs:обосноваться{}, // обосноваться на верхушке rus_verbs:пытать{}, // пытать на электрическом стуле rus_verbs:совершиться{}, // совершиться на заседании rus_verbs:свернуться{}, // свернуться на медленном огне rus_verbs:пролетать{}, // пролетать на дельтаплане rus_verbs:сбыться{}, // сбыться на самом деле rus_verbs:разговориться{}, // разговориться на уроке rus_verbs:разворачиваться{}, // разворачиваться на перекрестке rus_verbs:преподнести{}, // преподнести на блюдечке rus_verbs:напечатать{}, // напечатать на лазернике rus_verbs:прорвать{}, // прорвать на периферии rus_verbs:раскачиваться{}, // раскачиваться на доске rus_verbs:задерживаться{}, // задерживаться на старте rus_verbs:угощать{}, // угощать на вечеринке rus_verbs:шарить{}, // шарить на столе rus_verbs:увеличивать{}, // увеличивать на первом этапе rus_verbs:рехнуться{}, // рехнуться на старости лет rus_verbs:расцвести{}, // расцвести на грядке rus_verbs:закипеть{}, // закипеть на плите rus_verbs:подлететь{}, // подлететь на параплане rus_verbs:рыться{}, // рыться на свалке rus_verbs:добираться{}, // добираться на попутках rus_verbs:продержаться{}, // продержаться на вершине rus_verbs:разыскивать{}, // разыскивать на выставках rus_verbs:освобождать{}, // освобождать на заседании rus_verbs:передвигаться{}, // передвигаться на самокате rus_verbs:проявиться{}, // проявиться на свету rus_verbs:заскользить{}, // заскользить на льду rus_verbs:пересказать{}, // пересказать на сцене студенческого театра rus_verbs:протестовать{}, // протестовать на улице rus_verbs:указываться{}, // указываться на табличках rus_verbs:прискакать{}, // прискакать на лошадке rus_verbs:копошиться{}, // копошиться на свежем воздухе rus_verbs:подсчитать{}, // подсчитать на бумажке rus_verbs:разволноваться{}, // разволноваться на экзамене rus_verbs:завертеться{}, // завертеться на полу rus_verbs:ознакомиться{}, // ознакомиться на ходу rus_verbs:ржать{}, // ржать на уроке rus_verbs:раскинуть{}, // раскинуть на грядках rus_verbs:разгромить{}, // разгромить на ринге rus_verbs:подслушать{}, // подслушать на совещании rus_verbs:описываться{}, // описываться на страницах книги rus_verbs:качаться{}, // качаться на стуле rus_verbs:усилить{}, // усилить на флангах rus_verbs:набросать{}, // набросать на клочке картона rus_verbs:расстреливать{}, // расстреливать на подходе rus_verbs:запрыгать{}, // запрыгать на одной ноге rus_verbs:сыскать{}, // сыскать на чужбине rus_verbs:подтвердиться{}, // подтвердиться на практике rus_verbs:плескаться{}, // плескаться на мелководье rus_verbs:расширяться{}, // расширяться на конце rus_verbs:подержать{}, // подержать на солнце rus_verbs:планироваться{}, // планироваться на общем собрании rus_verbs:сгинуть{}, // сгинуть на чужбине rus_verbs:замкнуться{}, // замкнуться на точке rus_verbs:закачаться{}, // закачаться на ветру rus_verbs:перечитывать{}, // перечитывать на ходу rus_verbs:перелететь{}, // перелететь на дельтаплане rus_verbs:оживать{}, // оживать на солнце rus_verbs:женить{}, // женить на богатой невесте rus_verbs:заглохнуть{}, // заглохнуть на старте rus_verbs:копаться{}, // копаться на полу rus_verbs:развлекаться{}, // развлекаться на дискотеке rus_verbs:печататься{}, // печататься на струйном принтере rus_verbs:обрываться{}, // обрываться на полуслове rus_verbs:ускакать{}, // ускакать на лошадке rus_verbs:подписывать{}, // подписывать на столе rus_verbs:добывать{}, // добывать на выработке rus_verbs:скопиться{}, // скопиться на выходе rus_verbs:повстречать{}, // повстречать на пути rus_verbs:поцеловаться{}, // поцеловаться на площади rus_verbs:растянуть{}, // растянуть на столе rus_verbs:подаваться{}, // подаваться на благотворительном обеде rus_verbs:повстречаться{}, // повстречаться на митинге rus_verbs:примоститься{}, // примоститься на ступеньках rus_verbs:отразить{}, // отразить на страницах доклада rus_verbs:пояснять{}, // пояснять на страницах приложения rus_verbs:накормить{}, // накормить на кухне rus_verbs:поужинать{}, // поужинать на веранде инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть на митинге деепричастие:спев{}, инфинитив:спеть{ вид:несоверш }, глагол:спеть{ вид:несоверш }, rus_verbs:топить{}, // топить на мелководье rus_verbs:освоить{}, // освоить на практике rus_verbs:распластаться{}, // распластаться на травке rus_verbs:отплыть{}, // отплыть на старом каяке rus_verbs:улетать{}, // улетать на любом самолете rus_verbs:отстаивать{}, // отстаивать на корте rus_verbs:осуждать{}, // осуждать на словах rus_verbs:переговорить{}, // переговорить на обеде rus_verbs:укрыть{}, // укрыть на чердаке rus_verbs:томиться{}, // томиться на привязи rus_verbs:сжигать{}, // сжигать на полигоне rus_verbs:позавтракать{}, // позавтракать на лоне природы rus_verbs:функционировать{}, // функционирует на солнечной энергии rus_verbs:разместить{}, // разместить на сайте rus_verbs:пронести{}, // пронести на теле rus_verbs:нашарить{}, // нашарить на столе rus_verbs:корчиться{}, // корчиться на полу rus_verbs:распознать{}, // распознать на снимке rus_verbs:повеситься{}, // повеситься на шнуре rus_verbs:обозначиться{}, // обозначиться на картах rus_verbs:оступиться{}, // оступиться на скользком льду rus_verbs:подносить{}, // подносить на блюдечке rus_verbs:расстелить{}, // расстелить на газоне rus_verbs:обсуждаться{}, // обсуждаться на собрании rus_verbs:расписаться{}, // расписаться на бланке rus_verbs:плестись{}, // плестись на привязи rus_verbs:объявиться{}, // объявиться на сцене rus_verbs:повышаться{}, // повышаться на первом датчике rus_verbs:разрабатывать{}, // разрабатывать на заводе rus_verbs:прерывать{}, // прерывать на середине rus_verbs:каяться{}, // каяться на публике rus_verbs:освоиться{}, // освоиться на лошади rus_verbs:подплыть{}, // подплыть на плоту rus_verbs:оскорбить{}, // оскорбить на митинге rus_verbs:торжествовать{}, // торжествовать на пьедестале rus_verbs:поправлять{}, // поправлять на одежде rus_verbs:отражать{}, // отражать на картине rus_verbs:дремать{}, // дремать на кушетке rus_verbs:применяться{}, // применяться на производстве стали rus_verbs:поражать{}, // поражать на большой дистанции rus_verbs:расстрелять{}, // расстрелять на окраине хутора rus_verbs:рассчитать{}, // рассчитать на калькуляторе rus_verbs:записывать{}, // записывать на ленте rus_verbs:перебирать{}, // перебирать на ладони rus_verbs:разбиться{}, // разбиться на катере rus_verbs:поискать{}, // поискать на ферме rus_verbs:прятать{}, // прятать на заброшенном складе rus_verbs:пропеть{}, // пропеть на эстраде rus_verbs:замелькать{}, // замелькать на экране rus_verbs:грустить{}, // грустить на веранде rus_verbs:крутить{}, // крутить на оси rus_verbs:подготовить{}, // подготовить на конспиративной квартире rus_verbs:различать{}, // различать на картинке rus_verbs:киснуть{}, // киснуть на чужбине rus_verbs:оборваться{}, // оборваться на полуслове rus_verbs:запутаться{}, // запутаться на простейшем тесте rus_verbs:общаться{}, // общаться на уроке rus_verbs:производиться{}, // производиться на фабрике rus_verbs:сочинить{}, // сочинить на досуге rus_verbs:давить{}, // давить на лице rus_verbs:разработать{}, // разработать на секретном предприятии rus_verbs:качать{}, // качать на качелях rus_verbs:тушить{}, // тушить на крыше пожар rus_verbs:охранять{}, // охранять на территории базы rus_verbs:приметить{}, // приметить на взгорке rus_verbs:скрыть{}, // скрыть на теле rus_verbs:удерживать{}, // удерживать на руке rus_verbs:усвоить{}, // усвоить на уроке rus_verbs:растаять{}, // растаять на солнечной стороне rus_verbs:красоваться{}, // красоваться на виду rus_verbs:сохраняться{}, // сохраняться на холоде rus_verbs:лечить{}, // лечить на дому rus_verbs:прокатиться{}, // прокатиться на уницикле rus_verbs:договариваться{}, // договариваться на нейтральной территории rus_verbs:качнуться{}, // качнуться на одной ноге rus_verbs:опубликовать{}, // опубликовать на сайте rus_verbs:отражаться{}, // отражаться на поверхности воды rus_verbs:обедать{}, // обедать на веранде rus_verbs:посидеть{}, // посидеть на лавочке rus_verbs:сообщаться{}, // сообщаться на официальном сайте rus_verbs:свершиться{}, // свершиться на заседании rus_verbs:ночевать{}, // ночевать на даче rus_verbs:темнеть{}, // темнеть на свету rus_verbs:гибнуть{}, // гибнуть на территории полигона rus_verbs:усиливаться{}, // усиливаться на территории округа rus_verbs:проживать{}, // проживать на даче rus_verbs:исследовать{}, // исследовать на большой глубине rus_verbs:обитать{}, // обитать на громадной глубине rus_verbs:сталкиваться{}, // сталкиваться на большой высоте rus_verbs:таиться{}, // таиться на большой глубине rus_verbs:спасать{}, // спасать на пожаре rus_verbs:сказываться{}, // сказываться на общем результате rus_verbs:заблудиться{}, // заблудиться на стройке rus_verbs:пошарить{}, // пошарить на полках rus_verbs:планировать{}, // планировать на бумаге rus_verbs:ранить{}, // ранить на полигоне rus_verbs:хлопать{}, // хлопать на сцене rus_verbs:основать{}, // основать на горе новый монастырь rus_verbs:отбить{}, // отбить на столе rus_verbs:отрицать{}, // отрицать на заседании комиссии rus_verbs:устоять{}, // устоять на ногах rus_verbs:отзываться{}, // отзываться на страницах отчёта rus_verbs:притормозить{}, // притормозить на обочине rus_verbs:читаться{}, // читаться на лице rus_verbs:заиграть{}, // заиграть на саксофоне rus_verbs:зависнуть{}, // зависнуть на игровой площадке rus_verbs:сознаться{}, // сознаться на допросе rus_verbs:выясняться{}, // выясняться на очной ставке rus_verbs:наводить{}, // наводить на столе порядок rus_verbs:покоиться{}, // покоиться на кладбище rus_verbs:значиться{}, // значиться на бейджике rus_verbs:съехать{}, // съехать на санках rus_verbs:познакомить{}, // познакомить на свадьбе rus_verbs:завязать{}, // завязать на спине rus_verbs:грохнуть{}, // грохнуть на площади rus_verbs:разъехаться{}, // разъехаться на узкой дороге rus_verbs:столпиться{}, // столпиться на крыльце rus_verbs:порыться{}, // порыться на полках rus_verbs:ослабить{}, // ослабить на шее rus_verbs:оправдывать{}, // оправдывать на суде rus_verbs:обнаруживаться{}, // обнаруживаться на складе rus_verbs:спастись{}, // спастись на дереве rus_verbs:прерваться{}, // прерваться на полуслове rus_verbs:строиться{}, // строиться на пустыре rus_verbs:познать{}, // познать на практике rus_verbs:путешествовать{}, // путешествовать на поезде rus_verbs:побеждать{}, // побеждать на ринге rus_verbs:рассматриваться{}, // рассматриваться на заседании rus_verbs:продаваться{}, // продаваться на открытом рынке rus_verbs:разместиться{}, // разместиться на базе rus_verbs:завыть{}, // завыть на холме rus_verbs:настигнуть{}, // настигнуть на окраине rus_verbs:укрыться{}, // укрыться на чердаке rus_verbs:расплакаться{}, // расплакаться на заседании комиссии rus_verbs:заканчивать{}, // заканчивать на последнем задании rus_verbs:пролежать{}, // пролежать на столе rus_verbs:громоздиться{}, // громоздиться на полу rus_verbs:замерзнуть{}, // замерзнуть на открытом воздухе rus_verbs:поскользнуться{}, // поскользнуться на льду rus_verbs:таскать{}, // таскать на спине rus_verbs:просматривать{}, // просматривать на сайте rus_verbs:обдумать{}, // обдумать на досуге rus_verbs:гадать{}, // гадать на кофейной гуще rus_verbs:останавливать{}, // останавливать на выходе rus_verbs:обозначать{}, // обозначать на странице rus_verbs:долететь{}, // долететь на спортивном байке rus_verbs:тесниться{}, // тесниться на чердачке rus_verbs:хоронить{}, // хоронить на частном кладбище rus_verbs:установиться{}, // установиться на юге rus_verbs:прикидывать{}, // прикидывать на клочке бумаги rus_verbs:затаиться{}, // затаиться на дереве rus_verbs:раздобыть{}, // раздобыть на складе rus_verbs:перебросить{}, // перебросить на вертолетах rus_verbs:захватывать{}, // захватывать на базе rus_verbs:сказаться{}, // сказаться на итоговых оценках rus_verbs:покачиваться{}, // покачиваться на волнах rus_verbs:крутиться{}, // крутиться на кухне rus_verbs:помещаться{}, // помещаться на полке rus_verbs:питаться{}, // питаться на помойке rus_verbs:отдохнуть{}, // отдохнуть на загородной вилле rus_verbs:кататься{}, // кататься на велике rus_verbs:поработать{}, // поработать на стройке rus_verbs:ограбить{}, // ограбить на пустыре rus_verbs:зарабатывать{}, // зарабатывать на бирже rus_verbs:преуспеть{}, // преуспеть на ниве искусства rus_verbs:заерзать{}, // заерзать на стуле rus_verbs:разъяснить{}, // разъяснить на полях rus_verbs:отчеканить{}, // отчеканить на медной пластине rus_verbs:торговать{}, // торговать на рынке rus_verbs:поколебаться{}, // поколебаться на пороге rus_verbs:прикинуть{}, // прикинуть на бумажке rus_verbs:рассечь{}, // рассечь на тупом конце rus_verbs:посмеяться{}, // посмеяться на переменке rus_verbs:остыть{}, // остыть на морозном воздухе rus_verbs:запереться{}, // запереться на чердаке rus_verbs:обогнать{}, // обогнать на повороте rus_verbs:подтянуться{}, // подтянуться на турнике rus_verbs:привозить{}, // привозить на машине rus_verbs:подбирать{}, // подбирать на полу rus_verbs:уничтожать{}, // уничтожать на подходе rus_verbs:притаиться{}, // притаиться на вершине rus_verbs:плясать{}, // плясать на костях rus_verbs:поджидать{}, // поджидать на вокзале rus_verbs:закончить{}, // Мы закончили игру на самом интересном месте (САМ не может быть первым прилагательным в цепочке!) rus_verbs:смениться{}, // смениться на посту rus_verbs:посчитать{}, // посчитать на пальцах rus_verbs:прицелиться{}, // прицелиться на бегу rus_verbs:нарисовать{}, // нарисовать на стене rus_verbs:прыгать{}, // прыгать на сцене rus_verbs:повертеть{}, // повертеть на пальце rus_verbs:попрощаться{}, // попрощаться на панихиде инфинитив:просыпаться{ вид:соверш }, глагол:просыпаться{ вид:соверш }, // просыпаться на диване rus_verbs:разобрать{}, // разобрать на столе rus_verbs:помереть{}, // помереть на чужбине rus_verbs:различить{}, // различить на нечеткой фотографии rus_verbs:рисовать{}, // рисовать на доске rus_verbs:проследить{}, // проследить на экране rus_verbs:задремать{}, // задремать на диване rus_verbs:ругаться{}, // ругаться на людях rus_verbs:сгореть{}, // сгореть на работе rus_verbs:зазвучать{}, // зазвучать на коротких волнах rus_verbs:задохнуться{}, // задохнуться на вершине горы rus_verbs:порождать{}, // порождать на поверхности небольшую рябь rus_verbs:отдыхать{}, // отдыхать на курорте rus_verbs:образовать{}, // образовать на дне толстый слой rus_verbs:поправиться{}, // поправиться на дармовых харчах rus_verbs:отмечать{}, // отмечать на календаре rus_verbs:реять{}, // реять на флагштоке rus_verbs:ползти{}, // ползти на коленях rus_verbs:продавать{}, // продавать на аукционе rus_verbs:сосредоточиться{}, // сосредоточиться на основной задаче rus_verbs:рыскать{}, // мышки рыскали на кухне rus_verbs:расстегнуть{}, // расстегнуть на куртке все пуговицы rus_verbs:напасть{}, // напасть на территории другого государства rus_verbs:издать{}, // издать на западе rus_verbs:оставаться{}, // оставаться на страже порядка rus_verbs:появиться{}, // наконец появиться на экране rus_verbs:лежать{}, // лежать на столе rus_verbs:ждать{}, // ждать на берегу инфинитив:писать{aux stress="пис^ать"}, // писать на бумаге глагол:писать{aux stress="пис^ать"}, rus_verbs:оказываться{}, // оказываться на полу rus_verbs:поставить{}, // поставить на столе rus_verbs:держать{}, // держать на крючке rus_verbs:выходить{}, // выходить на остановке rus_verbs:заговорить{}, // заговорить на китайском языке rus_verbs:ожидать{}, // ожидать на стоянке rus_verbs:закричать{}, // закричал на минарете муэдзин rus_verbs:простоять{}, // простоять на посту rus_verbs:продолжить{}, // продолжить на первом этаже rus_verbs:ощутить{}, // ощутить на себе влияние кризиса rus_verbs:состоять{}, // состоять на учете rus_verbs:готовиться{}, инфинитив:акклиматизироваться{вид:несоверш}, // альпинисты готовятся акклиматизироваться на новой высоте глагол:акклиматизироваться{вид:несоверш}, rus_verbs:арестовать{}, // грабители были арестованы на месте преступления rus_verbs:схватить{}, // грабители были схвачены на месте преступления инфинитив:атаковать{ вид:соверш }, // взвод был атакован на границе глагол:атаковать{ вид:соверш }, прилагательное:атакованный{ вид:соверш }, прилагательное:атаковавший{ вид:соверш }, rus_verbs:базировать{}, // установка будет базирована на границе rus_verbs:базироваться{}, // установка базируется на границе rus_verbs:барахтаться{}, // дети барахтались на мелководье rus_verbs:браконьерить{}, // Охотники браконьерили ночью на реке rus_verbs:браконьерствовать{}, // Охотники ночью браконьерствовали на реке rus_verbs:бренчать{}, // парень что-то бренчал на гитаре rus_verbs:бренькать{}, // парень что-то бренькает на гитаре rus_verbs:начать{}, // Рынок акций РФ начал торги на отрицательной территории. rus_verbs:буксовать{}, // Колеса буксуют на льду rus_verbs:вертеться{}, // Непоседливый ученик много вертится на стуле rus_verbs:взвести{}, // Боец взвел на оружии предохранитель rus_verbs:вилять{}, // Машина сильно виляла на дороге rus_verbs:висеть{}, // Яблоко висит на ветке rus_verbs:возлежать{}, // возлежать на лежанке rus_verbs:подниматься{}, // Мы поднимаемся на лифте rus_verbs:подняться{}, // Мы поднимемся на лифте rus_verbs:восседать{}, // Коля восседает на лошади rus_verbs:воссиять{}, // Луна воссияла на небе rus_verbs:воцариться{}, // Мир воцарился на всей земле rus_verbs:воцаряться{}, // Мир воцаряется на всей земле rus_verbs:вращать{}, // вращать на поясе rus_verbs:вращаться{}, // вращаться на поясе rus_verbs:встретить{}, // встретить друга на улице rus_verbs:встретиться{}, // встретиться на занятиях rus_verbs:встречать{}, // встречать на занятиях rus_verbs:въебывать{}, // въебывать на работе rus_verbs:въезжать{}, // въезжать на автомобиле rus_verbs:въехать{}, // въехать на автомобиле rus_verbs:выгорать{}, // ткань выгорает на солнце rus_verbs:выгореть{}, // ткань выгорела на солнце rus_verbs:выгравировать{}, // выгравировать на табличке надпись rus_verbs:выжить{}, // выжить на необитаемом острове rus_verbs:вылежаться{}, // помидоры вылежались на солнце rus_verbs:вылеживаться{}, // вылеживаться на солнце rus_verbs:выместить{}, // выместить на ком-то злобу rus_verbs:вымещать{}, // вымещать на ком-то свое раздражение rus_verbs:вымещаться{}, // вымещаться на ком-то rus_verbs:выращивать{}, // выращивать на грядке помидоры rus_verbs:выращиваться{}, // выращиваться на грядке инфинитив:вырезать{вид:соверш}, // вырезать на доске надпись глагол:вырезать{вид:соверш}, инфинитив:вырезать{вид:несоверш}, глагол:вырезать{вид:несоверш}, rus_verbs:вырисоваться{}, // вырисоваться на графике rus_verbs:вырисовываться{}, // вырисовываться на графике rus_verbs:высаживать{}, // высаживать на необитаемом острове rus_verbs:высаживаться{}, // высаживаться на острове rus_verbs:высвечивать{}, // высвечивать на дисплее температуру rus_verbs:высвечиваться{}, // высвечиваться на дисплее rus_verbs:выстроить{}, // выстроить на фундаменте rus_verbs:выстроиться{}, // выстроиться на плацу rus_verbs:выстудить{}, // выстудить на морозе rus_verbs:выстудиться{}, // выстудиться на морозе rus_verbs:выстужать{}, // выстужать на морозе rus_verbs:выстуживать{}, // выстуживать на морозе rus_verbs:выстуживаться{}, // выстуживаться на морозе rus_verbs:выстукать{}, // выстукать на клавиатуре rus_verbs:выстукивать{}, // выстукивать на клавиатуре rus_verbs:выстукиваться{}, // выстукиваться на клавиатуре rus_verbs:выступать{}, // выступать на сцене rus_verbs:выступить{}, // выступить на сцене rus_verbs:выстучать{}, // выстучать на клавиатуре rus_verbs:выстывать{}, // выстывать на морозе rus_verbs:выстыть{}, // выстыть на морозе rus_verbs:вытатуировать{}, // вытатуировать на руке якорь rus_verbs:говорить{}, // говорить на повышенных тонах rus_verbs:заметить{}, // заметить на берегу rus_verbs:стоять{}, // твёрдо стоять на ногах rus_verbs:оказаться{}, // оказаться на передовой линии rus_verbs:почувствовать{}, // почувствовать на своей шкуре rus_verbs:остановиться{}, // остановиться на первом пункте rus_verbs:показаться{}, // показаться на горизонте rus_verbs:чувствовать{}, // чувствовать на своей шкуре rus_verbs:искать{}, // искать на открытом пространстве rus_verbs:иметься{}, // иметься на складе rus_verbs:клясться{}, // клясться на Коране rus_verbs:прервать{}, // прервать на полуслове rus_verbs:играть{}, // играть на чувствах rus_verbs:спуститься{}, // спуститься на парашюте rus_verbs:понадобиться{}, // понадобиться на экзамене rus_verbs:служить{}, // служить на флоте rus_verbs:подобрать{}, // подобрать на улице rus_verbs:появляться{}, // появляться на сцене rus_verbs:селить{}, // селить на чердаке rus_verbs:поймать{}, // поймать на границе rus_verbs:увидать{}, // увидать на опушке rus_verbs:подождать{}, // подождать на перроне rus_verbs:прочесть{}, // прочесть на полях rus_verbs:тонуть{}, // тонуть на мелководье rus_verbs:ощущать{}, // ощущать на коже rus_verbs:отметить{}, // отметить на полях rus_verbs:показывать{}, // показывать на графике rus_verbs:разговаривать{}, // разговаривать на иностранном языке rus_verbs:прочитать{}, // прочитать на сайте rus_verbs:попробовать{}, // попробовать на практике rus_verbs:замечать{}, // замечать на коже грязь rus_verbs:нести{}, // нести на плечах rus_verbs:носить{}, // носить на голове rus_verbs:гореть{}, // гореть на работе rus_verbs:застыть{}, // застыть на пороге инфинитив:жениться{ вид:соверш }, // жениться на королеве глагол:жениться{ вид:соверш }, прилагательное:женатый{}, прилагательное:женившийся{}, rus_verbs:спрятать{}, // спрятать на чердаке rus_verbs:развернуться{}, // развернуться на плацу rus_verbs:строить{}, // строить на песке rus_verbs:устроить{}, // устроить на даче тестральный вечер rus_verbs:настаивать{}, // настаивать на выполнении приказа rus_verbs:находить{}, // находить на берегу rus_verbs:мелькнуть{}, // мелькнуть на экране rus_verbs:очутиться{}, // очутиться на опушке леса инфинитив:использовать{вид:соверш}, // использовать на работе глагол:использовать{вид:соверш}, инфинитив:использовать{вид:несоверш}, глагол:использовать{вид:несоверш}, прилагательное:использованный{}, прилагательное:использующий{}, прилагательное:использовавший{}, rus_verbs:лететь{}, // лететь на воздушном шаре rus_verbs:смеяться{}, // смеяться на сцене rus_verbs:ездить{}, // ездить на мопеде rus_verbs:заснуть{}, // заснуть на диване rus_verbs:застать{}, // застать на рабочем месте rus_verbs:очнуться{}, // очнуться на больничной койке rus_verbs:разглядеть{}, // разглядеть на фотографии rus_verbs:обойти{}, // обойти на вираже rus_verbs:удержаться{}, // удержаться на троне rus_verbs:побывать{}, // побывать на другой планете rus_verbs:заняться{}, // заняться на выходных делом rus_verbs:вянуть{}, // вянуть на солнце rus_verbs:постоять{}, // постоять на голове rus_verbs:приобрести{}, // приобрести на распродаже rus_verbs:попасться{}, // попасться на краже rus_verbs:продолжаться{}, // продолжаться на земле rus_verbs:открывать{}, // открывать на арене rus_verbs:создавать{}, // создавать на сцене rus_verbs:обсуждать{}, // обсуждать на кухне rus_verbs:отыскать{}, // отыскать на полу rus_verbs:уснуть{}, // уснуть на диване rus_verbs:задержаться{}, // задержаться на работе rus_verbs:курить{}, // курить на свежем воздухе rus_verbs:приподняться{}, // приподняться на локтях rus_verbs:установить{}, // установить на вершине rus_verbs:запереть{}, // запереть на балконе rus_verbs:синеть{}, // синеть на воздухе rus_verbs:убивать{}, // убивать на нейтральной территории rus_verbs:скрываться{}, // скрываться на даче rus_verbs:родить{}, // родить на полу rus_verbs:описать{}, // описать на страницах книги rus_verbs:перехватить{}, // перехватить на подлете rus_verbs:скрывать{}, // скрывать на даче rus_verbs:сменить{}, // сменить на посту rus_verbs:мелькать{}, // мелькать на экране rus_verbs:присутствовать{}, // присутствовать на мероприятии rus_verbs:украсть{}, // украсть на рынке rus_verbs:победить{}, // победить на ринге rus_verbs:упомянуть{}, // упомянуть на страницах романа rus_verbs:плыть{}, // плыть на старой лодке rus_verbs:повиснуть{}, // повиснуть на перекладине rus_verbs:нащупать{}, // нащупать на дне rus_verbs:затихнуть{}, // затихнуть на дне rus_verbs:построить{}, // построить на участке rus_verbs:поддерживать{}, // поддерживать на поверхности rus_verbs:заработать{}, // заработать на бирже rus_verbs:провалиться{}, // провалиться на экзамене rus_verbs:сохранить{}, // сохранить на диске rus_verbs:располагаться{}, // располагаться на софе rus_verbs:поклясться{}, // поклясться на библии rus_verbs:сражаться{}, // сражаться на арене rus_verbs:спускаться{}, // спускаться на дельтаплане rus_verbs:уничтожить{}, // уничтожить на подступах rus_verbs:изучить{}, // изучить на практике rus_verbs:рождаться{}, // рождаться на праздниках rus_verbs:прилететь{}, // прилететь на самолете rus_verbs:догнать{}, // догнать на перекрестке rus_verbs:изобразить{}, // изобразить на бумаге rus_verbs:проехать{}, // проехать на тракторе rus_verbs:приготовить{}, // приготовить на масле rus_verbs:споткнуться{}, // споткнуться на полу rus_verbs:собирать{}, // собирать на берегу rus_verbs:отсутствовать{}, // отсутствовать на тусовке rus_verbs:приземлиться{}, // приземлиться на военном аэродроме rus_verbs:сыграть{}, // сыграть на трубе rus_verbs:прятаться{}, // прятаться на даче rus_verbs:спрятаться{}, // спрятаться на чердаке rus_verbs:провозгласить{}, // провозгласить на митинге rus_verbs:изложить{}, // изложить на бумаге rus_verbs:использоваться{}, // использоваться на практике rus_verbs:замяться{}, // замяться на входе rus_verbs:раздаваться{}, // Крик ягуара раздается на краю болота rus_verbs:сверкнуть{}, // сверкнуть на солнце rus_verbs:сверкать{}, // сверкать на свету rus_verbs:задержать{}, // задержать на митинге rus_verbs:осечься{}, // осечься на первом слове rus_verbs:хранить{}, // хранить на банковском счету rus_verbs:шутить{}, // шутить на уроке rus_verbs:кружиться{}, // кружиться на балу rus_verbs:чертить{}, // чертить на доске rus_verbs:отразиться{}, // отразиться на оценках rus_verbs:греть{}, // греть на солнце rus_verbs:рассуждать{}, // рассуждать на страницах своей книги rus_verbs:окружать{}, // окружать на острове rus_verbs:сопровождать{}, // сопровождать на охоте rus_verbs:заканчиваться{}, // заканчиваться на самом интересном месте rus_verbs:содержаться{}, // содержаться на приусадебном участке rus_verbs:поселиться{}, // поселиться на даче rus_verbs:запеть{}, // запеть на сцене инфинитив:провозить{ вид:несоверш }, // провозить на теле глагол:провозить{ вид:несоверш }, прилагательное:провезенный{}, прилагательное:провозивший{вид:несоверш}, прилагательное:провозящий{вид:несоверш}, деепричастие:провозя{}, rus_verbs:мочить{}, // мочить на месте rus_verbs:преследовать{}, // преследовать на территории другого штата rus_verbs:пролететь{}, // пролетел на параплане rus_verbs:драться{}, // драться на рапирах rus_verbs:просидеть{}, // просидеть на занятиях rus_verbs:убираться{}, // убираться на балконе rus_verbs:таять{}, // таять на солнце rus_verbs:проверять{}, // проверять на полиграфе rus_verbs:убеждать{}, // убеждать на примере rus_verbs:скользить{}, // скользить на льду rus_verbs:приобретать{}, // приобретать на распродаже rus_verbs:летать{}, // летать на метле rus_verbs:толпиться{}, // толпиться на перроне rus_verbs:плавать{}, // плавать на надувном матрасе rus_verbs:описывать{}, // описывать на страницах повести rus_verbs:пробыть{}, // пробыть на солнце слишком долго rus_verbs:застрять{}, // застрять на верхнем этаже rus_verbs:метаться{}, // метаться на полу rus_verbs:сжечь{}, // сжечь на костре rus_verbs:расслабиться{}, // расслабиться на кушетке rus_verbs:услыхать{}, // услыхать на рынке rus_verbs:удержать{}, // удержать на прежнем уровне rus_verbs:образоваться{}, // образоваться на дне rus_verbs:рассмотреть{}, // рассмотреть на поверхности чипа rus_verbs:уезжать{}, // уезжать на попутке rus_verbs:похоронить{}, // похоронить на закрытом кладбище rus_verbs:настоять{}, // настоять на пересмотре оценок rus_verbs:растянуться{}, // растянуться на горячем песке rus_verbs:покрутить{}, // покрутить на шесте rus_verbs:обнаружиться{}, // обнаружиться на болоте rus_verbs:гулять{}, // гулять на свадьбе rus_verbs:утонуть{}, // утонуть на курорте rus_verbs:храниться{}, // храниться на депозите rus_verbs:танцевать{}, // танцевать на свадьбе rus_verbs:трудиться{}, // трудиться на заводе инфинитив:засыпать{переходность:непереходный вид:несоверш}, // засыпать на кровати глагол:засыпать{переходность:непереходный вид:несоверш}, деепричастие:засыпая{переходность:непереходный вид:несоверш}, прилагательное:засыпавший{переходность:непереходный вид:несоверш}, прилагательное:засыпающий{ вид:несоверш переходность:непереходный }, // ребенок, засыпающий на руках rus_verbs:сушить{}, // сушить на открытом воздухе rus_verbs:зашевелиться{}, // зашевелиться на чердаке rus_verbs:обдумывать{}, // обдумывать на досуге rus_verbs:докладывать{}, // докладывать на научной конференции rus_verbs:промелькнуть{}, // промелькнуть на экране // прилагательное:находящийся{ вид:несоверш }, // колонна, находящаяся на ничейной территории прилагательное:написанный{}, // слово, написанное на заборе rus_verbs:умещаться{}, // компьютер, умещающийся на ладони rus_verbs:открыть{}, // книга, открытая на последней странице rus_verbs:спать{}, // йог, спящий на гвоздях rus_verbs:пробуксовывать{}, // колесо, пробуксовывающее на обледенелом асфальте rus_verbs:забуксовать{}, // колесо, забуксовавшее на обледенелом асфальте rus_verbs:отобразиться{}, // удивление, отобразившееся на лице rus_verbs:увидеть{}, // на полу я увидел чьи-то следы rus_verbs:видеть{}, // на полу я вижу чьи-то следы rus_verbs:оставить{}, // Мел оставил на доске белый след. rus_verbs:оставлять{}, // Мел оставляет на доске белый след. rus_verbs:встречаться{}, // встречаться на лекциях rus_verbs:познакомиться{}, // познакомиться на занятиях rus_verbs:устроиться{}, // она устроилась на кровати rus_verbs:ложиться{}, // ложись на полу rus_verbs:останавливаться{}, // останавливаться на достигнутом rus_verbs:спотыкаться{}, // спотыкаться на ровном месте rus_verbs:распечатать{}, // распечатать на бумаге rus_verbs:распечатывать{}, // распечатывать на бумаге rus_verbs:просмотреть{}, // просмотреть на бумаге rus_verbs:закрепляться{}, // закрепляться на плацдарме rus_verbs:погреться{}, // погреться на солнышке rus_verbs:мешать{}, // Он мешал краски на палитре. rus_verbs:занять{}, // Он занял первое место на соревнованиях. rus_verbs:заговариваться{}, // Он заговаривался иногда на уроках. деепричастие:женившись{ вид:соверш }, rus_verbs:везти{}, // Он везёт песок на тачке. прилагательное:казненный{}, // Он был казнён на электрическом стуле. rus_verbs:прожить{}, // Он безвыездно прожил всё лето на даче. rus_verbs:принести{}, // Официантка принесла нам обед на подносе. rus_verbs:переписать{}, // Перепишите эту рукопись на машинке. rus_verbs:идти{}, // Поезд идёт на малой скорости. rus_verbs:петь{}, // птички поют на рассвете rus_verbs:смотреть{}, // Смотри на обороте. rus_verbs:прибрать{}, // прибрать на столе rus_verbs:прибраться{}, // прибраться на столе rus_verbs:растить{}, // растить капусту на огороде rus_verbs:тащить{}, // тащить ребенка на руках rus_verbs:убирать{}, // убирать на столе rus_verbs:простыть{}, // Я простыл на морозе. rus_verbs:сиять{}, // ясные звезды мирно сияли на безоблачном весеннем небе. rus_verbs:проводиться{}, // такие эксперименты не проводятся на воде rus_verbs:достать{}, // Я не могу достать до яблок на верхних ветках. rus_verbs:расплыться{}, // Чернила расплылись на плохой бумаге. rus_verbs:вскочить{}, // У него вскочил прыщ на носу. rus_verbs:свить{}, // У нас на балконе воробей свил гнездо. rus_verbs:оторваться{}, // У меня на пальто оторвалась пуговица. rus_verbs:восходить{}, // Солнце восходит на востоке. rus_verbs:блестеть{}, // Снег блестит на солнце. rus_verbs:побить{}, // Рысак побил всех лошадей на скачках. rus_verbs:литься{}, // Реки крови льются на войне. rus_verbs:держаться{}, // Ребёнок уже твёрдо держится на ногах. rus_verbs:клубиться{}, // Пыль клубится на дороге. инфинитив:написать{ aux stress="напис^ать" }, // Ты должен написать статью на английском языке глагол:написать{ aux stress="напис^ать" }, // Он написал статью на русском языке. // глагол:находиться{вид:несоверш}, // мой поезд находится на первом пути // инфинитив:находиться{вид:несоверш}, rus_verbs:жить{}, // Было интересно жить на курорте. rus_verbs:повидать{}, // Он много повидал на своём веку. rus_verbs:разъезжаться{}, // Ноги разъезжаются не только на льду. rus_verbs:расположиться{}, // Оба села расположились на берегу реки. rus_verbs:объясняться{}, // Они объясняются на иностранном языке. rus_verbs:прощаться{}, // Они долго прощались на вокзале. rus_verbs:работать{}, // Она работает на ткацкой фабрике. rus_verbs:купить{}, // Она купила молоко на рынке. rus_verbs:поместиться{}, // Все книги поместились на полке. глагол:проводить{вид:несоверш}, инфинитив:проводить{вид:несоверш}, // Нужно проводить теорию на практике. rus_verbs:пожить{}, // Недолго она пожила на свете. rus_verbs:краснеть{}, // Небо краснеет на закате. rus_verbs:бывать{}, // На Волге бывает сильное волнение. rus_verbs:ехать{}, // Мы туда ехали на автобусе. rus_verbs:провести{}, // Мы провели месяц на даче. rus_verbs:поздороваться{}, // Мы поздоровались при встрече на улице. rus_verbs:расти{}, // Арбузы растут теперь не только на юге. ГЛ_ИНФ(сидеть), // три больших пса сидят на траве ГЛ_ИНФ(сесть), // три больших пса сели на траву ГЛ_ИНФ(перевернуться), // На дороге перевернулся автомобиль ГЛ_ИНФ(повезти), // я повезу тебя на машине ГЛ_ИНФ(отвезти), // мы отвезем тебя на такси ГЛ_ИНФ(пить), // пить на кухне чай ГЛ_ИНФ(найти), // найти на острове ГЛ_ИНФ(быть), // на этих костях есть следы зубов ГЛ_ИНФ(высадиться), // помощники высадились на острове ГЛ_ИНФ(делать),прилагательное:делающий{}, прилагательное:делавший{}, деепричастие:делая{}, // смотрю фильм о том, что пираты делали на необитаемом острове ГЛ_ИНФ(случиться), // это случилось на опушке леса ГЛ_ИНФ(продать), ГЛ_ИНФ(есть) // кошки ели мой корм на песчаном берегу } #endregion VerbList // Чтобы разрешить связывание в паттернах типа: смотреть на youtube fact гл_предл { if context { Гл_НА_Предл предлог:в{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { Гл_НА_Предл предлог:на{} *:*{падеж:предл} } then return true } // локатив fact гл_предл { if context { Гл_НА_Предл предлог:на{} *:*{падеж:мест} } then return true } #endregion ПРЕДЛОЖНЫЙ #region ВИНИТЕЛЬНЫЙ // НА+винительный падеж: // ЗАБИРАТЬСЯ НА ВЕРШИНУ ГОРЫ #region VerbList wordentry_set Гл_НА_Вин= { rus_verbs:переметнуться{}, // Ее взгляд растерянно переметнулся на Лили. rus_verbs:отогнать{}, // Водитель отогнал машину на стоянку. rus_verbs:фапать{}, // Не фапай на желтяк и не перебивай. rus_verbs:умножить{}, // Умножьте это количество примерно на 10. //rus_verbs:умножать{}, rus_verbs:откатить{}, // Откатил Шпак валун на шлях и перекрыл им дорогу. rus_verbs:откатывать{}, rus_verbs:доносить{}, // Вот и побежали на вас доносить. rus_verbs:донести{}, rus_verbs:разбирать{}, // Ворованные автомобили злоумышленники разбирали на запчасти и продавали. безлич_глагол:хватит{}, // - На одну атаку хватит. rus_verbs:скупиться{}, // Он сражался за жизнь, не скупясь на хитрости и усилия, и пока этот стиль давал неплохие результаты. rus_verbs:поскупиться{}, // Не поскупись на похвалы! rus_verbs:подыматься{}, rus_verbs:транспортироваться{}, rus_verbs:бахнуть{}, // Бахнуть стакан на пол rus_verbs:РАЗДЕЛИТЬ{}, // Президентские выборы разделили Венесуэлу на два непримиримых лагеря (РАЗДЕЛИТЬ) rus_verbs:НАЦЕЛИВАТЬСЯ{}, // Невдалеке пролетел кондор, нацеливаясь на бизонью тушу. (НАЦЕЛИВАТЬСЯ) rus_verbs:ВЫПЛЕСНУТЬ{}, // Низкий вибрирующий гул напоминал вулкан, вот-вот готовый выплеснуть на земную твердь потоки раскаленной лавы. (ВЫПЛЕСНУТЬ) rus_verbs:ИСЧЕЗНУТЬ{}, // Оно фыркнуло и исчезло в лесу на другой стороне дороги (ИСЧЕЗНУТЬ) rus_verbs:ВЫЗВАТЬ{}, // вызвать своего брата на поединок. (ВЫЗВАТЬ) rus_verbs:ПОБРЫЗГАТЬ{}, // Матрос побрызгал немного фимиама на крошечный огонь (ПОБРЫЗГАТЬ/БРЫЗГАТЬ/БРЫЗНУТЬ/КАПНУТЬ/КАПАТЬ/ПОКАПАТЬ) rus_verbs:БРЫЗГАТЬ{}, rus_verbs:БРЫЗНУТЬ{}, rus_verbs:КАПНУТЬ{}, rus_verbs:КАПАТЬ{}, rus_verbs:ПОКАПАТЬ{}, rus_verbs:ПООХОТИТЬСЯ{}, // Мы можем когда-нибудь вернуться и поохотиться на него. (ПООХОТИТЬСЯ/ОХОТИТЬСЯ) rus_verbs:ОХОТИТЬСЯ{}, // rus_verbs:ПОПАСТЬСЯ{}, // Не думал я, что они попадутся на это (ПОПАСТЬСЯ/НАРВАТЬСЯ/НАТОЛКНУТЬСЯ) rus_verbs:НАРВАТЬСЯ{}, // rus_verbs:НАТОЛКНУТЬСЯ{}, // rus_verbs:ВЫСЛАТЬ{}, // Он выслал разведчиков на большое расстояние от основного отряда. (ВЫСЛАТЬ) прилагательное:ПОХОЖИЙ{}, // Ты не выглядишь похожим на индейца (ПОХОЖИЙ) rus_verbs:РАЗОРВАТЬ{}, // Через минуту он был мертв и разорван на части. (РАЗОРВАТЬ) rus_verbs:СТОЛКНУТЬ{}, // Только быстрыми выпадами копья он сумел столкнуть их обратно на карниз. (СТОЛКНУТЬ/СТАЛКИВАТЬ) rus_verbs:СТАЛКИВАТЬ{}, // rus_verbs:СПУСТИТЬ{}, // Я побежал к ним, но они к тому времени спустили лодку на воду (СПУСТИТЬ) rus_verbs:ПЕРЕБРАСЫВАТЬ{}, // Сирия перебрасывает на юг страны воинские подкрепления (ПЕРЕБРАСЫВАТЬ, ПЕРЕБРОСИТЬ, НАБРАСЫВАТЬ, НАБРОСИТЬ) rus_verbs:ПЕРЕБРОСИТЬ{}, // rus_verbs:НАБРАСЫВАТЬ{}, // rus_verbs:НАБРОСИТЬ{}, // rus_verbs:СВЕРНУТЬ{}, // Он вывел машину на бульвар и поехал на восток, а затем свернул на юг. (СВЕРНУТЬ/СВОРАЧИВАТЬ/ПОВЕРНУТЬ/ПОВОРАЧИВАТЬ) rus_verbs:СВОРАЧИВАТЬ{}, // // rus_verbs:ПОВЕРНУТЬ{}, // rus_verbs:ПОВОРАЧИВАТЬ{}, // rus_verbs:наорать{}, rus_verbs:ПРОДВИНУТЬСЯ{}, // Полк продвинется на десятки километров (ПРОДВИНУТЬСЯ) rus_verbs:БРОСАТЬ{}, // Он бросает обещания на ветер (БРОСАТЬ) rus_verbs:ОДОЛЖИТЬ{}, // Я вам одолжу книгу на десять дней (ОДОЛЖИТЬ) rus_verbs:перегнать{}, // Скот нужно перегнать с этого пастбища на другое rus_verbs:перегонять{}, rus_verbs:выгонять{}, rus_verbs:выгнать{}, rus_verbs:СВОДИТЬСЯ{}, // сейчас панели кузовов расходятся по десяткам покрасочных постов и потом сводятся вновь на общий конвейер (СВОДИТЬСЯ) rus_verbs:ПОЖЕРТВОВАТЬ{}, // Бывший функционер компартии Эстонии пожертвовал деньги на расследования преступлений коммунизма (ПОЖЕРТВОВАТЬ) rus_verbs:ПРОВЕРЯТЬ{}, // Школьников будут принудительно проверять на курение (ПРОВЕРЯТЬ) rus_verbs:ОТПУСТИТЬ{}, // Приставы отпустят должников на отдых (ОТПУСТИТЬ) rus_verbs:использоваться{}, // имеющийся у государства денежный запас активно используется на поддержание рынка акций rus_verbs:назначаться{}, // назначаться на пост rus_verbs:наблюдать{}, // Судья , долго наблюдавший в трубу , вдруг вскричал rus_verbs:ШПИОНИТЬ{}, // Канадского офицера, шпионившего на Россию, приговорили к 20 годам тюрьмы (ШПИОНИТЬ НА вин) rus_verbs:ЗАПЛАНИРОВАТЬ{}, // все деньги , запланированные на сейсмоукрепление домов на Камчатке (ЗАПЛАНИРОВАТЬ НА) // rus_verbs:ПОХОДИТЬ{}, // больше походил на обвинительную речь , адресованную руководству республики (ПОХОДИТЬ НА) rus_verbs:ДЕЙСТВОВАТЬ{}, // выявленный контрабандный канал действовал на постоянной основе (ДЕЙСТВОВАТЬ НА) rus_verbs:ПЕРЕДАТЬ{}, // после чего должно быть передано на рассмотрение суда (ПЕРЕДАТЬ НА вин) rus_verbs:НАЗНАЧИТЬСЯ{}, // Зимой на эту должность пытался назначиться народный депутат (НАЗНАЧИТЬСЯ НА) rus_verbs:РЕШИТЬСЯ{}, // Франция решилась на одностороннее и рискованное военное вмешательство (РЕШИТЬСЯ НА) rus_verbs:ОРИЕНТИРОВАТЬ{}, // Этот браузер полностью ориентирован на планшеты и сенсорный ввод (ОРИЕНТИРОВАТЬ НА вин) rus_verbs:ЗАВЕСТИ{}, // на Витьку завели дело (ЗАВЕСТИ НА) rus_verbs:ОБРУШИТЬСЯ{}, // В Северной Осетии на воинскую часть обрушилась снежная лавина (ОБРУШИТЬСЯ В, НА) rus_verbs:НАСТРАИВАТЬСЯ{}, // гетеродин, настраивающийся на волну (НАСТРАИВАТЬСЯ НА) rus_verbs:СУЩЕСТВОВАТЬ{}, // Он существует на средства родителей. (СУЩЕСТВОВАТЬ НА) прилагательное:способный{}, // Он способен на убийство. (СПОСОБНЫЙ НА) rus_verbs:посыпаться{}, // на Нину посыпались снежинки инфинитив:нарезаться{ вид:несоверш }, // Урожай собирают механически или вручную, стебли нарезаются на куски и быстро транспортируются на перерабатывающий завод. глагол:нарезаться{ вид:несоверш }, rus_verbs:пожаловать{}, // скандально известный певец пожаловал к нам на передачу rus_verbs:показать{}, // Вадим показал на Колю rus_verbs:съехаться{}, // Финалисты съехались на свои игры в Лос-Анжелес. (СЪЕХАТЬСЯ НА, В) rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА) rus_verbs:упасть{}, // В Таиланде на автобус с российскими туристами упал башенный кран (УПАСТЬ В, НА) прилагательное:тугой{}, // Бабушка туга на ухо. (ТУГОЙ НА) rus_verbs:свисать{}, // Волосы свисают на лоб. (свисать на) rus_verbs:ЦЕНИТЬСЯ{}, // Всякая рабочая рука ценилась на вес золота. (ЦЕНИТЬСЯ НА) rus_verbs:ШУМЕТЬ{}, // Вы шумите на весь дом! (ШУМЕТЬ НА) rus_verbs:протянуться{}, // Дорога протянулась на сотни километров. (протянуться на) rus_verbs:РАССЧИТАТЬ{}, // Книга рассчитана на массового читателя. (РАССЧИТАТЬ НА) rus_verbs:СОРИЕНТИРОВАТЬ{}, // мы сориентировали процесс на повышение котировок (СОРИЕНТИРОВАТЬ НА) rus_verbs:рыкнуть{}, // рыкнуть на остальных членов стаи (рыкнуть на) rus_verbs:оканчиваться{}, // оканчиваться на звонкую согласную (оканчиваться на) rus_verbs:выехать{}, // посигналить нарушителю, выехавшему на встречную полосу (выехать на) rus_verbs:прийтись{}, // Пятое число пришлось на субботу. rus_verbs:крениться{}, // корабль кренился на правый борт (крениться на) rus_verbs:приходиться{}, // основной налоговый гнет приходится на средний бизнес (приходиться на) rus_verbs:верить{}, // верить людям на слово (верить на слово) rus_verbs:выезжать{}, // Завтра вся семья выезжает на новую квартиру. rus_verbs:записать{}, // Запишите меня на завтрашний приём к доктору. rus_verbs:пасть{}, // Жребий пал на меня. rus_verbs:ездить{}, // Вчера мы ездили на оперу. rus_verbs:влезть{}, // Мальчик влез на дерево. rus_verbs:выбежать{}, // Мальчик выбежал из комнаты на улицу. rus_verbs:разбиться{}, // окно разбилось на мелкие осколки rus_verbs:бежать{}, // я бегу на урок rus_verbs:сбегаться{}, // сбегаться на происшествие rus_verbs:присылать{}, // присылать на испытание rus_verbs:надавить{}, // надавить на педать rus_verbs:внести{}, // внести законопроект на рассмотрение rus_verbs:вносить{}, // вносить законопроект на рассмотрение rus_verbs:поворачиваться{}, // поворачиваться на 180 градусов rus_verbs:сдвинуть{}, // сдвинуть на несколько сантиметров rus_verbs:опубликовать{}, // С.Митрохин опубликовал компромат на думских подельников Гудкова rus_verbs:вырасти{}, // Официальный курс доллара вырос на 26 копеек. rus_verbs:оглядываться{}, // оглядываться на девушек rus_verbs:расходиться{}, // расходиться на отдых rus_verbs:поскакать{}, // поскакать на службу rus_verbs:прыгать{}, // прыгать на сцену rus_verbs:приглашать{}, // приглашать на обед rus_verbs:рваться{}, // Кусок ткани рвется на части rus_verbs:понестись{}, // понестись на волю rus_verbs:распространяться{}, // распространяться на всех жителей штата инфинитив:просыпаться{ вид:соверш }, глагол:просыпаться{ вид:соверш }, // просыпаться на пол инфинитив:просыпаться{ вид:несоверш }, глагол:просыпаться{ вид:несоверш }, деепричастие:просыпавшись{}, деепричастие:просыпаясь{}, rus_verbs:заехать{}, // заехать на пандус rus_verbs:разобрать{}, // разобрать на составляющие rus_verbs:опускаться{}, // опускаться на колени rus_verbs:переехать{}, // переехать на конспиративную квартиру rus_verbs:закрывать{}, // закрывать глаза на действия конкурентов rus_verbs:поместить{}, // поместить на поднос rus_verbs:отходить{}, // отходить на подготовленные позиции rus_verbs:сыпаться{}, // сыпаться на плечи rus_verbs:отвезти{}, // отвезти на занятия rus_verbs:накинуть{}, // накинуть на плечи rus_verbs:отлететь{}, // отлететь на пол rus_verbs:закинуть{}, // закинуть на чердак rus_verbs:зашипеть{}, // зашипеть на собаку rus_verbs:прогреметь{}, // прогреметь на всю страну rus_verbs:повалить{}, // повалить на стол rus_verbs:опереть{}, // опереть на фундамент rus_verbs:забросить{}, // забросить на антресоль rus_verbs:подействовать{}, // подействовать на материал rus_verbs:разделять{}, // разделять на части rus_verbs:прикрикнуть{}, // прикрикнуть на детей rus_verbs:разложить{}, // разложить на множители rus_verbs:провожать{}, // провожать на работу rus_verbs:катить{}, // катить на стройку rus_verbs:наложить{}, // наложить запрет на проведение операций с недвижимостью rus_verbs:сохранять{}, // сохранять на память rus_verbs:злиться{}, // злиться на друга rus_verbs:оборачиваться{}, // оборачиваться на свист rus_verbs:сползти{}, // сползти на землю rus_verbs:записывать{}, // записывать на ленту rus_verbs:загнать{}, // загнать на дерево rus_verbs:забормотать{}, // забормотать на ухо rus_verbs:протиснуться{}, // протиснуться на самый край rus_verbs:заторопиться{}, // заторопиться на вручение премии rus_verbs:гаркнуть{}, // гаркнуть на шалунов rus_verbs:навалиться{}, // навалиться на виновника всей толпой rus_verbs:проскользнуть{}, // проскользнуть на крышу дома rus_verbs:подтянуть{}, // подтянуть на палубу rus_verbs:скатиться{}, // скатиться на двойки rus_verbs:давить{}, // давить на жалость rus_verbs:намекнуть{}, // намекнуть на новые обстоятельства rus_verbs:замахнуться{}, // замахнуться на святое rus_verbs:заменить{}, // заменить на свежую салфетку rus_verbs:свалить{}, // свалить на землю rus_verbs:стекать{}, // стекать на оголенные провода rus_verbs:увеличиваться{}, // увеличиваться на сотню процентов rus_verbs:развалиться{}, // развалиться на части rus_verbs:сердиться{}, // сердиться на товарища rus_verbs:обронить{}, // обронить на пол rus_verbs:подсесть{}, // подсесть на наркоту rus_verbs:реагировать{}, // реагировать на импульсы rus_verbs:отпускать{}, // отпускать на волю rus_verbs:прогнать{}, // прогнать на рабочее место rus_verbs:ложить{}, // ложить на стол rus_verbs:рвать{}, // рвать на части rus_verbs:разлететься{}, // разлететься на кусочки rus_verbs:превышать{}, // превышать на существенную величину rus_verbs:сбиться{}, // сбиться на рысь rus_verbs:пристроиться{}, // пристроиться на хорошую работу rus_verbs:удрать{}, // удрать на пастбище rus_verbs:толкать{}, // толкать на преступление rus_verbs:посматривать{}, // посматривать на экран rus_verbs:набирать{}, // набирать на судно rus_verbs:отступать{}, // отступать на дерево rus_verbs:подуть{}, // подуть на молоко rus_verbs:плеснуть{}, // плеснуть на голову rus_verbs:соскользнуть{}, // соскользнуть на землю rus_verbs:затаить{}, // затаить на кого-то обиду rus_verbs:обижаться{}, // обижаться на Колю rus_verbs:смахнуть{}, // смахнуть на пол rus_verbs:застегнуть{}, // застегнуть на все пуговицы rus_verbs:спускать{}, // спускать на землю rus_verbs:греметь{}, // греметь на всю округу rus_verbs:скосить{}, // скосить на соседа глаз rus_verbs:отважиться{}, // отважиться на прыжок rus_verbs:литься{}, // литься на землю rus_verbs:порвать{}, // порвать на тряпки rus_verbs:проследовать{}, // проследовать на сцену rus_verbs:надевать{}, // надевать на голову rus_verbs:проскочить{}, // проскочить на красный свет rus_verbs:прилечь{}, // прилечь на диванчик rus_verbs:разделиться{}, // разделиться на небольшие группы rus_verbs:завыть{}, // завыть на луну rus_verbs:переносить{}, // переносить на другую машину rus_verbs:наговорить{}, // наговорить на сотню рублей rus_verbs:намекать{}, // намекать на новые обстоятельства rus_verbs:нападать{}, // нападать на охранников rus_verbs:убегать{}, // убегать на другое место rus_verbs:тратить{}, // тратить на развлечения rus_verbs:присаживаться{}, // присаживаться на корточки rus_verbs:переместиться{}, // переместиться на вторую линию rus_verbs:завалиться{}, // завалиться на диван rus_verbs:удалиться{}, // удалиться на покой rus_verbs:уменьшаться{}, // уменьшаться на несколько процентов rus_verbs:обрушить{}, // обрушить на голову rus_verbs:резать{}, // резать на части rus_verbs:умчаться{}, // умчаться на юг rus_verbs:навернуться{}, // навернуться на камень rus_verbs:примчаться{}, // примчаться на матч rus_verbs:издавать{}, // издавать на собственные средства rus_verbs:переключить{}, // переключить на другой язык rus_verbs:отправлять{}, // отправлять на пенсию rus_verbs:залечь{}, // залечь на дно rus_verbs:установиться{}, // установиться на диск rus_verbs:направлять{}, // направлять на дополнительное обследование rus_verbs:разрезать{}, // разрезать на части rus_verbs:оскалиться{}, // оскалиться на прохожего rus_verbs:рычать{}, // рычать на пьяных rus_verbs:погружаться{}, // погружаться на дно rus_verbs:опираться{}, // опираться на костыли rus_verbs:поторопиться{}, // поторопиться на учебу rus_verbs:сдвинуться{}, // сдвинуться на сантиметр rus_verbs:увеличить{}, // увеличить на процент rus_verbs:опускать{}, // опускать на землю rus_verbs:созвать{}, // созвать на митинг rus_verbs:делить{}, // делить на части rus_verbs:пробиться{}, // пробиться на заключительную часть rus_verbs:простираться{}, // простираться на много миль rus_verbs:забить{}, // забить на учебу rus_verbs:переложить{}, // переложить на чужие плечи rus_verbs:грохнуться{}, // грохнуться на землю rus_verbs:прорваться{}, // прорваться на сцену rus_verbs:разлить{}, // разлить на землю rus_verbs:укладываться{}, // укладываться на ночевку rus_verbs:уволить{}, // уволить на пенсию rus_verbs:наносить{}, // наносить на кожу rus_verbs:набежать{}, // набежать на берег rus_verbs:заявиться{}, // заявиться на стрельбище rus_verbs:налиться{}, // налиться на крышку rus_verbs:надвигаться{}, // надвигаться на берег rus_verbs:распустить{}, // распустить на каникулы rus_verbs:переключиться{}, // переключиться на другую задачу rus_verbs:чихнуть{}, // чихнуть на окружающих rus_verbs:шлепнуться{}, // шлепнуться на спину rus_verbs:устанавливать{}, // устанавливать на крышу rus_verbs:устанавливаться{}, // устанавливаться на крышу rus_verbs:устраиваться{}, // устраиваться на работу rus_verbs:пропускать{}, // пропускать на стадион инфинитив:сбегать{ вид:соверш }, глагол:сбегать{ вид:соверш }, // сбегать на фильм инфинитив:сбегать{ вид:несоверш }, глагол:сбегать{ вид:несоверш }, деепричастие:сбегав{}, деепричастие:сбегая{}, rus_verbs:показываться{}, // показываться на глаза rus_verbs:прибегать{}, // прибегать на урок rus_verbs:съездить{}, // съездить на ферму rus_verbs:прославиться{}, // прославиться на всю страну rus_verbs:опрокинуться{}, // опрокинуться на спину rus_verbs:насыпать{}, // насыпать на землю rus_verbs:употреблять{}, // употреблять на корм скоту rus_verbs:пристроить{}, // пристроить на работу rus_verbs:заворчать{}, // заворчать на вошедшего rus_verbs:завязаться{}, // завязаться на поставщиков rus_verbs:сажать{}, // сажать на стул rus_verbs:напрашиваться{}, // напрашиваться на жесткие ответные меры rus_verbs:заменять{}, // заменять на исправную rus_verbs:нацепить{}, // нацепить на голову rus_verbs:сыпать{}, // сыпать на землю rus_verbs:закрываться{}, // закрываться на ремонт rus_verbs:распространиться{}, // распространиться на всю популяцию rus_verbs:поменять{}, // поменять на велосипед rus_verbs:пересесть{}, // пересесть на велосипеды rus_verbs:подоспеть{}, // подоспеть на разбор rus_verbs:шипеть{}, // шипеть на собак rus_verbs:поделить{}, // поделить на части rus_verbs:подлететь{}, // подлететь на расстояние выстрела rus_verbs:нажимать{}, // нажимать на все кнопки rus_verbs:распасться{}, // распасться на части rus_verbs:приволочь{}, // приволочь на диван rus_verbs:пожить{}, // пожить на один доллар rus_verbs:устремляться{}, // устремляться на свободу rus_verbs:смахивать{}, // смахивать на пол rus_verbs:забежать{}, // забежать на обед rus_verbs:увеличиться{}, // увеличиться на существенную величину rus_verbs:прокрасться{}, // прокрасться на склад rus_verbs:пущать{}, // пущать на постой rus_verbs:отклонить{}, // отклонить на несколько градусов rus_verbs:насмотреться{}, // насмотреться на безобразия rus_verbs:настроить{}, // настроить на короткие волны rus_verbs:уменьшиться{}, // уменьшиться на пару сантиметров rus_verbs:поменяться{}, // поменяться на другую книжку rus_verbs:расколоться{}, // расколоться на части rus_verbs:разлиться{}, // разлиться на землю rus_verbs:срываться{}, // срываться на жену rus_verbs:осудить{}, // осудить на пожизненное заключение rus_verbs:передвинуть{}, // передвинуть на первое место rus_verbs:допускаться{}, // допускаться на полигон rus_verbs:задвинуть{}, // задвинуть на полку rus_verbs:повлиять{}, // повлиять на оценку rus_verbs:отбавлять{}, // отбавлять на осмотр rus_verbs:сбрасывать{}, // сбрасывать на землю rus_verbs:накинуться{}, // накинуться на случайных прохожих rus_verbs:пролить{}, // пролить на кожу руки rus_verbs:затащить{}, // затащить на сеновал rus_verbs:перебежать{}, // перебежать на сторону противника rus_verbs:наливать{}, // наливать на скатерть rus_verbs:пролезть{}, // пролезть на сцену rus_verbs:откладывать{}, // откладывать на черный день rus_verbs:распадаться{}, // распадаться на небольшие фрагменты rus_verbs:перечислить{}, // перечислить на счет rus_verbs:закачаться{}, // закачаться на верхний уровень rus_verbs:накрениться{}, // накрениться на правый борт rus_verbs:подвинуться{}, // подвинуться на один уровень rus_verbs:разнести{}, // разнести на мелкие кусочки rus_verbs:зажить{}, // зажить на широкую ногу rus_verbs:оглохнуть{}, // оглохнуть на правое ухо rus_verbs:посетовать{}, // посетовать на бюрократизм rus_verbs:уводить{}, // уводить на осмотр rus_verbs:ускакать{}, // ускакать на забег rus_verbs:посветить{}, // посветить на стену rus_verbs:разрываться{}, // разрываться на части rus_verbs:побросать{}, // побросать на землю rus_verbs:карабкаться{}, // карабкаться на скалу rus_verbs:нахлынуть{}, // нахлынуть на кого-то rus_verbs:разлетаться{}, // разлетаться на мелкие осколочки rus_verbs:среагировать{}, // среагировать на сигнал rus_verbs:претендовать{}, // претендовать на приз rus_verbs:дунуть{}, // дунуть на одуванчик rus_verbs:переводиться{}, // переводиться на другую работу rus_verbs:перевезти{}, // перевезти на другую площадку rus_verbs:топать{}, // топать на урок rus_verbs:относить{}, // относить на склад rus_verbs:сбивать{}, // сбивать на землю rus_verbs:укладывать{}, // укладывать на спину rus_verbs:укатить{}, // укатить на отдых rus_verbs:убирать{}, // убирать на полку rus_verbs:опасть{}, // опасть на землю rus_verbs:ронять{}, // ронять на снег rus_verbs:пялиться{}, // пялиться на тело rus_verbs:глазеть{}, // глазеть на тело rus_verbs:снижаться{}, // снижаться на безопасную высоту rus_verbs:запрыгнуть{}, // запрыгнуть на платформу rus_verbs:разбиваться{}, // разбиваться на главы rus_verbs:сгодиться{}, // сгодиться на фарш rus_verbs:перескочить{}, // перескочить на другую страницу rus_verbs:нацелиться{}, // нацелиться на главную добычу rus_verbs:заезжать{}, // заезжать на бордюр rus_verbs:забираться{}, // забираться на крышу rus_verbs:проорать{}, // проорать на всё село rus_verbs:сбежаться{}, // сбежаться на шум rus_verbs:сменять{}, // сменять на хлеб rus_verbs:мотать{}, // мотать на ус rus_verbs:раскалываться{}, // раскалываться на две половинки rus_verbs:коситься{}, // коситься на режиссёра rus_verbs:плевать{}, // плевать на законы rus_verbs:ссылаться{}, // ссылаться на авторитетное мнение rus_verbs:наставить{}, // наставить на путь истинный rus_verbs:завывать{}, // завывать на Луну rus_verbs:опаздывать{}, // опаздывать на совещание rus_verbs:залюбоваться{}, // залюбоваться на пейзаж rus_verbs:повергнуть{}, // повергнуть на землю rus_verbs:надвинуть{}, // надвинуть на лоб rus_verbs:стекаться{}, // стекаться на площадь rus_verbs:обозлиться{}, // обозлиться на тренера rus_verbs:оттянуть{}, // оттянуть на себя rus_verbs:истратить{}, // истратить на дешевых шлюх rus_verbs:вышвырнуть{}, // вышвырнуть на улицу rus_verbs:затолкать{}, // затолкать на верхнюю полку rus_verbs:заскочить{}, // заскочить на огонек rus_verbs:проситься{}, // проситься на улицу rus_verbs:натыкаться{}, // натыкаться на борщевик rus_verbs:обрушиваться{}, // обрушиваться на митингующих rus_verbs:переписать{}, // переписать на чистовик rus_verbs:переноситься{}, // переноситься на другое устройство rus_verbs:напроситься{}, // напроситься на обидный ответ rus_verbs:натягивать{}, // натягивать на ноги rus_verbs:кидаться{}, // кидаться на прохожих rus_verbs:откликаться{}, // откликаться на призыв rus_verbs:поспевать{}, // поспевать на балет rus_verbs:обратиться{}, // обратиться на кафедру rus_verbs:полюбоваться{}, // полюбоваться на бюст rus_verbs:таращиться{}, // таращиться на мустангов rus_verbs:напороться{}, // напороться на колючки rus_verbs:раздать{}, // раздать на руки rus_verbs:дивиться{}, // дивиться на танцовщиц rus_verbs:назначать{}, // назначать на ответственнейший пост rus_verbs:кидать{}, // кидать на балкон rus_verbs:нахлобучить{}, // нахлобучить на башку rus_verbs:увлекать{}, // увлекать на луг rus_verbs:ругнуться{}, // ругнуться на животину rus_verbs:переселиться{}, // переселиться на хутор rus_verbs:разрывать{}, // разрывать на части rus_verbs:утащить{}, // утащить на дерево rus_verbs:наставлять{}, // наставлять на путь rus_verbs:соблазнить{}, // соблазнить на обмен rus_verbs:накладывать{}, // накладывать на рану rus_verbs:набрести{}, // набрести на грибную поляну rus_verbs:наведываться{}, // наведываться на прежнюю работу rus_verbs:погулять{}, // погулять на чужие деньги rus_verbs:уклоняться{}, // уклоняться на два градуса влево rus_verbs:слезать{}, // слезать на землю rus_verbs:клевать{}, // клевать на мотыля // rus_verbs:назначаться{}, // назначаться на пост rus_verbs:напялить{}, // напялить на голову rus_verbs:натянуться{}, // натянуться на рамку rus_verbs:разгневаться{}, // разгневаться на придворных rus_verbs:эмигрировать{}, // эмигрировать на Кипр rus_verbs:накатить{}, // накатить на основу rus_verbs:пригнать{}, // пригнать на пастбище rus_verbs:обречь{}, // обречь на мучения rus_verbs:сокращаться{}, // сокращаться на четверть rus_verbs:оттеснить{}, // оттеснить на пристань rus_verbs:подбить{}, // подбить на аферу rus_verbs:заманить{}, // заманить на дерево инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать на кустик // деепричастие:пописав{ aux stress="поп^исать" }, rus_verbs:посходить{}, // посходить на перрон rus_verbs:налечь{}, // налечь на мясцо rus_verbs:отбирать{}, // отбирать на флот rus_verbs:нашептывать{}, // нашептывать на ухо rus_verbs:откладываться{}, // откладываться на будущее rus_verbs:залаять{}, // залаять на грабителя rus_verbs:настроиться{}, // настроиться на прием rus_verbs:разбивать{}, // разбивать на куски rus_verbs:пролиться{}, // пролиться на почву rus_verbs:сетовать{}, // сетовать на объективные трудности rus_verbs:подвезти{}, // подвезти на митинг rus_verbs:припереться{}, // припереться на праздник rus_verbs:подталкивать{}, // подталкивать на прыжок rus_verbs:прорываться{}, // прорываться на сцену rus_verbs:снижать{}, // снижать на несколько процентов rus_verbs:нацелить{}, // нацелить на танк rus_verbs:расколоть{}, // расколоть на два куска rus_verbs:увозить{}, // увозить на обкатку rus_verbs:оседать{}, // оседать на дно rus_verbs:съедать{}, // съедать на ужин rus_verbs:навлечь{}, // навлечь на себя rus_verbs:равняться{}, // равняться на лучших rus_verbs:сориентироваться{}, // сориентироваться на местности rus_verbs:снизить{}, // снизить на несколько процентов rus_verbs:перенестись{}, // перенестись на много лет назад rus_verbs:завезти{}, // завезти на склад rus_verbs:проложить{}, // проложить на гору rus_verbs:понадеяться{}, // понадеяться на удачу rus_verbs:заступить{}, // заступить на вахту rus_verbs:засеменить{}, // засеменить на выход rus_verbs:запирать{}, // запирать на ключ rus_verbs:скатываться{}, // скатываться на землю rus_verbs:дробить{}, // дробить на части rus_verbs:разваливаться{}, // разваливаться на кусочки rus_verbs:завозиться{}, // завозиться на склад rus_verbs:нанимать{}, // нанимать на дневную работу rus_verbs:поспеть{}, // поспеть на концерт rus_verbs:променять{}, // променять на сытость rus_verbs:переправить{}, // переправить на север rus_verbs:налетать{}, // налетать на силовое поле rus_verbs:затворить{}, // затворить на замок rus_verbs:подогнать{}, // подогнать на пристань rus_verbs:наехать{}, // наехать на камень rus_verbs:распевать{}, // распевать на разные голоса rus_verbs:разносить{}, // разносить на клочки rus_verbs:преувеличивать{}, // преувеличивать на много килограммов rus_verbs:хромать{}, // хромать на одну ногу rus_verbs:телеграфировать{}, // телеграфировать на базу rus_verbs:порезать{}, // порезать на лоскуты rus_verbs:порваться{}, // порваться на части rus_verbs:загонять{}, // загонять на дерево rus_verbs:отбывать{}, // отбывать на место службы rus_verbs:усаживаться{}, // усаживаться на трон rus_verbs:накопить{}, // накопить на квартиру rus_verbs:зыркнуть{}, // зыркнуть на визитера rus_verbs:копить{}, // копить на машину rus_verbs:помещать{}, // помещать на верхнюю грань rus_verbs:сползать{}, // сползать на снег rus_verbs:попроситься{}, // попроситься на улицу rus_verbs:перетащить{}, // перетащить на чердак rus_verbs:растащить{}, // растащить на сувениры rus_verbs:ниспадать{}, // ниспадать на землю rus_verbs:сфотографировать{}, // сфотографировать на память rus_verbs:нагонять{}, // нагонять на конкурентов страх rus_verbs:покушаться{}, // покушаться на понтифика rus_verbs:покуситься{}, rus_verbs:наняться{}, // наняться на службу rus_verbs:просачиваться{}, // просачиваться на поверхность rus_verbs:пускаться{}, // пускаться на ветер rus_verbs:отваживаться{}, // отваживаться на прыжок rus_verbs:досадовать{}, // досадовать на объективные трудности rus_verbs:унестись{}, // унестись на небо rus_verbs:ухудшаться{}, // ухудшаться на несколько процентов rus_verbs:насадить{}, // насадить на копьё rus_verbs:нагрянуть{}, // нагрянуть на праздник rus_verbs:зашвырнуть{}, // зашвырнуть на полку rus_verbs:грешить{}, // грешить на постояльцев rus_verbs:просочиться{}, // просочиться на поверхность rus_verbs:надоумить{}, // надоумить на глупость rus_verbs:намотать{}, // намотать на шпиндель rus_verbs:замкнуть{}, // замкнуть на корпус rus_verbs:цыкнуть{}, // цыкнуть на детей rus_verbs:переворачиваться{}, // переворачиваться на спину rus_verbs:соваться{}, // соваться на площать rus_verbs:отлучиться{}, // отлучиться на обед rus_verbs:пенять{}, // пенять на себя rus_verbs:нарезать{}, // нарезать на ломтики rus_verbs:поставлять{}, // поставлять на Кипр rus_verbs:залезать{}, // залезать на балкон rus_verbs:отлучаться{}, // отлучаться на обед rus_verbs:сбиваться{}, // сбиваться на шаг rus_verbs:таращить{}, // таращить глаза на вошедшего rus_verbs:прошмыгнуть{}, // прошмыгнуть на кухню rus_verbs:опережать{}, // опережать на пару сантиметров rus_verbs:переставить{}, // переставить на стол rus_verbs:раздирать{}, // раздирать на части rus_verbs:затвориться{}, // затвориться на засовы rus_verbs:материться{}, // материться на кого-то rus_verbs:наскочить{}, // наскочить на риф rus_verbs:набираться{}, // набираться на борт rus_verbs:покрикивать{}, // покрикивать на помощников rus_verbs:заменяться{}, // заменяться на более новый rus_verbs:подсадить{}, // подсадить на верхнюю полку rus_verbs:проковылять{}, // проковылять на кухню rus_verbs:прикатить{}, // прикатить на старт rus_verbs:залететь{}, // залететь на чужую территорию rus_verbs:загрузить{}, // загрузить на конвейер rus_verbs:уплывать{}, // уплывать на материк rus_verbs:опозорить{}, // опозорить на всю деревню rus_verbs:провоцировать{}, // провоцировать на ответную агрессию rus_verbs:забивать{}, // забивать на учебу rus_verbs:набегать{}, // набегать на прибрежные деревни rus_verbs:запираться{}, // запираться на ключ rus_verbs:фотографировать{}, // фотографировать на мыльницу rus_verbs:подымать{}, // подымать на недосягаемую высоту rus_verbs:съезжаться{}, // съезжаться на симпозиум rus_verbs:отвлекаться{}, // отвлекаться на игру rus_verbs:проливать{}, // проливать на брюки rus_verbs:спикировать{}, // спикировать на зазевавшегося зайца rus_verbs:уползти{}, // уползти на вершину холма rus_verbs:переместить{}, // переместить на вторую палубу rus_verbs:превысить{}, // превысить на несколько метров rus_verbs:передвинуться{}, // передвинуться на соседнюю клетку rus_verbs:спровоцировать{}, // спровоцировать на бросок rus_verbs:сместиться{}, // сместиться на соседнюю клетку rus_verbs:заготовить{}, // заготовить на зиму rus_verbs:плеваться{}, // плеваться на пол rus_verbs:переселить{}, // переселить на север rus_verbs:напирать{}, // напирать на дверь rus_verbs:переезжать{}, // переезжать на другой этаж rus_verbs:приподнимать{}, // приподнимать на несколько сантиметров rus_verbs:трогаться{}, // трогаться на красный свет rus_verbs:надвинуться{}, // надвинуться на глаза rus_verbs:засмотреться{}, // засмотреться на купальники rus_verbs:убыть{}, // убыть на фронт rus_verbs:передвигать{}, // передвигать на второй уровень rus_verbs:отвозить{}, // отвозить на свалку rus_verbs:обрекать{}, // обрекать на гибель rus_verbs:записываться{}, // записываться на танцы rus_verbs:настраивать{}, // настраивать на другой диапазон rus_verbs:переписывать{}, // переписывать на диск rus_verbs:израсходовать{}, // израсходовать на гонки rus_verbs:обменять{}, // обменять на перспективного игрока rus_verbs:трубить{}, // трубить на всю округу rus_verbs:набрасываться{}, // набрасываться на жертву rus_verbs:чихать{}, // чихать на правила rus_verbs:наваливаться{}, // наваливаться на рычаг rus_verbs:сподобиться{}, // сподобиться на повторный анализ rus_verbs:намазать{}, // намазать на хлеб rus_verbs:прореагировать{}, // прореагировать на вызов rus_verbs:зачислить{}, // зачислить на факультет rus_verbs:наведаться{}, // наведаться на склад rus_verbs:откидываться{}, // откидываться на спинку кресла rus_verbs:захромать{}, // захромать на левую ногу rus_verbs:перекочевать{}, // перекочевать на другой берег rus_verbs:накатываться{}, // накатываться на песчаный берег rus_verbs:приостановить{}, // приостановить на некоторое время rus_verbs:запрятать{}, // запрятать на верхнюю полочку rus_verbs:прихрамывать{}, // прихрамывать на правую ногу rus_verbs:упорхнуть{}, // упорхнуть на свободу rus_verbs:расстегивать{}, // расстегивать на пальто rus_verbs:напуститься{}, // напуститься на бродягу rus_verbs:накатывать{}, // накатывать на оригинал rus_verbs:наезжать{}, // наезжать на простофилю rus_verbs:тявкнуть{}, // тявкнуть на подошедшего человека rus_verbs:отрядить{}, // отрядить на починку rus_verbs:положиться{}, // положиться на главаря rus_verbs:опрокидывать{}, // опрокидывать на голову rus_verbs:поторапливаться{}, // поторапливаться на рейс rus_verbs:налагать{}, // налагать на заемщика rus_verbs:скопировать{}, // скопировать на диск rus_verbs:опадать{}, // опадать на землю rus_verbs:купиться{}, // купиться на посулы rus_verbs:гневаться{}, // гневаться на слуг rus_verbs:слететься{}, // слететься на раздачу rus_verbs:убавить{}, // убавить на два уровня rus_verbs:спихнуть{}, // спихнуть на соседа rus_verbs:накричать{}, // накричать на ребенка rus_verbs:приберечь{}, // приберечь на ужин rus_verbs:приклеить{}, // приклеить на ветровое стекло rus_verbs:ополчиться{}, // ополчиться на посредников rus_verbs:тратиться{}, // тратиться на сувениры rus_verbs:слетаться{}, // слетаться на свет rus_verbs:доставляться{}, // доставляться на базу rus_verbs:поплевать{}, // поплевать на руки rus_verbs:огрызаться{}, // огрызаться на замечание rus_verbs:попереться{}, // попереться на рынок rus_verbs:растягиваться{}, // растягиваться на полу rus_verbs:повергать{}, // повергать на землю rus_verbs:ловиться{}, // ловиться на мотыля rus_verbs:наседать{}, // наседать на обороняющихся rus_verbs:развалить{}, // развалить на кирпичи rus_verbs:разломить{}, // разломить на несколько частей rus_verbs:примерить{}, // примерить на себя rus_verbs:лепиться{}, // лепиться на стену rus_verbs:скопить{}, // скопить на старость rus_verbs:затратить{}, // затратить на ликвидацию последствий rus_verbs:притащиться{}, // притащиться на гулянку rus_verbs:осерчать{}, // осерчать на прислугу rus_verbs:натравить{}, // натравить на медведя rus_verbs:ссыпать{}, // ссыпать на землю rus_verbs:подвозить{}, // подвозить на пристань rus_verbs:мобилизовать{}, // мобилизовать на сборы rus_verbs:смотаться{}, // смотаться на работу rus_verbs:заглядеться{}, // заглядеться на девчонок rus_verbs:таскаться{}, // таскаться на работу rus_verbs:разгружать{}, // разгружать на транспортер rus_verbs:потреблять{}, // потреблять на кондиционирование инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять на базу деепричастие:сгоняв{}, rus_verbs:посылаться{}, // посылаться на разведку rus_verbs:окрыситься{}, // окрыситься на кого-то rus_verbs:отлить{}, // отлить на сковороду rus_verbs:шикнуть{}, // шикнуть на детишек rus_verbs:уповать{}, // уповать на бескорысную помощь rus_verbs:класться{}, // класться на стол rus_verbs:поковылять{}, // поковылять на выход rus_verbs:навевать{}, // навевать на собравшихся скуку rus_verbs:накладываться{}, // накладываться на грунтовку rus_verbs:наноситься{}, // наноситься на чистую кожу // rus_verbs:запланировать{}, // запланировать на среду rus_verbs:кувыркнуться{}, // кувыркнуться на землю rus_verbs:гавкнуть{}, // гавкнуть на хозяина rus_verbs:перестроиться{}, // перестроиться на новый лад rus_verbs:расходоваться{}, // расходоваться на образование rus_verbs:дуться{}, // дуться на бабушку rus_verbs:перетаскивать{}, // перетаскивать на рабочий стол rus_verbs:издаться{}, // издаться на деньги спонсоров rus_verbs:смещаться{}, // смещаться на несколько миллиметров rus_verbs:зазывать{}, // зазывать на новогоднюю распродажу rus_verbs:пикировать{}, // пикировать на окопы rus_verbs:чертыхаться{}, // чертыхаться на мешающихся детей rus_verbs:зудить{}, // зудить на ухо rus_verbs:подразделяться{}, // подразделяться на группы rus_verbs:изливаться{}, // изливаться на землю rus_verbs:помочиться{}, // помочиться на траву rus_verbs:примерять{}, // примерять на себя rus_verbs:разрядиться{}, // разрядиться на землю rus_verbs:мотнуться{}, // мотнуться на крышу rus_verbs:налегать{}, // налегать на весла rus_verbs:зацокать{}, // зацокать на куриц rus_verbs:наниматься{}, // наниматься на корабль rus_verbs:сплевывать{}, // сплевывать на землю rus_verbs:настучать{}, // настучать на саботажника rus_verbs:приземляться{}, // приземляться на брюхо rus_verbs:наталкиваться{}, // наталкиваться на объективные трудности rus_verbs:посигналить{}, // посигналить нарушителю, выехавшему на встречную полосу rus_verbs:серчать{}, // серчать на нерасторопную помощницу rus_verbs:сваливать{}, // сваливать на подоконник rus_verbs:засобираться{}, // засобираться на работу rus_verbs:распилить{}, // распилить на одинаковые бруски //rus_verbs:умножать{}, // умножать на константу rus_verbs:копировать{}, // копировать на диск rus_verbs:накрутить{}, // накрутить на руку rus_verbs:навалить{}, // навалить на телегу rus_verbs:натолкнуть{}, // натолкнуть на свежую мысль rus_verbs:шлепаться{}, // шлепаться на бетон rus_verbs:ухлопать{}, // ухлопать на скупку произведений искусства rus_verbs:замахиваться{}, // замахиваться на авторитетнейшее мнение rus_verbs:посягнуть{}, // посягнуть на святое rus_verbs:разменять{}, // разменять на мелочь rus_verbs:откатываться{}, // откатываться на заранее подготовленные позиции rus_verbs:усаживать{}, // усаживать на скамейку rus_verbs:натаскать{}, // натаскать на поиск наркотиков rus_verbs:зашикать{}, // зашикать на кошку rus_verbs:разломать{}, // разломать на равные части rus_verbs:приглашаться{}, // приглашаться на сцену rus_verbs:присягать{}, // присягать на верность rus_verbs:запрограммировать{}, // запрограммировать на постоянную уборку rus_verbs:расщедриться{}, // расщедриться на новый компьютер rus_verbs:насесть{}, // насесть на двоечников rus_verbs:созывать{}, // созывать на собрание rus_verbs:позариться{}, // позариться на чужое добро rus_verbs:перекидываться{}, // перекидываться на соседние здания rus_verbs:наползать{}, // наползать на неповрежденную ткань rus_verbs:изрубить{}, // изрубить на мелкие кусочки rus_verbs:наворачиваться{}, // наворачиваться на глаза rus_verbs:раскричаться{}, // раскричаться на всю округу rus_verbs:переползти{}, // переползти на светлую сторону rus_verbs:уполномочить{}, // уполномочить на разведовательную операцию rus_verbs:мочиться{}, // мочиться на трупы убитых врагов rus_verbs:радировать{}, // радировать на базу rus_verbs:промотать{}, // промотать на начало rus_verbs:заснять{}, // заснять на видео rus_verbs:подбивать{}, // подбивать на матч-реванш rus_verbs:наплевать{}, // наплевать на справедливость rus_verbs:подвывать{}, // подвывать на луну rus_verbs:расплескать{}, // расплескать на пол rus_verbs:польститься{}, // польститься на бесплатный сыр rus_verbs:помчать{}, // помчать на работу rus_verbs:съезжать{}, // съезжать на обочину rus_verbs:нашептать{}, // нашептать кому-то на ухо rus_verbs:наклеить{}, // наклеить на доску объявлений rus_verbs:завозить{}, // завозить на склад rus_verbs:заявляться{}, // заявляться на любимую работу rus_verbs:наглядеться{}, // наглядеться на воробьев rus_verbs:хлопнуться{}, // хлопнуться на живот rus_verbs:забредать{}, // забредать на поляну rus_verbs:посягать{}, // посягать на исконные права собственности rus_verbs:сдвигать{}, // сдвигать на одну позицию rus_verbs:спрыгивать{}, // спрыгивать на землю rus_verbs:сдвигаться{}, // сдвигаться на две позиции rus_verbs:разделать{}, // разделать на орехи rus_verbs:разлагать{}, // разлагать на элементарные элементы rus_verbs:обрушивать{}, // обрушивать на головы врагов rus_verbs:натечь{}, // натечь на пол rus_verbs:политься{}, // вода польется на землю rus_verbs:успеть{}, // Они успеют на поезд. инфинитив:мигрировать{ вид:несоверш }, глагол:мигрировать{ вид:несоверш }, деепричастие:мигрируя{}, инфинитив:мигрировать{ вид:соверш }, глагол:мигрировать{ вид:соверш }, деепричастие:мигрировав{}, rus_verbs:двинуться{}, // Мы скоро двинемся на дачу. rus_verbs:подойти{}, // Он не подойдёт на должность секретаря. rus_verbs:потянуть{}, // Он не потянет на директора. rus_verbs:тянуть{}, // Он не тянет на директора. rus_verbs:перескакивать{}, // перескакивать с одного примера на другой rus_verbs:жаловаться{}, // Он жалуется на нездоровье. rus_verbs:издать{}, // издать на деньги спонсоров rus_verbs:показаться{}, // показаться на глаза rus_verbs:высаживать{}, // высаживать на необитаемый остров rus_verbs:вознестись{}, // вознестись на самую вершину славы rus_verbs:залить{}, // залить на youtube rus_verbs:закачать{}, // закачать на youtube rus_verbs:сыграть{}, // сыграть на деньги rus_verbs:экстраполировать{}, // Формулу можно экстраполировать на случай нескольких переменных инфинитив:экстраполироваться{ вид:несоверш}, // Ситуация легко экстраполируется на случай нескольких переменных глагол:экстраполироваться{ вид:несоверш}, инфинитив:экстраполироваться{ вид:соверш}, глагол:экстраполироваться{ вид:соверш}, деепричастие:экстраполируясь{}, инфинитив:акцентировать{вид:соверш}, // оратор акцентировал внимание слушателей на новый аспект проблемы глагол:акцентировать{вид:соверш}, инфинитив:акцентировать{вид:несоверш}, глагол:акцентировать{вид:несоверш}, прилагательное:акцентировавший{вид:несоверш}, //прилагательное:акцентировавший{вид:соверш}, прилагательное:акцентирующий{}, деепричастие:акцентировав{}, деепричастие:акцентируя{}, rus_verbs:бабахаться{}, // он бабахался на пол rus_verbs:бабахнуться{}, // мальчил бабахнулся на асфальт rus_verbs:батрачить{}, // Крестьяне батрачили на хозяина rus_verbs:бахаться{}, // Наездники бахались на землю rus_verbs:бахнуться{}, // Наездник опять бахнулся на землю rus_verbs:благословить{}, // батюшка благословил отрока на подвиг rus_verbs:благословлять{}, // батюшка благословляет отрока на подвиг rus_verbs:блевануть{}, // Он блеванул на землю rus_verbs:блевать{}, // Он блюет на землю rus_verbs:бухнуться{}, // Наездник бухнулся на землю rus_verbs:валить{}, // Ветер валил деревья на землю rus_verbs:спилить{}, // Спиленное дерево валится на землю rus_verbs:ввезти{}, // Предприятие ввезло товар на таможню rus_verbs:вдохновить{}, // Фильм вдохновил мальчика на поход в лес rus_verbs:вдохновиться{}, // Мальчик вдохновился на поход rus_verbs:вдохновлять{}, // Фильм вдохновляет на поход в лес rus_verbs:вестись{}, // Не ведись на эти уловки! rus_verbs:вешать{}, // Гости вешают одежду на вешалку rus_verbs:вешаться{}, // Одежда вешается на вешалки rus_verbs:вещать{}, // радиостанция вещает на всю страну rus_verbs:взбираться{}, // Туристы взбираются на заросший лесом холм rus_verbs:взбредать{}, // Что иногда взбредает на ум rus_verbs:взбрести{}, // Что-то взбрело на ум rus_verbs:взвалить{}, // Мама взвалила на свои плечи всё домашнее хозяйство rus_verbs:взваливаться{}, // Все домашнее хозяйство взваливается на мамины плечи rus_verbs:взваливать{}, // Не надо взваливать всё на мои плечи rus_verbs:взглянуть{}, // Кошка взглянула на мышку rus_verbs:взгромождать{}, // Мальчик взгромождает стул на стол rus_verbs:взгромождаться{}, // Мальчик взгромождается на стол rus_verbs:взгромоздить{}, // Мальчик взгромоздил стул на стол rus_verbs:взгромоздиться{}, // Мальчик взгромоздился на стул rus_verbs:взирать{}, // Очевидцы взирали на непонятный объект rus_verbs:взлетать{}, // Фабрика фейерверков взлетает на воздух rus_verbs:взлететь{}, // Фабрика фейерверков взлетела на воздух rus_verbs:взобраться{}, // Туристы взобрались на гору rus_verbs:взойти{}, // Туристы взошли на гору rus_verbs:взъесться{}, // Отец взъелся на непутевого сына rus_verbs:взъяриться{}, // Отец взъярился на непутевого сына rus_verbs:вкатить{}, // рабочие вкатили бочку на пандус rus_verbs:вкатывать{}, // рабочик вкатывают бочку на пандус rus_verbs:влиять{}, // Это решение влияет на всех игроков рынка rus_verbs:водворить{}, // водворить нарушителя на место rus_verbs:водвориться{}, // водвориться на свое место rus_verbs:водворять{}, // водворять вещь на свое место rus_verbs:водворяться{}, // водворяться на свое место rus_verbs:водружать{}, // водружать флаг на флагшток rus_verbs:водружаться{}, // Флаг водружается на флагшток rus_verbs:водрузить{}, // водрузить флаг на флагшток rus_verbs:водрузиться{}, // Флаг водрузился на вершину горы rus_verbs:воздействовать{}, // Излучение воздействует на кожу rus_verbs:воззреть{}, // воззреть на поле боя rus_verbs:воззриться{}, // воззриться на поле боя rus_verbs:возить{}, // возить туристов на гору rus_verbs:возлагать{}, // Многочисленные посетители возлагают цветы на могилу rus_verbs:возлагаться{}, // Ответственность возлагается на начальство rus_verbs:возлечь{}, // возлечь на лежанку rus_verbs:возложить{}, // возложить цветы на могилу поэта rus_verbs:вознести{}, // вознести кого-то на вершину славы rus_verbs:возноситься{}, // возносится на вершину успеха rus_verbs:возносить{}, // возносить счастливчика на вершину успеха rus_verbs:подниматься{}, // Мы поднимаемся на восьмой этаж rus_verbs:подняться{}, // Мы поднялись на восьмой этаж rus_verbs:вонять{}, // Кусок сыра воняет на всю округу rus_verbs:воодушевлять{}, // Идеалы воодушевляют на подвиги rus_verbs:воодушевляться{}, // Люди воодушевляются на подвиги rus_verbs:ворчать{}, // Старый пес ворчит на прохожих rus_verbs:воспринимать{}, // воспринимать сообщение на слух rus_verbs:восприниматься{}, // сообщение плохо воспринимается на слух rus_verbs:воспринять{}, // воспринять сообщение на слух rus_verbs:восприняться{}, // восприняться на слух rus_verbs:воссесть{}, // Коля воссел на трон rus_verbs:вправить{}, // вправить мозг на место rus_verbs:вправлять{}, // вправлять мозги на место rus_verbs:временить{}, // временить с выходом на пенсию rus_verbs:врубать{}, // врубать на полную мощность rus_verbs:врубить{}, // врубить на полную мощность rus_verbs:врубиться{}, // врубиться на полную мощность rus_verbs:врываться{}, // врываться на собрание rus_verbs:вскарабкаться{}, // вскарабкаться на утёс rus_verbs:вскарабкиваться{}, // вскарабкиваться на утёс rus_verbs:вскочить{}, // вскочить на ноги rus_verbs:всплывать{}, // всплывать на поверхность воды rus_verbs:всплыть{}, // всплыть на поверхность воды rus_verbs:вспрыгивать{}, // вспрыгивать на платформу rus_verbs:вспрыгнуть{}, // вспрыгнуть на платформу rus_verbs:встать{}, // встать на защиту чести и достоинства rus_verbs:вторгаться{}, // вторгаться на чужую территорию rus_verbs:вторгнуться{}, // вторгнуться на чужую территорию rus_verbs:въезжать{}, // въезжать на пандус rus_verbs:наябедничать{}, // наябедничать на соседа по парте rus_verbs:выблевать{}, // выблевать завтрак на пол rus_verbs:выблеваться{}, // выблеваться на пол rus_verbs:выблевывать{}, // выблевывать завтрак на пол rus_verbs:выблевываться{}, // выблевываться на пол rus_verbs:вывезти{}, // вывезти мусор на свалку rus_verbs:вывесить{}, // вывесить белье на просушку rus_verbs:вывести{}, // вывести собаку на прогулку rus_verbs:вывешивать{}, // вывешивать белье на веревку rus_verbs:вывозить{}, // вывозить детей на природу rus_verbs:вызывать{}, // Начальник вызывает на ковер rus_verbs:выйти{}, // выйти на свободу rus_verbs:выкладывать{}, // выкладывать на всеобщее обозрение rus_verbs:выкладываться{}, // выкладываться на всеобщее обозрение rus_verbs:выливать{}, // выливать на землю rus_verbs:выливаться{}, // выливаться на землю rus_verbs:вылить{}, // вылить жидкость на землю rus_verbs:вылиться{}, // Топливо вылилось на землю rus_verbs:выложить{}, // выложить на берег rus_verbs:выменивать{}, // выменивать золото на хлеб rus_verbs:вымениваться{}, // Золото выменивается на хлеб rus_verbs:выменять{}, // выменять золото на хлеб rus_verbs:выпадать{}, // снег выпадает на землю rus_verbs:выплевывать{}, // выплевывать на землю rus_verbs:выплевываться{}, // выплевываться на землю rus_verbs:выплескать{}, // выплескать на землю rus_verbs:выплескаться{}, // выплескаться на землю rus_verbs:выплескивать{}, // выплескивать на землю rus_verbs:выплескиваться{}, // выплескиваться на землю rus_verbs:выплывать{}, // выплывать на поверхность rus_verbs:выплыть{}, // выплыть на поверхность rus_verbs:выплюнуть{}, // выплюнуть на пол rus_verbs:выползать{}, // выползать на свежий воздух rus_verbs:выпроситься{}, // выпроситься на улицу rus_verbs:выпрыгивать{}, // выпрыгивать на свободу rus_verbs:выпрыгнуть{}, // выпрыгнуть на перрон rus_verbs:выпускать{}, // выпускать на свободу rus_verbs:выпустить{}, // выпустить на свободу rus_verbs:выпучивать{}, // выпучивать на кого-то глаза rus_verbs:выпучиваться{}, // глаза выпучиваются на кого-то rus_verbs:выпучить{}, // выпучить глаза на кого-то rus_verbs:выпучиться{}, // выпучиться на кого-то rus_verbs:выронить{}, // выронить на землю rus_verbs:высадить{}, // высадить на берег rus_verbs:высадиться{}, // высадиться на берег rus_verbs:высаживаться{}, // высаживаться на остров rus_verbs:выскальзывать{}, // выскальзывать на землю rus_verbs:выскочить{}, // выскочить на сцену rus_verbs:высморкаться{}, // высморкаться на землю rus_verbs:высморкнуться{}, // высморкнуться на землю rus_verbs:выставить{}, // выставить на всеобщее обозрение rus_verbs:выставиться{}, // выставиться на всеобщее обозрение rus_verbs:выставлять{}, // выставлять на всеобщее обозрение rus_verbs:выставляться{}, // выставляться на всеобщее обозрение инфинитив:высыпать{вид:соверш}, // высыпать на землю инфинитив:высыпать{вид:несоверш}, глагол:высыпать{вид:соверш}, глагол:высыпать{вид:несоверш}, деепричастие:высыпав{}, деепричастие:высыпая{}, прилагательное:высыпавший{вид:соверш}, //++прилагательное:высыпавший{вид:несоверш}, прилагательное:высыпающий{вид:несоверш}, rus_verbs:высыпаться{}, // высыпаться на землю rus_verbs:вытаращивать{}, // вытаращивать глаза на медведя rus_verbs:вытаращиваться{}, // вытаращиваться на медведя rus_verbs:вытаращить{}, // вытаращить глаза на медведя rus_verbs:вытаращиться{}, // вытаращиться на медведя rus_verbs:вытекать{}, // вытекать на землю rus_verbs:вытечь{}, // вытечь на землю rus_verbs:выучиваться{}, // выучиваться на кого-то rus_verbs:выучиться{}, // выучиться на кого-то rus_verbs:посмотреть{}, // посмотреть на экран rus_verbs:нашить{}, // нашить что-то на одежду rus_verbs:придти{}, // придти на помощь кому-то инфинитив:прийти{}, // прийти на помощь кому-то глагол:прийти{}, деепричастие:придя{}, // Придя на вокзал, он поспешно взял билеты. rus_verbs:поднять{}, // поднять на вершину rus_verbs:согласиться{}, // согласиться на ничью rus_verbs:послать{}, // послать на фронт rus_verbs:слать{}, // слать на фронт rus_verbs:надеяться{}, // надеяться на лучшее rus_verbs:крикнуть{}, // крикнуть на шалунов rus_verbs:пройти{}, // пройти на пляж rus_verbs:прислать{}, // прислать на экспертизу rus_verbs:жить{}, // жить на подачки rus_verbs:становиться{}, // становиться на ноги rus_verbs:наслать{}, // наслать на кого-то rus_verbs:принять{}, // принять на заметку rus_verbs:собираться{}, // собираться на экзамен rus_verbs:оставить{}, // оставить на всякий случай rus_verbs:звать{}, // звать на помощь rus_verbs:направиться{}, // направиться на прогулку rus_verbs:отвечать{}, // отвечать на звонки rus_verbs:отправиться{}, // отправиться на прогулку rus_verbs:поставить{}, // поставить на пол rus_verbs:обернуться{}, // обернуться на зов rus_verbs:отозваться{}, // отозваться на просьбу rus_verbs:закричать{}, // закричать на собаку rus_verbs:опустить{}, // опустить на землю rus_verbs:принести{}, // принести на пляж свой жезлонг rus_verbs:указать{}, // указать на дверь rus_verbs:ходить{}, // ходить на занятия rus_verbs:уставиться{}, // уставиться на листок rus_verbs:приходить{}, // приходить на экзамен rus_verbs:махнуть{}, // махнуть на пляж rus_verbs:явиться{}, // явиться на допрос rus_verbs:оглянуться{}, // оглянуться на дорогу rus_verbs:уехать{}, // уехать на заработки rus_verbs:повести{}, // повести на штурм rus_verbs:опуститься{}, // опуститься на колени //rus_verbs:передать{}, // передать на проверку rus_verbs:побежать{}, // побежать на занятия rus_verbs:прибыть{}, // прибыть на место службы rus_verbs:кричать{}, // кричать на медведя rus_verbs:стечь{}, // стечь на землю rus_verbs:обратить{}, // обратить на себя внимание rus_verbs:подать{}, // подать на пропитание rus_verbs:привести{}, // привести на съемки rus_verbs:испытывать{}, // испытывать на животных rus_verbs:перевести{}, // перевести на жену rus_verbs:купить{}, // купить на заемные деньги rus_verbs:собраться{}, // собраться на встречу rus_verbs:заглянуть{}, // заглянуть на огонёк rus_verbs:нажать{}, // нажать на рычаг rus_verbs:поспешить{}, // поспешить на праздник rus_verbs:перейти{}, // перейти на русский язык rus_verbs:поверить{}, // поверить на честное слово rus_verbs:глянуть{}, // глянуть на обложку rus_verbs:зайти{}, // зайти на огонёк rus_verbs:проходить{}, // проходить на сцену rus_verbs:глядеть{}, // глядеть на актрису //rus_verbs:решиться{}, // решиться на прыжок rus_verbs:пригласить{}, // пригласить на танец rus_verbs:позвать{}, // позвать на экзамен rus_verbs:усесться{}, // усесться на стул rus_verbs:поступить{}, // поступить на математический факультет rus_verbs:лечь{}, // лечь на живот rus_verbs:потянуться{}, // потянуться на юг rus_verbs:присесть{}, // присесть на корточки rus_verbs:наступить{}, // наступить на змею rus_verbs:заорать{}, // заорать на попрошаек rus_verbs:надеть{}, // надеть на голову rus_verbs:поглядеть{}, // поглядеть на девчонок rus_verbs:принимать{}, // принимать на гарантийное обслуживание rus_verbs:привезти{}, // привезти на испытания rus_verbs:рухнуть{}, // рухнуть на асфальт rus_verbs:пускать{}, // пускать на корм rus_verbs:отвести{}, // отвести на приём rus_verbs:отправить{}, // отправить на утилизацию rus_verbs:двигаться{}, // двигаться на восток rus_verbs:нести{}, // нести на пляж rus_verbs:падать{}, // падать на руки rus_verbs:откинуться{}, // откинуться на спинку кресла rus_verbs:рявкнуть{}, // рявкнуть на детей rus_verbs:получать{}, // получать на проживание rus_verbs:полезть{}, // полезть на рожон rus_verbs:направить{}, // направить на дообследование rus_verbs:приводить{}, // приводить на проверку rus_verbs:потребоваться{}, // потребоваться на замену rus_verbs:кинуться{}, // кинуться на нападавшего rus_verbs:учиться{}, // учиться на токаря rus_verbs:приподнять{}, // приподнять на один метр rus_verbs:налить{}, // налить на стол rus_verbs:играть{}, // играть на деньги rus_verbs:рассчитывать{}, // рассчитывать на подмогу rus_verbs:шепнуть{}, // шепнуть на ухо rus_verbs:швырнуть{}, // швырнуть на землю rus_verbs:прыгнуть{}, // прыгнуть на оленя rus_verbs:предлагать{}, // предлагать на выбор rus_verbs:садиться{}, // садиться на стул rus_verbs:лить{}, // лить на землю rus_verbs:испытать{}, // испытать на животных rus_verbs:фыркнуть{}, // фыркнуть на детеныша rus_verbs:годиться{}, // мясо годится на фарш rus_verbs:проверить{}, // проверить высказывание на истинность rus_verbs:откликнуться{}, // откликнуться на призывы rus_verbs:полагаться{}, // полагаться на интуицию rus_verbs:покоситься{}, // покоситься на соседа rus_verbs:повесить{}, // повесить на гвоздь инфинитив:походить{вид:соверш}, // походить на занятия глагол:походить{вид:соверш}, деепричастие:походив{}, прилагательное:походивший{}, rus_verbs:помчаться{}, // помчаться на экзамен rus_verbs:ставить{}, // ставить на контроль rus_verbs:свалиться{}, // свалиться на землю rus_verbs:валиться{}, // валиться на землю rus_verbs:подарить{}, // подарить на день рожденья rus_verbs:сбежать{}, // сбежать на необитаемый остров rus_verbs:стрелять{}, // стрелять на поражение rus_verbs:обращать{}, // обращать на себя внимание rus_verbs:наступать{}, // наступать на те же грабли rus_verbs:сбросить{}, // сбросить на землю rus_verbs:обидеться{}, // обидеться на друга rus_verbs:устроиться{}, // устроиться на стажировку rus_verbs:погрузиться{}, // погрузиться на большую глубину rus_verbs:течь{}, // течь на землю rus_verbs:отбросить{}, // отбросить на землю rus_verbs:метать{}, // метать на дно rus_verbs:пустить{}, // пустить на переплавку rus_verbs:прожить{}, // прожить на пособие rus_verbs:полететь{}, // полететь на континент rus_verbs:пропустить{}, // пропустить на сцену rus_verbs:указывать{}, // указывать на ошибку rus_verbs:наткнуться{}, // наткнуться на клад rus_verbs:рвануть{}, // рвануть на юг rus_verbs:ступать{}, // ступать на землю rus_verbs:спрыгнуть{}, // спрыгнуть на берег rus_verbs:заходить{}, // заходить на огонёк rus_verbs:нырнуть{}, // нырнуть на глубину rus_verbs:рвануться{}, // рвануться на свободу rus_verbs:натянуть{}, // натянуть на голову rus_verbs:забраться{}, // забраться на стол rus_verbs:помахать{}, // помахать на прощание rus_verbs:содержать{}, // содержать на спонсорскую помощь rus_verbs:приезжать{}, // приезжать на праздники rus_verbs:проникнуть{}, // проникнуть на территорию rus_verbs:подъехать{}, // подъехать на митинг rus_verbs:устремиться{}, // устремиться на волю rus_verbs:посадить{}, // посадить на стул rus_verbs:ринуться{}, // ринуться на голкипера rus_verbs:подвигнуть{}, // подвигнуть на подвиг rus_verbs:отдавать{}, // отдавать на перевоспитание rus_verbs:отложить{}, // отложить на черный день rus_verbs:убежать{}, // убежать на танцы rus_verbs:поднимать{}, // поднимать на верхний этаж rus_verbs:переходить{}, // переходить на цифровой сигнал rus_verbs:отослать{}, // отослать на переаттестацию rus_verbs:отодвинуть{}, // отодвинуть на другую половину стола rus_verbs:назначить{}, // назначить на должность rus_verbs:осесть{}, // осесть на дно rus_verbs:торопиться{}, // торопиться на экзамен rus_verbs:менять{}, // менять на еду rus_verbs:доставить{}, // доставить на шестой этаж rus_verbs:заслать{}, // заслать на проверку rus_verbs:дуть{}, // дуть на воду rus_verbs:сослать{}, // сослать на каторгу rus_verbs:останавливаться{}, // останавливаться на отдых rus_verbs:сдаваться{}, // сдаваться на милость победителя rus_verbs:сослаться{}, // сослаться на презумпцию невиновности rus_verbs:рассердиться{}, // рассердиться на дочь rus_verbs:кинуть{}, // кинуть на землю rus_verbs:расположиться{}, // расположиться на ночлег rus_verbs:осмелиться{}, // осмелиться на подлог rus_verbs:шептать{}, // шептать на ушко rus_verbs:уронить{}, // уронить на землю rus_verbs:откинуть{}, // откинуть на спинку кресла rus_verbs:перенести{}, // перенести на рабочий стол rus_verbs:сдаться{}, // сдаться на милость победителя rus_verbs:светить{}, // светить на дорогу rus_verbs:мчаться{}, // мчаться на бал rus_verbs:нестись{}, // нестись на свидание rus_verbs:поглядывать{}, // поглядывать на экран rus_verbs:орать{}, // орать на детей rus_verbs:уложить{}, // уложить на лопатки rus_verbs:решаться{}, // решаться на поступок rus_verbs:попадать{}, // попадать на карандаш rus_verbs:сплюнуть{}, // сплюнуть на землю rus_verbs:снимать{}, // снимать на телефон rus_verbs:опоздать{}, // опоздать на работу rus_verbs:посылать{}, // посылать на проверку rus_verbs:погнать{}, // погнать на пастбище rus_verbs:поступать{}, // поступать на кибернетический факультет rus_verbs:спускаться{}, // спускаться на уровень моря rus_verbs:усадить{}, // усадить на диван rus_verbs:проиграть{}, // проиграть на спор rus_verbs:прилететь{}, // прилететь на фестиваль rus_verbs:повалиться{}, // повалиться на спину rus_verbs:огрызнуться{}, // Собака огрызнулась на хозяина rus_verbs:задавать{}, // задавать на выходные rus_verbs:запасть{}, // запасть на девочку rus_verbs:лезть{}, // лезть на забор rus_verbs:потащить{}, // потащить на выборы rus_verbs:направляться{}, // направляться на экзамен rus_verbs:определять{}, // определять на вкус rus_verbs:поползти{}, // поползти на стену rus_verbs:поплыть{}, // поплыть на берег rus_verbs:залезть{}, // залезть на яблоню rus_verbs:сдать{}, // сдать на мясокомбинат rus_verbs:приземлиться{}, // приземлиться на дорогу rus_verbs:лаять{}, // лаять на прохожих rus_verbs:перевернуть{}, // перевернуть на бок rus_verbs:ловить{}, // ловить на живца rus_verbs:отнести{}, // отнести животное на хирургический стол rus_verbs:плюнуть{}, // плюнуть на условности rus_verbs:передавать{}, // передавать на проверку rus_verbs:нанять{}, // Босс нанял на работу еще несколько человек rus_verbs:разозлиться{}, // Папа разозлился на сына из-за плохих оценок по математике инфинитив:рассыпаться{вид:несоверш}, // рассыпаться на мелкие детали инфинитив:рассыпаться{вид:соверш}, глагол:рассыпаться{вид:несоверш}, глагол:рассыпаться{вид:соверш}, деепричастие:рассыпавшись{}, деепричастие:рассыпаясь{}, прилагательное:рассыпавшийся{вид:несоверш}, прилагательное:рассыпавшийся{вид:соверш}, прилагательное:рассыпающийся{}, rus_verbs:зарычать{}, // Медведица зарычала на медвежонка rus_verbs:призвать{}, // призвать на сборы rus_verbs:увезти{}, // увезти на дачу rus_verbs:содержаться{}, // содержаться на пожертвования rus_verbs:навести{}, // навести на скопление телескоп rus_verbs:отправляться{}, // отправляться на утилизацию rus_verbs:улечься{}, // улечься на животик rus_verbs:налететь{}, // налететь на препятствие rus_verbs:перевернуться{}, // перевернуться на спину rus_verbs:улететь{}, // улететь на родину rus_verbs:ложиться{}, // ложиться на бок rus_verbs:класть{}, // класть на место rus_verbs:отреагировать{}, // отреагировать на выступление rus_verbs:доставлять{}, // доставлять на дом rus_verbs:отнять{}, // отнять на благо правящей верхушки rus_verbs:ступить{}, // ступить на землю rus_verbs:сводить{}, // сводить на концерт знаменитой рок-группы rus_verbs:унести{}, // унести на работу rus_verbs:сходить{}, // сходить на концерт rus_verbs:потратить{}, // потратить на корм и наполнитель для туалета все деньги rus_verbs:соскочить{}, // соскочить на землю rus_verbs:пожаловаться{}, // пожаловаться на соседей rus_verbs:тащить{}, // тащить на замену rus_verbs:замахать{}, // замахать руками на паренька rus_verbs:заглядывать{}, // заглядывать на обед rus_verbs:соглашаться{}, // соглашаться на равный обмен rus_verbs:плюхнуться{}, // плюхнуться на мягкий пуфик rus_verbs:увести{}, // увести на осмотр rus_verbs:успевать{}, // успевать на контрольную работу rus_verbs:опрокинуть{}, // опрокинуть на себя rus_verbs:подавать{}, // подавать на апелляцию rus_verbs:прибежать{}, // прибежать на вокзал rus_verbs:отшвырнуть{}, // отшвырнуть на замлю rus_verbs:привлекать{}, // привлекать на свою сторону rus_verbs:опереться{}, // опереться на палку rus_verbs:перебраться{}, // перебраться на маленький островок rus_verbs:уговорить{}, // уговорить на новые траты rus_verbs:гулять{}, // гулять на спонсорские деньги rus_verbs:переводить{}, // переводить на другой путь rus_verbs:заколебаться{}, // заколебаться на один миг rus_verbs:зашептать{}, // зашептать на ушко rus_verbs:привстать{}, // привстать на цыпочки rus_verbs:хлынуть{}, // хлынуть на берег rus_verbs:наброситься{}, // наброситься на еду rus_verbs:напасть{}, // повстанцы, напавшие на конвой rus_verbs:убрать{}, // книга, убранная на полку rus_verbs:попасть{}, // путешественники, попавшие на ничейную территорию rus_verbs:засматриваться{}, // засматриваться на девчонок rus_verbs:застегнуться{}, // застегнуться на все пуговицы rus_verbs:провериться{}, // провериться на заболевания rus_verbs:проверяться{}, // проверяться на заболевания rus_verbs:тестировать{}, // тестировать на профпригодность rus_verbs:протестировать{}, // протестировать на профпригодность rus_verbs:уходить{}, // отец, уходящий на работу rus_verbs:налипнуть{}, // снег, налипший на провода rus_verbs:налипать{}, // снег, налипающий на провода rus_verbs:улетать{}, // Многие птицы улетают осенью на юг. rus_verbs:поехать{}, // она поехала на встречу с заказчиком rus_verbs:переключать{}, // переключать на резервную линию rus_verbs:переключаться{}, // переключаться на резервную линию rus_verbs:подписаться{}, // подписаться на обновление rus_verbs:нанести{}, // нанести на кожу rus_verbs:нарываться{}, // нарываться на неприятности rus_verbs:выводить{}, // выводить на орбиту rus_verbs:вернуться{}, // вернуться на родину rus_verbs:возвращаться{}, // возвращаться на родину прилагательное:падкий{}, // Он падок на деньги. прилагательное:обиженный{}, // Он обижен на отца. rus_verbs:косить{}, // Он косит на оба глаза. rus_verbs:закрыть{}, // Он забыл закрыть дверь на замок. прилагательное:готовый{}, // Он готов на всякие жертвы. rus_verbs:говорить{}, // Он говорит на скользкую тему. прилагательное:глухой{}, // Он глух на одно ухо. rus_verbs:взять{}, // Он взял ребёнка себе на колени. rus_verbs:оказывать{}, // Лекарство не оказывало на него никакого действия. rus_verbs:вести{}, // Лестница ведёт на третий этаж. rus_verbs:уполномочивать{}, // уполномочивать на что-либо глагол:спешить{ вид:несоверш }, // Я спешу на поезд. rus_verbs:брать{}, // Я беру всю ответственность на себя. rus_verbs:произвести{}, // Это произвело на меня глубокое впечатление. rus_verbs:употребить{}, // Эти деньги можно употребить на ремонт фабрики. rus_verbs:наводить{}, // Эта песня наводит на меня сон и скуку. rus_verbs:разбираться{}, // Эта машина разбирается на части. rus_verbs:оказать{}, // Эта книга оказала на меня большое влияние. rus_verbs:разбить{}, // Учитель разбил учеников на несколько групп. rus_verbs:отразиться{}, // Усиленная работа отразилась на его здоровье. rus_verbs:перегрузить{}, // Уголь надо перегрузить на другое судно. rus_verbs:делиться{}, // Тридцать делится на пять без остатка. rus_verbs:удаляться{}, // Суд удаляется на совещание. rus_verbs:показывать{}, // Стрелка компаса всегда показывает на север. rus_verbs:сохранить{}, // Сохраните это на память обо мне. rus_verbs:уезжать{}, // Сейчас все студенты уезжают на экскурсию. rus_verbs:лететь{}, // Самолёт летит на север. rus_verbs:бить{}, // Ружьё бьёт на пятьсот метров. // rus_verbs:прийтись{}, // Пятое число пришлось на субботу. rus_verbs:вынести{}, // Они вынесли из лодки на берег все вещи. rus_verbs:смотреть{}, // Она смотрит на нас из окна. rus_verbs:отдать{}, // Она отдала мне деньги на сохранение. rus_verbs:налюбоваться{}, // Не могу налюбоваться на картину. rus_verbs:любоваться{}, // гости любовались на картину rus_verbs:попробовать{}, // Дайте мне попробовать на ощупь. прилагательное:действительный{}, // Прививка оспы действительна только на три года. rus_verbs:спуститься{}, // На город спустился смог прилагательное:нечистый{}, // Он нечист на руку. прилагательное:неспособный{}, // Он неспособен на такую низость. прилагательное:злой{}, // кот очень зол на хозяина rus_verbs:пойти{}, // Девочка не пошла на урок физультуры rus_verbs:прибывать{}, // мой поезд прибывает на первый путь rus_verbs:застегиваться{}, // пальто застегивается на двадцать одну пуговицу rus_verbs:идти{}, // Дело идёт на лад. rus_verbs:лазить{}, // Он лазил на чердак. rus_verbs:поддаваться{}, // Он легко поддаётся на уговоры. // rus_verbs:действовать{}, // действующий на нервы rus_verbs:выходить{}, // Балкон выходит на площадь. rus_verbs:работать{}, // Время работает на нас. глагол:написать{aux stress="напис^ать"}, // Он написал музыку на слова Пушкина. rus_verbs:бросить{}, // Они бросили все силы на строительство. // глагол:разрезать{aux stress="разр^езать"}, глагол:разрезать{aux stress="разрез^ать"}, // Она разрезала пирог на шесть кусков. rus_verbs:броситься{}, // Она радостно бросилась мне на шею. rus_verbs:оправдать{}, // Она оправдала неявку на занятия болезнью. rus_verbs:ответить{}, // Она не ответила на мой поклон. rus_verbs:нашивать{}, // Она нашивала заплату на локоть. rus_verbs:молиться{}, // Она молится на свою мать. rus_verbs:запереть{}, // Она заперла дверь на замок. rus_verbs:заявить{}, // Она заявила свои права на наследство. rus_verbs:уйти{}, // Все деньги ушли на путешествие. rus_verbs:вступить{}, // Водолаз вступил на берег. rus_verbs:сойти{}, // Ночь сошла на землю. rus_verbs:приехать{}, // Мы приехали на вокзал слишком рано. rus_verbs:рыдать{}, // Не рыдай так безумно над ним. rus_verbs:подписать{}, // Не забудьте подписать меня на газету. rus_verbs:держать{}, // Наш пароход держал курс прямо на север. rus_verbs:свезти{}, // На выставку свезли экспонаты со всего мира. rus_verbs:ехать{}, // Мы сейчас едем на завод. rus_verbs:выбросить{}, // Волнами лодку выбросило на берег. ГЛ_ИНФ(сесть), // сесть на снег ГЛ_ИНФ(записаться), ГЛ_ИНФ(положить) // положи книгу на стол } #endregion VerbList // Чтобы разрешить связывание в паттернах типа: залить на youtube fact гл_предл { if context { Гл_НА_Вин предлог:на{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { глагол:купить{} предлог:на{} 'деньги'{падеж:вин} } then return true } fact гл_предл { if context { Гл_НА_Вин предлог:на{} *:*{ падеж:вин } } then return true } // смещаться на несколько миллиметров fact гл_предл { if context { Гл_НА_Вин предлог:на{} наречие:*{} } then return true } // партия взяла на себя нереалистичные обязательства fact гл_предл { if context { глагол:взять{} предлог:на{} 'себя'{падеж:вин} } then return true } #endregion ВИНИТЕЛЬНЫЙ // Все остальные варианты с предлогом 'НА' по умолчанию запрещаем. fact гл_предл { if context { * предлог:на{} *:*{ падеж:предл } } then return false,-3 } fact гл_предл { if context { * предлог:на{} *:*{ падеж:мест } } then return false,-3 } fact гл_предл { if context { * предлог:на{} *:*{ падеж:вин } } then return false,-4 } // Этот вариант нужен для обработки конструкций с числительными: // Президентские выборы разделили Венесуэлу на два непримиримых лагеря fact гл_предл { if context { * предлог:на{} *:*{ падеж:род } } then return false,-4 } // Продавать на eBay fact гл_предл { if context { * предлог:на{} * } then return false,-6 } #endregion Предлог_НА #region Предлог_С // ------------- ПРЕДЛОГ 'С' ----------------- // У этого предлога предпочтительная семантика привязывает его обычно к существительному. // Поэтому запрещаем по умолчанию его привязку к глаголам, а разрешенные глаголы перечислим. #region ТВОРИТЕЛЬНЫЙ wordentry_set Гл_С_Твор={ rus_verbs:помогать{}, // будет готов помогать врачам в онкологическом центре с постановкой верных диагнозов rus_verbs:перепихнуться{}, // неужели ты не хочешь со мной перепихнуться rus_verbs:забраться{}, rus_verbs:ДРАТЬСЯ{}, // Мои же собственные ратники забросали бы меня гнилой капустой, и мне пришлось бы драться с каждым рыцарем в стране, чтобы доказать свою смелость. (ДРАТЬСЯ/БИТЬСЯ/ПОДРАТЬСЯ) rus_verbs:БИТЬСЯ{}, // rus_verbs:ПОДРАТЬСЯ{}, // прилагательное:СХОЖИЙ{}, // Не был ли он схожим с одним из живых языков Земли (СХОЖИЙ) rus_verbs:ВСТУПИТЬ{}, // Он намеревался вступить с Вольфом в ближний бой. (ВСТУПИТЬ) rus_verbs:КОРРЕЛИРОВАТЬ{}, // Это коррелирует с традиционно сильными направлениями московской математической школы. (КОРРЕЛИРОВАТЬ) rus_verbs:УВИДЕТЬСЯ{}, // Он проигнорирует истерические протесты жены и увидится сначала с доктором, а затем с психотерапевтом (УВИДЕТЬСЯ) rus_verbs:ОЧНУТЬСЯ{}, // Когда он очнулся с болью в левой стороне черепа, у него возникло пугающее ощущение. (ОЧНУТЬСЯ) прилагательное:сходный{}, // Мозг этих существ сходен по размерам с мозгом динозавра rus_verbs:накрыться{}, // Было холодно, и он накрылся с головой одеялом. rus_verbs:РАСПРЕДЕЛИТЬ{}, // Бюджет распределят с участием горожан (РАСПРЕДЕЛИТЬ) rus_verbs:НАБРОСИТЬСЯ{}, // Пьяный водитель набросился с ножом на сотрудников ГИБДД (НАБРОСИТЬСЯ) rus_verbs:БРОСИТЬСЯ{}, // она со смехом бросилась прочь (БРОСИТЬСЯ) rus_verbs:КОНТАКТИРОВАТЬ{}, // Электронным магазинам стоит контактировать с клиентами (КОНТАКТИРОВАТЬ) rus_verbs:ВИДЕТЬСЯ{}, // Тогда мы редко виделись друг с другом rus_verbs:сесть{}, // сел в него с дорожной сумкой , наполненной наркотиками rus_verbs:купить{}, // Мы купили с ним одну и ту же книгу rus_verbs:ПРИМЕНЯТЬ{}, // Меры по стимулированию спроса в РФ следует применять с осторожностью (ПРИМЕНЯТЬ) rus_verbs:УЙТИ{}, // ты мог бы уйти со мной (УЙТИ) rus_verbs:ЖДАТЬ{}, // С нарастающим любопытством ждем результатов аудита золотых хранилищ европейских и американских центробанков (ЖДАТЬ) rus_verbs:ГОСПИТАЛИЗИРОВАТЬ{}, // Мэра Твери, участвовавшего в спартакиаде, госпитализировали с инфарктом (ГОСПИТАЛИЗИРОВАТЬ) rus_verbs:ЗАХЛОПНУТЬСЯ{}, // она захлопнулась со звоном (ЗАХЛОПНУТЬСЯ) rus_verbs:ОТВЕРНУТЬСЯ{}, // она со вздохом отвернулась (ОТВЕРНУТЬСЯ) rus_verbs:отправить{}, // вы можете отправить со мной человека rus_verbs:выступать{}, // Градоначальник , выступая с обзором основных городских событий , поведал об этом депутатам rus_verbs:ВЫЕЗЖАТЬ{}, // заключенные сами шьют куклы и иногда выезжают с представлениями в детский дом неподалеку (ВЫЕЗЖАТЬ С твор) rus_verbs:ПОКОНЧИТЬ{}, // со всем этим покончено (ПОКОНЧИТЬ С) rus_verbs:ПОБЕЖАТЬ{}, // Дмитрий побежал со всеми (ПОБЕЖАТЬ С) прилагательное:несовместимый{}, // характер ранений был несовместим с жизнью (НЕСОВМЕСТИМЫЙ С) rus_verbs:ПОСЕТИТЬ{}, // Его кабинет местные тележурналисты посетили со скрытой камерой (ПОСЕТИТЬ С) rus_verbs:СЛОЖИТЬСЯ{}, // сами банки принимают меры по урегулированию сложившейся с вкладчиками ситуации (СЛОЖИТЬСЯ С) rus_verbs:ЗАСТАТЬ{}, // Молодой человек убил пенсионера , застав его в постели с женой (ЗАСТАТЬ С) rus_verbs:ОЗНАКАМЛИВАТЬСЯ{}, // при заполнении заявления владельцы судов ознакамливаются с режимом (ОЗНАКАМЛИВАТЬСЯ С) rus_verbs:СООБРАЗОВЫВАТЬ{}, // И все свои задачи мы сообразовываем с этим пониманием (СООБРАЗОВЫВАТЬ С) rus_verbs:СВЫКАТЬСЯ{}, rus_verbs:стаскиваться{}, rus_verbs:спиливаться{}, rus_verbs:КОНКУРИРОВАТЬ{}, // Бедные и менее развитые страны не могут конкурировать с этими субсидиями (КОНКУРИРОВАТЬ С) rus_verbs:ВЫРВАТЬСЯ{}, // тот с трудом вырвался (ВЫРВАТЬСЯ С твор) rus_verbs:СОБРАТЬСЯ{}, // нужно собраться с силами (СОБРАТЬСЯ С) rus_verbs:УДАВАТЬСЯ{}, // удавалось это с трудом (УДАВАТЬСЯ С) rus_verbs:РАСПАХНУТЬСЯ{}, // дверь с треском распахнулась (РАСПАХНУТЬСЯ С) rus_verbs:НАБЛЮДАТЬ{}, // Олег наблюдал с любопытством (НАБЛЮДАТЬ С) rus_verbs:ПОТЯНУТЬ{}, // затем с силой потянул (ПОТЯНУТЬ С) rus_verbs:КИВНУТЬ{}, // Питер с трудом кивнул (КИВНУТЬ С) rus_verbs:СГЛОТНУТЬ{}, // Борис с трудом сглотнул (СГЛОТНУТЬ С) rus_verbs:ЗАБРАТЬ{}, // забрать его с собой (ЗАБРАТЬ С) rus_verbs:ОТКРЫТЬСЯ{}, // дверь с шипением открылась (ОТКРЫТЬСЯ С) rus_verbs:ОТОРВАТЬ{}, // с усилием оторвал взгляд (ОТОРВАТЬ С твор) rus_verbs:ОГЛЯДЕТЬСЯ{}, // Рома с любопытством огляделся (ОГЛЯДЕТЬСЯ С) rus_verbs:ФЫРКНУТЬ{}, // турок фыркнул с отвращением (ФЫРКНУТЬ С) rus_verbs:согласиться{}, // с этим согласились все (согласиться с) rus_verbs:ПОСЫПАТЬСЯ{}, // с грохотом посыпались камни (ПОСЫПАТЬСЯ С твор) rus_verbs:ВЗДОХНУТЬ{}, // Алиса вздохнула с облегчением (ВЗДОХНУТЬ С) rus_verbs:ОБЕРНУТЬСЯ{}, // та с удивлением обернулась (ОБЕРНУТЬСЯ С) rus_verbs:ХМЫКНУТЬ{}, // Алексей хмыкнул с сомнением (ХМЫКНУТЬ С твор) rus_verbs:ВЫЕХАТЬ{}, // они выехали с рассветом (ВЫЕХАТЬ С твор) rus_verbs:ВЫДОХНУТЬ{}, // Владимир выдохнул с облегчением (ВЫДОХНУТЬ С) rus_verbs:УХМЫЛЬНУТЬСЯ{}, // Кеша ухмыльнулся с сомнением (УХМЫЛЬНУТЬСЯ С) rus_verbs:НЕСТИСЬ{}, // тот несся с криком (НЕСТИСЬ С твор) rus_verbs:ПАДАТЬ{}, // падают с глухим стуком (ПАДАТЬ С твор) rus_verbs:ТВОРИТЬСЯ{}, // странное творилось с глазами (ТВОРИТЬСЯ С твор) rus_verbs:УХОДИТЬ{}, // с ними уходили эльфы (УХОДИТЬ С твор) rus_verbs:СКАКАТЬ{}, // скакали тут с топорами (СКАКАТЬ С твор) rus_verbs:ЕСТЬ{}, // здесь едят с зеленью (ЕСТЬ С твор) rus_verbs:ПОЯВИТЬСЯ{}, // с рассветом появились птицы (ПОЯВИТЬСЯ С твор) rus_verbs:ВСКОЧИТЬ{}, // Олег вскочил с готовностью (ВСКОЧИТЬ С твор) rus_verbs:БЫТЬ{}, // хочу быть с тобой (БЫТЬ С твор) rus_verbs:ПОКАЧАТЬ{}, // с сомнением покачал головой. (ПОКАЧАТЬ С СОМНЕНИЕМ) rus_verbs:ВЫРУГАТЬСЯ{}, // капитан с чувством выругался (ВЫРУГАТЬСЯ С ЧУВСТВОМ) rus_verbs:ОТКРЫТЬ{}, // с трудом открыл глаза (ОТКРЫТЬ С ТРУДОМ, таких много) rus_verbs:ПОЛУЧИТЬСЯ{}, // забавно получилось с ним (ПОЛУЧИТЬСЯ С) rus_verbs:ВЫБЕЖАТЬ{}, // старый выбежал с копьем (ВЫБЕЖАТЬ С) rus_verbs:ГОТОВИТЬСЯ{}, // Большинство компотов готовится с использованием сахара (ГОТОВИТЬСЯ С) rus_verbs:ПОДИСКУТИРОВАТЬ{}, // я бы подискутировал с Андрюхой (ПОДИСКУТИРОВАТЬ С) rus_verbs:ТУСИТЬ{}, // кто тусил со Светкой (ТУСИТЬ С) rus_verbs:БЕЖАТЬ{}, // куда она бежит со всеми? (БЕЖАТЬ С твор) rus_verbs:ГОРЕТЬ{}, // ты горел со своим кораблем? (ГОРЕТЬ С) rus_verbs:ВЫПИТЬ{}, // хотите выпить со мной чаю? (ВЫПИТЬ С) rus_verbs:МЕНЯТЬСЯ{}, // Я меняюсь с товарищем книгами. (МЕНЯТЬСЯ С) rus_verbs:ВАЛЯТЬСЯ{}, // Он уже неделю валяется с гриппом. (ВАЛЯТЬСЯ С) rus_verbs:ПИТЬ{}, // вы даже будете пить со мной пиво. (ПИТЬ С) инфинитив:кристаллизоваться{ вид:соверш }, // После этого пересыщенный раствор кристаллизуется с образованием кристаллов сахара. инфинитив:кристаллизоваться{ вид:несоверш }, глагол:кристаллизоваться{ вид:соверш }, глагол:кристаллизоваться{ вид:несоверш }, rus_verbs:ПООБЩАТЬСЯ{}, // пообщайся с Борисом (ПООБЩАТЬСЯ С) rus_verbs:ОБМЕНЯТЬСЯ{}, // Миша обменялся с Петей марками (ОБМЕНЯТЬСЯ С) rus_verbs:ПРОХОДИТЬ{}, // мы с тобой сегодня весь день проходили с вещами. (ПРОХОДИТЬ С) rus_verbs:ВСТАТЬ{}, // Он занимался всю ночь и встал с головной болью. (ВСТАТЬ С) rus_verbs:ПОВРЕМЕНИТЬ{}, // МВФ рекомендует Ирландии повременить с мерами экономии (ПОВРЕМЕНИТЬ С) rus_verbs:ГЛЯДЕТЬ{}, // Её глаза глядели с мягкой грустью. (ГЛЯДЕТЬ С + твор) rus_verbs:ВЫСКОЧИТЬ{}, // Зачем ты выскочил со своим замечанием? (ВЫСКОЧИТЬ С) rus_verbs:НЕСТИ{}, // плот несло со страшной силой. (НЕСТИ С) rus_verbs:приближаться{}, // стена приближалась со страшной быстротой. (приближаться с) rus_verbs:заниматься{}, // После уроков я занимался с отстающими учениками. (заниматься с) rus_verbs:разработать{}, // Этот лекарственный препарат разработан с использованием рецептов традиционной китайской медицины. (разработать с) rus_verbs:вестись{}, // Разработка месторождения ведется с использованием большого количества техники. (вестись с) rus_verbs:конфликтовать{}, // Маша конфликтует с Петей (конфликтовать с) rus_verbs:мешать{}, // мешать воду с мукой (мешать с) rus_verbs:иметь{}, // мне уже приходилось несколько раз иметь с ним дело. rus_verbs:синхронизировать{}, // синхронизировать с эталонным генератором rus_verbs:засинхронизировать{}, // засинхронизировать с эталонным генератором rus_verbs:синхронизироваться{}, // синхронизироваться с эталонным генератором rus_verbs:засинхронизироваться{}, // засинхронизироваться с эталонным генератором rus_verbs:стирать{}, // стирать с мылом рубашку в тазу rus_verbs:прыгать{}, // парашютист прыгает с парашютом rus_verbs:выступить{}, // Он выступил с приветствием съезду. rus_verbs:ходить{}, // В чужой монастырь со своим уставом не ходят. rus_verbs:отозваться{}, // Он отозвался об этой книге с большой похвалой. rus_verbs:отзываться{}, // Он отзывается об этой книге с большой похвалой. rus_verbs:вставать{}, // он встаёт с зарёй rus_verbs:мирить{}, // Его ум мирил всех с его дурным характером. rus_verbs:продолжаться{}, // стрельба тем временем продолжалась с прежней точностью. rus_verbs:договориться{}, // мы договоримся с вами rus_verbs:побыть{}, // он хотел побыть с тобой rus_verbs:расти{}, // Мировые производственные мощности растут с беспрецедентной скоростью rus_verbs:вязаться{}, // вязаться с фактами rus_verbs:отнестись{}, // отнестись к животным с сочуствием rus_verbs:относиться{}, // относиться с пониманием rus_verbs:пойти{}, // Спектакль пойдёт с участием известных артистов. rus_verbs:бракосочетаться{}, // Потомственный кузнец бракосочетался с разорившейся графиней rus_verbs:гулять{}, // бабушка гуляет с внуком rus_verbs:разбираться{}, // разбираться с задачей rus_verbs:сверить{}, // Данные были сверены с эталонными значениями rus_verbs:делать{}, // Что делать со старым телефоном rus_verbs:осматривать{}, // осматривать с удивлением rus_verbs:обсудить{}, // обсудить с приятелем прохождение уровня в новой игре rus_verbs:попрощаться{}, // попрощаться с талантливым актером rus_verbs:задремать{}, // задремать с кружкой чая в руке rus_verbs:связать{}, // связать катастрофу с действиями конкурентов rus_verbs:носиться{}, // носиться с безумной идеей rus_verbs:кончать{}, // кончать с собой rus_verbs:обмениваться{}, // обмениваться с собеседниками rus_verbs:переговариваться{}, // переговариваться с маяком rus_verbs:общаться{}, // общаться с полицией rus_verbs:завершить{}, // завершить с ошибкой rus_verbs:обняться{}, // обняться с подругой rus_verbs:сливаться{}, // сливаться с фоном rus_verbs:смешаться{}, // смешаться с толпой rus_verbs:договариваться{}, // договариваться с потерпевшим rus_verbs:обедать{}, // обедать с гостями rus_verbs:сообщаться{}, // сообщаться с подземной рекой rus_verbs:сталкиваться{}, // сталкиваться со стаей птиц rus_verbs:читаться{}, // читаться с трудом rus_verbs:смириться{}, // смириться с утратой rus_verbs:разделить{}, // разделить с другими ответственность rus_verbs:роднить{}, // роднить с медведем rus_verbs:медлить{}, // медлить с ответом rus_verbs:скрестить{}, // скрестить с ужом rus_verbs:покоиться{}, // покоиться с миром rus_verbs:делиться{}, // делиться с друзьями rus_verbs:познакомить{}, // познакомить с Олей rus_verbs:порвать{}, // порвать с Олей rus_verbs:завязать{}, // завязать с Олей знакомство rus_verbs:суетиться{}, // суетиться с изданием романа rus_verbs:соединиться{}, // соединиться с сервером rus_verbs:справляться{}, // справляться с нуждой rus_verbs:замешкаться{}, // замешкаться с ответом rus_verbs:поссориться{}, // поссориться с подругой rus_verbs:ссориться{}, // ссориться с друзьями rus_verbs:торопить{}, // торопить с решением rus_verbs:поздравить{}, // поздравить с победой rus_verbs:проститься{}, // проститься с человеком rus_verbs:поработать{}, // поработать с деревом rus_verbs:приключиться{}, // приключиться с Колей rus_verbs:сговориться{}, // сговориться с Ваней rus_verbs:отъехать{}, // отъехать с ревом rus_verbs:объединять{}, // объединять с другой кампанией rus_verbs:употребить{}, // употребить с молоком rus_verbs:перепутать{}, // перепутать с другой книгой rus_verbs:запоздать{}, // запоздать с ответом rus_verbs:подружиться{}, // подружиться с другими детьми rus_verbs:дружить{}, // дружить с Сережей rus_verbs:поравняться{}, // поравняться с финишной чертой rus_verbs:ужинать{}, // ужинать с гостями rus_verbs:расставаться{}, // расставаться с приятелями rus_verbs:завтракать{}, // завтракать с семьей rus_verbs:объединиться{}, // объединиться с соседями rus_verbs:сменяться{}, // сменяться с напарником rus_verbs:соединить{}, // соединить с сетью rus_verbs:разговориться{}, // разговориться с охранником rus_verbs:преподнести{}, // преподнести с помпой rus_verbs:напечатать{}, // напечатать с картинками rus_verbs:соединять{}, // соединять с сетью rus_verbs:расправиться{}, // расправиться с беззащитным человеком rus_verbs:распрощаться{}, // распрощаться с деньгами rus_verbs:сравнить{}, // сравнить с конкурентами rus_verbs:ознакомиться{}, // ознакомиться с выступлением инфинитив:сочетаться{ вид:несоверш }, глагол:сочетаться{ вид:несоверш }, // сочетаться с сумочкой деепричастие:сочетаясь{}, прилагательное:сочетающийся{}, прилагательное:сочетавшийся{}, rus_verbs:изнасиловать{}, // изнасиловать с применением чрезвычайного насилия rus_verbs:прощаться{}, // прощаться с боевым товарищем rus_verbs:сравнивать{}, // сравнивать с конкурентами rus_verbs:складывать{}, // складывать с весом упаковки rus_verbs:повестись{}, // повестись с ворами rus_verbs:столкнуть{}, // столкнуть с отбойником rus_verbs:переглядываться{}, // переглядываться с соседом rus_verbs:поторопить{}, // поторопить с откликом rus_verbs:развлекаться{}, // развлекаться с подружками rus_verbs:заговаривать{}, // заговаривать с незнакомцами rus_verbs:поцеловаться{}, // поцеловаться с первой девушкой инфинитив:согласоваться{ вид:несоверш }, глагол:согласоваться{ вид:несоверш }, // согласоваться с подлежащим деепричастие:согласуясь{}, прилагательное:согласующийся{}, rus_verbs:совпасть{}, // совпасть с оригиналом rus_verbs:соединяться{}, // соединяться с куратором rus_verbs:повстречаться{}, // повстречаться с героями rus_verbs:поужинать{}, // поужинать с родителями rus_verbs:развестись{}, // развестись с первым мужем rus_verbs:переговорить{}, // переговорить с коллегами rus_verbs:сцепиться{}, // сцепиться с бродячей собакой rus_verbs:сожрать{}, // сожрать с потрохами rus_verbs:побеседовать{}, // побеседовать со шпаной rus_verbs:поиграть{}, // поиграть с котятами rus_verbs:сцепить{}, // сцепить с тягачом rus_verbs:помириться{}, // помириться с подружкой rus_verbs:связываться{}, // связываться с бандитами rus_verbs:совещаться{}, // совещаться с мастерами rus_verbs:обрушиваться{}, // обрушиваться с беспощадной критикой rus_verbs:переплестись{}, // переплестись с кустами rus_verbs:мутить{}, // мутить с одногрупницами rus_verbs:приглядываться{}, // приглядываться с интересом rus_verbs:сблизиться{}, // сблизиться с врагами rus_verbs:перешептываться{}, // перешептываться с симпатичной соседкой rus_verbs:растереть{}, // растереть с солью rus_verbs:смешиваться{}, // смешиваться с известью rus_verbs:соприкоснуться{}, // соприкоснуться с тайной rus_verbs:ладить{}, // ладить с родственниками rus_verbs:сотрудничать{}, // сотрудничать с органами дознания rus_verbs:съехаться{}, // съехаться с родственниками rus_verbs:перекинуться{}, // перекинуться с коллегами парой слов rus_verbs:советоваться{}, // советоваться с отчимом rus_verbs:сравниться{}, // сравниться с лучшими rus_verbs:знакомиться{}, // знакомиться с абитуриентами rus_verbs:нырять{}, // нырять с аквалангом rus_verbs:забавляться{}, // забавляться с куклой rus_verbs:перекликаться{}, // перекликаться с другой статьей rus_verbs:тренироваться{}, // тренироваться с партнершей rus_verbs:поспорить{}, // поспорить с казночеем инфинитив:сладить{ вид:соверш }, глагол:сладить{ вид:соверш }, // сладить с бычком деепричастие:сладив{}, прилагательное:сладивший{ вид:соверш }, rus_verbs:примириться{}, // примириться с утратой rus_verbs:раскланяться{}, // раскланяться с фрейлинами rus_verbs:слечь{}, // слечь с ангиной rus_verbs:соприкасаться{}, // соприкасаться со стеной rus_verbs:смешать{}, // смешать с грязью rus_verbs:пересекаться{}, // пересекаться с трассой rus_verbs:путать{}, // путать с государственной шерстью rus_verbs:поболтать{}, // поболтать с ученицами rus_verbs:здороваться{}, // здороваться с профессором rus_verbs:просчитаться{}, // просчитаться с покупкой rus_verbs:сторожить{}, // сторожить с собакой rus_verbs:обыскивать{}, // обыскивать с собаками rus_verbs:переплетаться{}, // переплетаться с другой веткой rus_verbs:обниматься{}, // обниматься с Ксюшей rus_verbs:объединяться{}, // объединяться с конкурентами rus_verbs:погорячиться{}, // погорячиться с покупкой rus_verbs:мыться{}, // мыться с мылом rus_verbs:свериться{}, // свериться с эталоном rus_verbs:разделаться{}, // разделаться с кем-то rus_verbs:чередоваться{}, // чередоваться с партнером rus_verbs:налететь{}, // налететь с соратниками rus_verbs:поспать{}, // поспать с включенным светом rus_verbs:управиться{}, // управиться с собакой rus_verbs:согрешить{}, // согрешить с замужней rus_verbs:определиться{}, // определиться с победителем rus_verbs:перемешаться{}, // перемешаться с гранулами rus_verbs:затрудняться{}, // затрудняться с ответом rus_verbs:обождать{}, // обождать со стартом rus_verbs:фыркать{}, // фыркать с презрением rus_verbs:засидеться{}, // засидеться с приятелем rus_verbs:крепнуть{}, // крепнуть с годами rus_verbs:пировать{}, // пировать с дружиной rus_verbs:щебетать{}, // щебетать с сестричками rus_verbs:маяться{}, // маяться с кашлем rus_verbs:сближать{}, // сближать с центральным светилом rus_verbs:меркнуть{}, // меркнуть с возрастом rus_verbs:заспорить{}, // заспорить с оппонентами rus_verbs:граничить{}, // граничить с Ливаном rus_verbs:перестараться{}, // перестараться со стимуляторами rus_verbs:объединить{}, // объединить с филиалом rus_verbs:свыкнуться{}, // свыкнуться с утратой rus_verbs:посоветоваться{}, // посоветоваться с адвокатами rus_verbs:напутать{}, // напутать с ведомостями rus_verbs:нагрянуть{}, // нагрянуть с обыском rus_verbs:посовещаться{}, // посовещаться с судьей rus_verbs:провернуть{}, // провернуть с друганом rus_verbs:разделяться{}, // разделяться с сотрапезниками rus_verbs:пересечься{}, // пересечься с второй колонной rus_verbs:опережать{}, // опережать с большим запасом rus_verbs:перепутаться{}, // перепутаться с другой линией rus_verbs:соотноситься{}, // соотноситься с затратами rus_verbs:смешивать{}, // смешивать с золой rus_verbs:свидеться{}, // свидеться с тобой rus_verbs:переспать{}, // переспать с графиней rus_verbs:поладить{}, // поладить с соседями rus_verbs:протащить{}, // протащить с собой rus_verbs:разминуться{}, // разминуться с встречным потоком rus_verbs:перемежаться{}, // перемежаться с успехами rus_verbs:рассчитаться{}, // рассчитаться с кредиторами rus_verbs:срастись{}, // срастись с телом rus_verbs:знакомить{}, // знакомить с родителями rus_verbs:поругаться{}, // поругаться с родителями rus_verbs:совладать{}, // совладать с чувствами rus_verbs:обручить{}, // обручить с богатой невестой rus_verbs:сближаться{}, // сближаться с вражеским эсминцем rus_verbs:замутить{}, // замутить с Ксюшей rus_verbs:повозиться{}, // повозиться с настройкой rus_verbs:торговаться{}, // торговаться с продавцами rus_verbs:уединиться{}, // уединиться с девчонкой rus_verbs:переборщить{}, // переборщить с добавкой rus_verbs:ознакомить{}, // ознакомить с пожеланиями rus_verbs:прочесывать{}, // прочесывать с собаками rus_verbs:переписываться{}, // переписываться с корреспондентами rus_verbs:повздорить{}, // повздорить с сержантом rus_verbs:разлучить{}, // разлучить с семьей rus_verbs:соседствовать{}, // соседствовать с цыганами rus_verbs:застукать{}, // застукать с проститутками rus_verbs:напуститься{}, // напуститься с кулаками rus_verbs:сдружиться{}, // сдружиться с ребятами rus_verbs:соперничать{}, // соперничать с параллельным классом rus_verbs:прочесать{}, // прочесать с собаками rus_verbs:кокетничать{}, // кокетничать с гимназистками rus_verbs:мириться{}, // мириться с убытками rus_verbs:оплошать{}, // оплошать с билетами rus_verbs:отождествлять{}, // отождествлять с литературным героем rus_verbs:хитрить{}, // хитрить с зарплатой rus_verbs:провозиться{}, // провозиться с задачкой rus_verbs:коротать{}, // коротать с друзьями rus_verbs:соревноваться{}, // соревноваться с машиной rus_verbs:уживаться{}, // уживаться с местными жителями rus_verbs:отождествляться{}, // отождествляться с литературным героем rus_verbs:сопоставить{}, // сопоставить с эталоном rus_verbs:пьянствовать{}, // пьянствовать с друзьями rus_verbs:залетать{}, // залетать с паленой водкой rus_verbs:гастролировать{}, // гастролировать с новой цирковой программой rus_verbs:запаздывать{}, // запаздывать с кормлением rus_verbs:таскаться{}, // таскаться с сумками rus_verbs:контрастировать{}, // контрастировать с туфлями rus_verbs:сшибиться{}, // сшибиться с форвардом rus_verbs:состязаться{}, // состязаться с лучшей командой rus_verbs:затрудниться{}, // затрудниться с объяснением rus_verbs:объясниться{}, // объясниться с пострадавшими rus_verbs:разводиться{}, // разводиться со сварливой женой rus_verbs:препираться{}, // препираться с адвокатами rus_verbs:сосуществовать{}, // сосуществовать с крупными хищниками rus_verbs:свестись{}, // свестись с нулевым счетом rus_verbs:обговорить{}, // обговорить с директором rus_verbs:обвенчаться{}, // обвенчаться с ведьмой rus_verbs:экспериментировать{}, // экспериментировать с генами rus_verbs:сверять{}, // сверять с таблицей rus_verbs:сверяться{}, // свериться с таблицей rus_verbs:сблизить{}, // сблизить с точкой rus_verbs:гармонировать{}, // гармонировать с обоями rus_verbs:перемешивать{}, // перемешивать с молоком rus_verbs:трепаться{}, // трепаться с сослуживцами rus_verbs:перемигиваться{}, // перемигиваться с соседкой rus_verbs:разоткровенничаться{}, // разоткровенничаться с незнакомцем rus_verbs:распить{}, // распить с собутыльниками rus_verbs:скрестись{}, // скрестись с дикой лошадью rus_verbs:передраться{}, // передраться с дворовыми собаками rus_verbs:умыть{}, // умыть с мылом rus_verbs:грызться{}, // грызться с соседями rus_verbs:переругиваться{}, // переругиваться с соседями rus_verbs:доиграться{}, // доиграться со спичками rus_verbs:заладиться{}, // заладиться с подругой rus_verbs:скрещиваться{}, // скрещиваться с дикими видами rus_verbs:повидаться{}, // повидаться с дедушкой rus_verbs:повоевать{}, // повоевать с орками rus_verbs:сразиться{}, // сразиться с лучшим рыцарем rus_verbs:кипятить{}, // кипятить с отбеливателем rus_verbs:усердствовать{}, // усердствовать с наказанием rus_verbs:схлестнуться{}, // схлестнуться с лучшим боксером rus_verbs:пошептаться{}, // пошептаться с судьями rus_verbs:сравняться{}, // сравняться с лучшими экземплярами rus_verbs:церемониться{}, // церемониться с пьяницами rus_verbs:консультироваться{}, // консультироваться со специалистами rus_verbs:переусердствовать{}, // переусердствовать с наказанием rus_verbs:проноситься{}, // проноситься с собой rus_verbs:перемешать{}, // перемешать с гипсом rus_verbs:темнить{}, // темнить с долгами rus_verbs:сталкивать{}, // сталкивать с черной дырой rus_verbs:увольнять{}, // увольнять с волчьим билетом rus_verbs:заигрывать{}, // заигрывать с совершенно диким животным rus_verbs:сопоставлять{}, // сопоставлять с эталонными образцами rus_verbs:расторгнуть{}, // расторгнуть с нерасторопными поставщиками долгосрочный контракт rus_verbs:созвониться{}, // созвониться с мамой rus_verbs:спеться{}, // спеться с отъявленными хулиганами rus_verbs:интриговать{}, // интриговать с придворными rus_verbs:приобрести{}, // приобрести со скидкой rus_verbs:задержаться{}, // задержаться со сдачей работы rus_verbs:плавать{}, // плавать со спасательным кругом rus_verbs:якшаться{}, // Не якшайся с врагами инфинитив:ассоциировать{вид:соверш}, // читатели ассоциируют с собой героя книги инфинитив:ассоциировать{вид:несоверш}, глагол:ассоциировать{вид:соверш}, // читатели ассоциируют с собой героя книги глагол:ассоциировать{вид:несоверш}, //+прилагательное:ассоциировавший{вид:несоверш}, прилагательное:ассоциировавший{вид:соверш}, прилагательное:ассоциирующий{}, деепричастие:ассоциируя{}, деепричастие:ассоциировав{}, rus_verbs:ассоциироваться{}, // герой книги ассоциируется с реальным персонажем rus_verbs:аттестовывать{}, // Они аттестовывают сотрудников с помощью наборра тестов rus_verbs:аттестовываться{}, // Сотрудники аттестовываются с помощью набора тестов //+инфинитив:аффилировать{вид:соверш}, // эти предприятия были аффилированы с олигархом //+глагол:аффилировать{вид:соверш}, прилагательное:аффилированный{}, rus_verbs:баловаться{}, // мальчик баловался с молотком rus_verbs:балясничать{}, // женщина балясничала с товарками rus_verbs:богатеть{}, // Провинция богатеет от торговли с соседями rus_verbs:бодаться{}, // теленок бодается с деревом rus_verbs:боксировать{}, // Майкл дважды боксировал с ним rus_verbs:брататься{}, // Солдаты братались с бойцами союзников rus_verbs:вальсировать{}, // Мальчик вальсирует с девочкой rus_verbs:вверстывать{}, // Дизайнер с трудом вверстывает блоки в страницу rus_verbs:происходить{}, // Что происходит с мировой экономикой? rus_verbs:произойти{}, // Что произошло с экономикой? rus_verbs:взаимодействовать{}, // Электроны взаимодействуют с фотонами rus_verbs:вздорить{}, // Эта женщина часто вздорила с соседями rus_verbs:сойтись{}, // Мальчик сошелся с бандой хулиганов rus_verbs:вобрать{}, // вобрать в себя лучшие методы борьбы с вредителями rus_verbs:водиться{}, // Няня водится с детьми rus_verbs:воевать{}, // Фермеры воевали с волками rus_verbs:возиться{}, // Няня возится с детьми rus_verbs:ворковать{}, // Голубь воркует с голубкой rus_verbs:воссоединиться{}, // Дети воссоединились с семьей rus_verbs:воссоединяться{}, // Дети воссоединяются с семьей rus_verbs:вошкаться{}, // Не вошкайся с этой ерундой rus_verbs:враждовать{}, // враждовать с соседями rus_verbs:временить{}, // временить с выходом на пенсию rus_verbs:расстаться{}, // я не могу расстаться с тобой rus_verbs:выдирать{}, // выдирать с мясом rus_verbs:выдираться{}, // выдираться с мясом rus_verbs:вытворить{}, // вытворить что-либо с чем-либо rus_verbs:вытворять{}, // вытворять что-либо с чем-либо rus_verbs:сделать{}, // сделать с чем-то rus_verbs:домыть{}, // домыть с мылом rus_verbs:случиться{}, // случиться с кем-то rus_verbs:остаться{}, // остаться с кем-то rus_verbs:случать{}, // случать с породистым кобельком rus_verbs:послать{}, // послать с весточкой rus_verbs:работать{}, // работать с роботами rus_verbs:провести{}, // провести с девчонками время rus_verbs:заговорить{}, // заговорить с незнакомкой rus_verbs:прошептать{}, // прошептать с придыханием rus_verbs:читать{}, // читать с выражением rus_verbs:слушать{}, // слушать с повышенным вниманием rus_verbs:принести{}, // принести с собой rus_verbs:спать{}, // спать с женщинами rus_verbs:закончить{}, // закончить с приготовлениями rus_verbs:помочь{}, // помочь с перестановкой rus_verbs:уехать{}, // уехать с семьей rus_verbs:случаться{}, // случаться с кем-то rus_verbs:кутить{}, // кутить с проститутками rus_verbs:разговаривать{}, // разговаривать с ребенком rus_verbs:погодить{}, // погодить с ликвидацией rus_verbs:считаться{}, // считаться с чужим мнением rus_verbs:носить{}, // носить с собой rus_verbs:хорошеть{}, // хорошеть с каждым днем rus_verbs:приводить{}, // приводить с собой rus_verbs:прыгнуть{}, // прыгнуть с парашютом rus_verbs:петь{}, // петь с чувством rus_verbs:сложить{}, // сложить с результатом rus_verbs:познакомиться{}, // познакомиться с другими студентами rus_verbs:обращаться{}, // обращаться с животными rus_verbs:съесть{}, // съесть с хлебом rus_verbs:ошибаться{}, // ошибаться с дозировкой rus_verbs:столкнуться{}, // столкнуться с медведем rus_verbs:справиться{}, // справиться с нуждой rus_verbs:торопиться{}, // торопиться с ответом rus_verbs:поздравлять{}, // поздравлять с победой rus_verbs:объясняться{}, // объясняться с начальством rus_verbs:пошутить{}, // пошутить с подругой rus_verbs:поздороваться{}, // поздороваться с коллегами rus_verbs:поступать{}, // Как поступать с таким поведением? rus_verbs:определяться{}, // определяться с кандидатами rus_verbs:связаться{}, // связаться с поставщиком rus_verbs:спорить{}, // спорить с собеседником rus_verbs:разобраться{}, // разобраться с делами rus_verbs:ловить{}, // ловить с удочкой rus_verbs:помедлить{}, // Кандидат помедлил с ответом на заданный вопрос rus_verbs:шутить{}, // шутить с диким зверем rus_verbs:разорвать{}, // разорвать с поставщиком контракт rus_verbs:увезти{}, // увезти с собой rus_verbs:унести{}, // унести с собой rus_verbs:сотворить{}, // сотворить с собой что-то нехорошее rus_verbs:складываться{}, // складываться с первым импульсом rus_verbs:соглашаться{}, // соглашаться с предложенным договором //rus_verbs:покончить{}, // покончить с развратом rus_verbs:прихватить{}, // прихватить с собой rus_verbs:похоронить{}, // похоронить с почестями rus_verbs:связывать{}, // связывать с компанией свою судьбу rus_verbs:совпадать{}, // совпадать с предсказанием rus_verbs:танцевать{}, // танцевать с девушками rus_verbs:поделиться{}, // поделиться с выжившими rus_verbs:оставаться{}, // я не хотел оставаться с ним в одной комнате. rus_verbs:беседовать{}, // преподаватель, беседующий со студентами rus_verbs:бороться{}, // человек, борющийся со смертельной болезнью rus_verbs:шептаться{}, // девочка, шепчущаяся с подругой rus_verbs:сплетничать{}, // женщина, сплетничавшая с товарками rus_verbs:поговорить{}, // поговорить с виновниками rus_verbs:сказать{}, // сказать с трудом rus_verbs:произнести{}, // произнести с трудом rus_verbs:говорить{}, // говорить с акцентом rus_verbs:произносить{}, // произносить с трудом rus_verbs:встречаться{}, // кто с Антонио встречался? rus_verbs:посидеть{}, // посидеть с друзьями rus_verbs:расквитаться{}, // расквитаться с обидчиком rus_verbs:поквитаться{}, // поквитаться с обидчиком rus_verbs:ругаться{}, // ругаться с женой rus_verbs:поскандалить{}, // поскандалить с женой rus_verbs:потанцевать{}, // потанцевать с подругой rus_verbs:скандалить{}, // скандалить с соседями rus_verbs:разругаться{}, // разругаться с другом rus_verbs:болтать{}, // болтать с подругами rus_verbs:потрепаться{}, // потрепаться с соседкой rus_verbs:войти{}, // войти с регистрацией rus_verbs:входить{}, // входить с регистрацией rus_verbs:возвращаться{}, // возвращаться с триумфом rus_verbs:опоздать{}, // Он опоздал с подачей сочинения. rus_verbs:молчать{}, // Он молчал с ледяным спокойствием. rus_verbs:сражаться{}, // Он героически сражался с врагами. rus_verbs:выходить{}, // Он всегда выходит с зонтиком. rus_verbs:сличать{}, // сличать перевод с оригиналом rus_verbs:начать{}, // я начал с товарищем спор о религии rus_verbs:согласовать{}, // Маша согласовала с Петей дальнейшие поездки rus_verbs:приходить{}, // Приходите с нею. rus_verbs:жить{}, // кто с тобой жил? rus_verbs:расходиться{}, // Маша расходится с Петей rus_verbs:сцеплять{}, // сцеплять карабин с обвязкой rus_verbs:торговать{}, // мы торгуем с ними нефтью rus_verbs:уединяться{}, // уединяться с подругой в доме rus_verbs:уладить{}, // уладить конфликт с соседями rus_verbs:идти{}, // Я шел туда с тяжёлым сердцем. rus_verbs:разделять{}, // Я разделяю с вами горе и радость. rus_verbs:обратиться{}, // Я обратился к нему с просьбой о помощи. rus_verbs:захватить{}, // Я не захватил с собой денег. прилагательное:знакомый{}, // Я знаком с ними обоими. rus_verbs:вести{}, // Я веду с ней переписку. прилагательное:сопряженный{}, // Это сопряжено с большими трудностями. прилагательное:связанный{причастие}, // Это дело связано с риском. rus_verbs:поехать{}, // Хотите поехать со мной в театр? rus_verbs:проснуться{}, // Утром я проснулся с ясной головой. rus_verbs:лететь{}, // Самолёт летел со скоростью звука. rus_verbs:играть{}, // С огнём играть опасно! rus_verbs:поделать{}, // С ним ничего не поделаешь. rus_verbs:стрястись{}, // С ней стряслось несчастье. rus_verbs:смотреться{}, // Пьеса смотрится с удовольствием. rus_verbs:смотреть{}, // Она смотрела на меня с явным неудовольствием. rus_verbs:разойтись{}, // Она разошлась с мужем. rus_verbs:пристать{}, // Она пристала ко мне с расспросами. rus_verbs:посмотреть{}, // Она посмотрела на меня с удивлением. rus_verbs:поступить{}, // Она плохо поступила с ним. rus_verbs:выйти{}, // Она вышла с усталым и недовольным видом. rus_verbs:взять{}, // Возьмите с собой только самое необходимое. rus_verbs:наплакаться{}, // Наплачется она с ним. rus_verbs:лежать{}, // Он лежит с воспалением лёгких. rus_verbs:дышать{}, // дышащий с трудом rus_verbs:брать{}, // брать с собой rus_verbs:мчаться{}, // Автомобиль мчится с необычайной быстротой. rus_verbs:упасть{}, // Ваза упала со звоном. rus_verbs:вернуться{}, // мы вернулись вчера домой с полным лукошком rus_verbs:сидеть{}, // Она сидит дома с ребенком rus_verbs:встретиться{}, // встречаться с кем-либо ГЛ_ИНФ(придти), прилагательное:пришедший{}, // пришедший с другом ГЛ_ИНФ(постирать), прилагательное:постиранный{}, деепричастие:постирав{}, rus_verbs:мыть{} } fact гл_предл { if context { Гл_С_Твор предлог:с{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { Гл_С_Твор предлог:с{} *:*{падеж:твор} } then return true } #endregion ТВОРИТЕЛЬНЫЙ #region РОДИТЕЛЬНЫЙ wordentry_set Гл_С_Род= { rus_verbs:УХОДИТЬ{}, // Но с базы не уходить. rus_verbs:РВАНУТЬ{}, // Водитель прорычал проклятие и рванул машину с места. (РВАНУТЬ) rus_verbs:ОХВАТИТЬ{}, // огонь охватил его со всех сторон (ОХВАТИТЬ) rus_verbs:ЗАМЕТИТЬ{}, // Он понимал, что свет из тайника невозможно заметить с палубы (ЗАМЕТИТЬ/РАЗГЛЯДЕТЬ) rus_verbs:РАЗГЛЯДЕТЬ{}, // rus_verbs:СПЛАНИРОВАТЬ{}, // Птицы размером с орлицу, вероятно, не могли бы подняться в воздух, не спланировав с высокого утеса. (СПЛАНИРОВАТЬ) rus_verbs:УМЕРЕТЬ{}, // Он умрет с голоду. (УМЕРЕТЬ) rus_verbs:ВСПУГНУТЬ{}, // Оба упали с лязгом, вспугнувшим птиц с ближайших деревьев (ВСПУГНУТЬ) rus_verbs:РЕВЕТЬ{}, // Время от времени какой-то ящер ревел с берега или самой реки. (РЕВЕТЬ/ЗАРЕВЕТЬ/ПРОРЕВЕТЬ/ЗАОРАТЬ/ПРООРАТЬ/ОРАТЬ/ПРОКРИЧАТЬ/ЗАКРИЧАТЬ/ВОПИТЬ/ЗАВОПИТЬ) rus_verbs:ЗАРЕВЕТЬ{}, // rus_verbs:ПРОРЕВЕТЬ{}, // rus_verbs:ЗАОРАТЬ{}, // rus_verbs:ПРООРАТЬ{}, // rus_verbs:ОРАТЬ{}, // rus_verbs:ЗАКРИЧАТЬ{}, rus_verbs:ВОПИТЬ{}, // rus_verbs:ЗАВОПИТЬ{}, // rus_verbs:СТАЩИТЬ{}, // Я видела как они стащили его с валуна и увели с собой. (СТАЩИТЬ/СТАСКИВАТЬ) rus_verbs:СТАСКИВАТЬ{}, // rus_verbs:ПРОВЫТЬ{}, // Призрак трубного зова провыл с другой стороны дверей. (ПРОВЫТЬ, ЗАВЫТЬ, ВЫТЬ) rus_verbs:ЗАВЫТЬ{}, // rus_verbs:ВЫТЬ{}, // rus_verbs:СВЕТИТЬ{}, // Полуденное майское солнце ярко светило с голубых небес Аризоны. (СВЕТИТЬ) rus_verbs:ОТСВЕЧИВАТЬ{}, // Солнце отсвечивало с белых лошадей, белых щитов и белых перьев и искрилось на наконечниках пик. (ОТСВЕЧИВАТЬ С, ИСКРИТЬСЯ НА) rus_verbs:перегнать{}, // Скот нужно перегнать с этого пастбища на другое rus_verbs:собирать{}, // мальчики начали собирать со столов посуду rus_verbs:разглядывать{}, // ты ее со всех сторон разглядывал rus_verbs:СЖИМАТЬ{}, // меня плотно сжимали со всех сторон (СЖИМАТЬ) rus_verbs:СОБРАТЬСЯ{}, // со всего света собрались! (СОБРАТЬСЯ) rus_verbs:ИЗГОНЯТЬ{}, // Вино в пакетах изгоняют с рынка (ИЗГОНЯТЬ) rus_verbs:ВЛЮБИТЬСЯ{}, // влюбился в нее с первого взгляда (ВЛЮБИТЬСЯ) rus_verbs:РАЗДАВАТЬСЯ{}, // теперь крик раздавался со всех сторон (РАЗДАВАТЬСЯ) rus_verbs:ПОСМОТРЕТЬ{}, // Посмотрите на это с моей точки зрения (ПОСМОТРЕТЬ С род) rus_verbs:СХОДИТЬ{}, // принимать участие во всех этих событиях - значит продолжать сходить с ума (СХОДИТЬ С род) rus_verbs:РУХНУТЬ{}, // В Башкирии микроавтобус рухнул с моста (РУХНУТЬ С) rus_verbs:УВОЛИТЬ{}, // рекомендовать уволить их с работы (УВОЛИТЬ С) rus_verbs:КУПИТЬ{}, // еда , купленная с рук (КУПИТЬ С род) rus_verbs:УБРАТЬ{}, // помочь убрать со стола? (УБРАТЬ С) rus_verbs:ТЯНУТЬ{}, // с моря тянуло ветром (ТЯНУТЬ С) rus_verbs:ПРИХОДИТЬ{}, // приходит с работы муж (ПРИХОДИТЬ С) rus_verbs:ПРОПАСТЬ{}, // изображение пропало с экрана (ПРОПАСТЬ С) rus_verbs:ПОТЯНУТЬ{}, // с балкона потянуло холодом (ПОТЯНУТЬ С род) rus_verbs:РАЗДАТЬСЯ{}, // с палубы раздался свист (РАЗДАТЬСЯ С род) rus_verbs:ЗАЙТИ{}, // зашел с другой стороны (ЗАЙТИ С род) rus_verbs:НАЧАТЬ{}, // давай начнем с этого (НАЧАТЬ С род) rus_verbs:УВЕСТИ{}, // дала увести с развалин (УВЕСТИ С род) rus_verbs:ОПУСКАТЬСЯ{}, // с гор опускалась ночь (ОПУСКАТЬСЯ С) rus_verbs:ВСКОЧИТЬ{}, // Тристан вскочил с места (ВСКОЧИТЬ С род) rus_verbs:БРАТЬ{}, // беру с него пример (БРАТЬ С род) rus_verbs:ПРИПОДНЯТЬСЯ{}, // голова приподнялась с плеча (ПРИПОДНЯТЬСЯ С род) rus_verbs:ПОЯВИТЬСЯ{}, // всадники появились с востока (ПОЯВИТЬСЯ С род) rus_verbs:НАЛЕТЕТЬ{}, // с моря налетел ветер (НАЛЕТЕТЬ С род) rus_verbs:ВЗВИТЬСЯ{}, // Натан взвился с места (ВЗВИТЬСЯ С род) rus_verbs:ПОДОБРАТЬ{}, // подобрал с земли копье (ПОДОБРАТЬ С) rus_verbs:ДЕРНУТЬСЯ{}, // Кирилл дернулся с места (ДЕРНУТЬСЯ С род) rus_verbs:ВОЗВРАЩАТЬСЯ{}, // они возвращались с реки (ВОЗВРАЩАТЬСЯ С род) rus_verbs:ПЛЫТЬ{}, // плыли они с запада (ПЛЫТЬ С род) rus_verbs:ЗНАТЬ{}, // одно знали с древности (ЗНАТЬ С) rus_verbs:НАКЛОНИТЬСЯ{}, // всадник наклонился с лошади (НАКЛОНИТЬСЯ С) rus_verbs:НАЧАТЬСЯ{}, // началось все со скуки (НАЧАТЬСЯ С) прилагательное:ИЗВЕСТНЫЙ{}, // Культура его известна со времен глубокой древности (ИЗВЕСТНЫЙ С) rus_verbs:СБИТЬ{}, // Порыв ветра сбил Ваньку с ног (ts СБИТЬ С) rus_verbs:СОБИРАТЬСЯ{}, // они собираются сюда со всей равнины. (СОБИРАТЬСЯ С род) rus_verbs:смыть{}, // Дождь должен смыть с листьев всю пыль. (СМЫТЬ С) rus_verbs:привстать{}, // Мартин привстал со своего стула. (привстать с) rus_verbs:спасть{}, // тяжесть спала с души. (спасть с) rus_verbs:выглядеть{}, // так оно со стороны выглядело. (ВЫГЛЯДЕТЬ С) rus_verbs:повернуть{}, // к вечеру они повернули с нее направо. (ПОВЕРНУТЬ С) rus_verbs:ТЯНУТЬСЯ{}, // со стороны реки ко мне тянулись языки тумана. (ТЯНУТЬСЯ С) rus_verbs:ВОЕВАТЬ{}, // Генерал воевал с юных лет. (ВОЕВАТЬ С чего-то) rus_verbs:БОЛЕТЬ{}, // Голова болит с похмелья. (БОЛЕТЬ С) rus_verbs:приближаться{}, // со стороны острова приближалась лодка. rus_verbs:ПОТЯНУТЬСЯ{}, // со всех сторон к нему потянулись руки. (ПОТЯНУТЬСЯ С) rus_verbs:пойти{}, // низкий гул пошел со стороны долины. (пошел с) rus_verbs:зашевелиться{}, // со всех сторон зашевелились кусты. (зашевелиться с) rus_verbs:МЧАТЬСЯ{}, // со стороны леса мчались всадники. (МЧАТЬСЯ С) rus_verbs:БЕЖАТЬ{}, // люди бежали со всех ног. (БЕЖАТЬ С) rus_verbs:СЛЫШАТЬСЯ{}, // шум слышался со стороны моря. (СЛЫШАТЬСЯ С) rus_verbs:ЛЕТЕТЬ{}, // со стороны деревни летела птица. (ЛЕТЕТЬ С) rus_verbs:ПЕРЕТЬ{}, // враги прут со всех сторон. (ПЕРЕТЬ С) rus_verbs:ПОСЫПАТЬСЯ{}, // вопросы посыпались со всех сторон. (ПОСЫПАТЬСЯ С) rus_verbs:ИДТИ{}, // угроза шла со стороны моря. (ИДТИ С + род.п.) rus_verbs:ПОСЛЫШАТЬСЯ{}, // со стен послышались крики ужаса. (ПОСЛЫШАТЬСЯ С) rus_verbs:ОБРУШИТЬСЯ{}, // звуки обрушились со всех сторон. (ОБРУШИТЬСЯ С) rus_verbs:УДАРИТЬ{}, // голоса ударили со всех сторон. (УДАРИТЬ С) rus_verbs:ПОКАЗАТЬСЯ{}, // со стороны деревни показались земляне. (ПОКАЗАТЬСЯ С) rus_verbs:прыгать{}, // придется прыгать со второго этажа. (прыгать с) rus_verbs:СТОЯТЬ{}, // со всех сторон стоял лес. (СТОЯТЬ С) rus_verbs:доноситься{}, // шум со двора доносился чудовищный. (доноситься с) rus_verbs:мешать{}, // мешать воду с мукой (мешать с) rus_verbs:вестись{}, // Переговоры ведутся с позиции силы. (вестись с) rus_verbs:вставать{}, // Он не встает с кровати. (вставать с) rus_verbs:окружать{}, // зеленые щупальца окружали ее со всех сторон. (окружать с) rus_verbs:причитаться{}, // С вас причитается 50 рублей. rus_verbs:соскользнуть{}, // его острый клюв соскользнул с ее руки. rus_verbs:сократить{}, // Его сократили со службы. rus_verbs:поднять{}, // рука подняла с пола rus_verbs:поднимать{}, rus_verbs:тащить{}, // тем временем другие пришельцы тащили со всех сторон камни. rus_verbs:полететь{}, // Мальчик полетел с лестницы. rus_verbs:литься{}, // вода льется с неба rus_verbs:натечь{}, // натечь с сапог rus_verbs:спрыгивать{}, // спрыгивать с движущегося трамвая rus_verbs:съезжать{}, // съезжать с заявленной темы rus_verbs:покатываться{}, // покатываться со смеху rus_verbs:перескакивать{}, // перескакивать с одного примера на другой rus_verbs:сдирать{}, // сдирать с тела кожу rus_verbs:соскальзывать{}, // соскальзывать с крючка rus_verbs:сметать{}, // сметать с прилавков rus_verbs:кувыркнуться{}, // кувыркнуться со ступеньки rus_verbs:прокаркать{}, // прокаркать с ветки rus_verbs:стряхивать{}, // стряхивать с одежды rus_verbs:сваливаться{}, // сваливаться с лестницы rus_verbs:слизнуть{}, // слизнуть с лица rus_verbs:доставляться{}, // доставляться с фермы rus_verbs:обступать{}, // обступать с двух сторон rus_verbs:повскакивать{}, // повскакивать с мест rus_verbs:обозревать{}, // обозревать с вершины rus_verbs:слинять{}, // слинять с урока rus_verbs:смывать{}, // смывать с лица rus_verbs:спихнуть{}, // спихнуть со стола rus_verbs:обозреть{}, // обозреть с вершины rus_verbs:накупить{}, // накупить с рук rus_verbs:схлынуть{}, // схлынуть с берега rus_verbs:спикировать{}, // спикировать с километровой высоты rus_verbs:уползти{}, // уползти с поля боя rus_verbs:сбиваться{}, // сбиваться с пути rus_verbs:отлучиться{}, // отлучиться с поста rus_verbs:сигануть{}, // сигануть с крыши rus_verbs:сместить{}, // сместить с поста rus_verbs:списать{}, // списать с оригинального устройства инфинитив:слетать{ вид:несоверш }, глагол:слетать{ вид:несоверш }, // слетать с трассы деепричастие:слетая{}, rus_verbs:напиваться{}, // напиваться с горя rus_verbs:свесить{}, // свесить с крыши rus_verbs:заполучить{}, // заполучить со склада rus_verbs:спадать{}, // спадать с глаз rus_verbs:стартовать{}, // стартовать с мыса rus_verbs:спереть{}, // спереть со склада rus_verbs:согнать{}, // согнать с живота rus_verbs:скатываться{}, // скатываться со стога rus_verbs:сняться{}, // сняться с выборов rus_verbs:слезать{}, // слезать со стола rus_verbs:деваться{}, // деваться с подводной лодки rus_verbs:огласить{}, // огласить с трибуны rus_verbs:красть{}, // красть со склада rus_verbs:расширить{}, // расширить с торца rus_verbs:угадывать{}, // угадывать с полуслова rus_verbs:оскорбить{}, // оскорбить со сцены rus_verbs:срывать{}, // срывать с головы rus_verbs:сшибить{}, // сшибить с коня rus_verbs:сбивать{}, // сбивать с одежды rus_verbs:содрать{}, // содрать с посетителей rus_verbs:столкнуть{}, // столкнуть с горы rus_verbs:отряхнуть{}, // отряхнуть с одежды rus_verbs:сбрасывать{}, // сбрасывать с борта rus_verbs:расстреливать{}, // расстреливать с борта вертолета rus_verbs:придти{}, // мать скоро придет с работы rus_verbs:съехать{}, // Миша съехал с горки rus_verbs:свисать{}, // свисать с веток rus_verbs:стянуть{}, // стянуть с кровати rus_verbs:скинуть{}, // скинуть снег с плеча rus_verbs:загреметь{}, // загреметь со стула rus_verbs:сыпаться{}, // сыпаться с неба rus_verbs:стряхнуть{}, // стряхнуть с головы rus_verbs:сползти{}, // сползти со стула rus_verbs:стереть{}, // стереть с экрана rus_verbs:прогнать{}, // прогнать с фермы rus_verbs:смахнуть{}, // смахнуть со стола rus_verbs:спускать{}, // спускать с поводка rus_verbs:деться{}, // деться с подводной лодки rus_verbs:сдернуть{}, // сдернуть с себя rus_verbs:сдвинуться{}, // сдвинуться с места rus_verbs:слететь{}, // слететь с катушек rus_verbs:обступить{}, // обступить со всех сторон rus_verbs:снести{}, // снести с плеч инфинитив:сбегать{ вид:несоверш }, глагол:сбегать{ вид:несоверш }, // сбегать с уроков деепричастие:сбегая{}, прилагательное:сбегающий{}, // прилагательное:сбегавший{ вид:несоверш }, rus_verbs:запить{}, // запить с горя rus_verbs:рубануть{}, // рубануть с плеча rus_verbs:чертыхнуться{}, // чертыхнуться с досады rus_verbs:срываться{}, // срываться с цепи rus_verbs:смыться{}, // смыться с уроков rus_verbs:похитить{}, // похитить со склада rus_verbs:смести{}, // смести со своего пути rus_verbs:отгружать{}, // отгружать со склада rus_verbs:отгрузить{}, // отгрузить со склада rus_verbs:бросаться{}, // Дети бросались в воду с моста rus_verbs:броситься{}, // самоубийца бросился с моста в воду rus_verbs:взимать{}, // Билетер взимает плату с каждого посетителя rus_verbs:взиматься{}, // Плата взимается с любого посетителя rus_verbs:взыскать{}, // Приставы взыскали долг с бедолаги rus_verbs:взыскивать{}, // Приставы взыскивают с бедолаги все долги rus_verbs:взыскиваться{}, // Долги взыскиваются с алиментщиков rus_verbs:вспархивать{}, // вспархивать с цветка rus_verbs:вспорхнуть{}, // вспорхнуть с ветки rus_verbs:выбросить{}, // выбросить что-то с балкона rus_verbs:выводить{}, // выводить с одежды пятна rus_verbs:снять{}, // снять с головы rus_verbs:начинать{}, // начинать с эскиза rus_verbs:двинуться{}, // двинуться с места rus_verbs:начинаться{}, // начинаться с гардероба rus_verbs:стечь{}, // стечь с крыши rus_verbs:слезть{}, // слезть с кучи rus_verbs:спуститься{}, // спуститься с крыши rus_verbs:сойти{}, // сойти с пьедестала rus_verbs:свернуть{}, // свернуть с пути rus_verbs:сорвать{}, // сорвать с цепи rus_verbs:сорваться{}, // сорваться с поводка rus_verbs:тронуться{}, // тронуться с места rus_verbs:угадать{}, // угадать с первой попытки rus_verbs:спустить{}, // спустить с лестницы rus_verbs:соскочить{}, // соскочить с крючка rus_verbs:сдвинуть{}, // сдвинуть с места rus_verbs:подниматься{}, // туман, поднимающийся с болота rus_verbs:подняться{}, // туман, поднявшийся с болота rus_verbs:валить{}, // Резкий порывистый ветер валит прохожих с ног. rus_verbs:свалить{}, // Резкий порывистый ветер свалит тебя с ног. rus_verbs:донестись{}, // С улицы донесся шум дождя. rus_verbs:опасть{}, // Опавшие с дерева листья. rus_verbs:махнуть{}, // Он махнул с берега в воду. rus_verbs:исчезнуть{}, // исчезнуть с экрана rus_verbs:свалиться{}, // свалиться со сцены rus_verbs:упасть{}, // упасть с дерева rus_verbs:вернуться{}, // Он ещё не вернулся с работы. rus_verbs:сдувать{}, // сдувать пух с одуванчиков rus_verbs:свергать{}, // свергать царя с трона rus_verbs:сбиться{}, // сбиться с пути rus_verbs:стирать{}, // стирать тряпкой надпись с доски rus_verbs:убирать{}, // убирать мусор c пола rus_verbs:удалять{}, // удалять игрока с поля rus_verbs:окружить{}, // Япония окружена со всех сторон морями. rus_verbs:снимать{}, // Я снимаю с себя всякую ответственность за его поведение. глагол:писаться{ aux stress="пис^аться" }, // Собственные имена пишутся с большой буквы. прилагательное:спокойный{}, // С этой стороны я спокоен. rus_verbs:спросить{}, // С тебя за всё спросят. rus_verbs:течь{}, // С него течёт пот. rus_verbs:дуть{}, // С моря дует ветер. rus_verbs:капать{}, // С его лица капали крупные капли пота. rus_verbs:опустить{}, // Она опустила ребёнка с рук на пол. rus_verbs:спрыгнуть{}, // Она легко спрыгнула с коня. rus_verbs:встать{}, // Все встали со стульев. rus_verbs:сбросить{}, // Войдя в комнату, он сбросил с себя пальто. rus_verbs:взять{}, // Возьми книгу с полки. rus_verbs:спускаться{}, // Мы спускались с горы. rus_verbs:уйти{}, // Он нашёл себе заместителя и ушёл со службы. rus_verbs:порхать{}, // Бабочка порхает с цветка на цветок. rus_verbs:отправляться{}, // Ваш поезд отправляется со второй платформы. rus_verbs:двигаться{}, // Он не двигался с места. rus_verbs:отходить{}, // мой поезд отходит с первого пути rus_verbs:попасть{}, // Майкл попал в кольцо с десятиметровой дистанции rus_verbs:падать{}, // снег падает с ветвей rus_verbs:скрыться{} // Ее водитель, бросив машину, скрылся с места происшествия. } fact гл_предл { if context { Гл_С_Род предлог:с{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { Гл_С_Род предлог:с{} *:*{падеж:род} } then return true } fact гл_предл { if context { Гл_С_Род предлог:с{} *:*{падеж:парт} } then return true } #endregion РОДИТЕЛЬНЫЙ fact гл_предл { if context { * предлог:с{} *:*{ падеж:твор } } then return false,-3 } fact гл_предл { if context { * предлог:с{} *:*{ падеж:род } } then return false,-4 } fact гл_предл { if context { * предлог:с{} * } then return false,-5 } #endregion Предлог_С /* #region Предлог_ПОД // -------------- ПРЕДЛОГ 'ПОД' ----------------------- fact гл_предл { if context { * предлог:под{} @regex("[a-z]+[0-9]*") } then return true } // ПОД+вин.п. не может присоединяться к существительным, поэтому // он присоединяется к любым глаголам. fact гл_предл { if context { * предлог:под{} *:*{ падеж:вин } } then return true } wordentry_set Гл_ПОД_твор= { rus_verbs:извиваться{}, // извивалась под его длинными усами rus_verbs:РАСПРОСТРАНЯТЬСЯ{}, // Под густым ковром травы и плотным сплетением корней (РАСПРОСТРАНЯТЬСЯ) rus_verbs:БРОСИТЬ{}, // чтобы ты его под деревом бросил? (БРОСИТЬ) rus_verbs:БИТЬСЯ{}, // под моей щекой сильно билось его сердце (БИТЬСЯ) rus_verbs:ОПУСТИТЬСЯ{}, // глаза его опустились под ее желтым взглядом (ОПУСТИТЬСЯ) rus_verbs:ВЗДЫМАТЬСЯ{}, // его грудь судорожно вздымалась под ее рукой (ВЗДЫМАТЬСЯ) rus_verbs:ПРОМЧАТЬСЯ{}, // Она промчалась под ними и исчезла за изгибом горы. (ПРОМЧАТЬСЯ) rus_verbs:всплыть{}, // Наконец он всплыл под нависавшей кормой, так и не отыскав того, что хотел. (всплыть) rus_verbs:КОНЧАТЬСЯ{}, // Он почти вертикально уходит в реку и кончается глубоко под водой. (КОНЧАТЬСЯ) rus_verbs:ПОЛЗТИ{}, // Там они ползли под спутанным терновником и сквозь переплетавшиеся кусты (ПОЛЗТИ) rus_verbs:ПРОХОДИТЬ{}, // Вольф проходил под гигантскими ветвями деревьев и мхов, свисавших с ветвей зелеными водопадами. (ПРОХОДИТЬ, ПРОПОЛЗТИ, ПРОПОЛЗАТЬ) rus_verbs:ПРОПОЛЗТИ{}, // rus_verbs:ПРОПОЛЗАТЬ{}, // rus_verbs:ИМЕТЬ{}, // Эти предположения не имеют под собой никакой почвы (ИМЕТЬ) rus_verbs:НОСИТЬ{}, // она носит под сердцем ребенка (НОСИТЬ) rus_verbs:ПАСТЬ{}, // Рим пал под натиском варваров (ПАСТЬ) rus_verbs:УТОНУТЬ{}, // Выступавшие старческие вены снова утонули под гладкой твердой плотью. (УТОНУТЬ) rus_verbs:ВАЛЯТЬСЯ{}, // Под его кривыми серыми ветвями и пестрыми коричнево-зелеными листьями валялись пустые ореховые скорлупки и сердцевины плодов. (ВАЛЯТЬСЯ) rus_verbs:вздрогнуть{}, // она вздрогнула под его взглядом rus_verbs:иметься{}, // у каждого под рукой имелся арбалет rus_verbs:ЖДАТЬ{}, // Сашка уже ждал под дождем (ЖДАТЬ) rus_verbs:НОЧЕВАТЬ{}, // мне приходилось ночевать под открытым небом (НОЧЕВАТЬ) rus_verbs:УЗНАТЬ{}, // вы должны узнать меня под этим именем (УЗНАТЬ) rus_verbs:ЗАДЕРЖИВАТЬСЯ{}, // мне нельзя задерживаться под землей! (ЗАДЕРЖИВАТЬСЯ) rus_verbs:ПОГИБНУТЬ{}, // под их копытами погибли целые армии! (ПОГИБНУТЬ) rus_verbs:РАЗДАВАТЬСЯ{}, // под ногами у меня раздавался сухой хруст (РАЗДАВАТЬСЯ) rus_verbs:КРУЖИТЬСЯ{}, // поверхность планеты кружилась у него под ногами (КРУЖИТЬСЯ) rus_verbs:ВИСЕТЬ{}, // под глазами у него висели тяжелые складки кожи (ВИСЕТЬ) rus_verbs:содрогнуться{}, // содрогнулся под ногами каменный пол (СОДРОГНУТЬСЯ) rus_verbs:СОБИРАТЬСЯ{}, // темнота уже собиралась под деревьями (СОБИРАТЬСЯ) rus_verbs:УПАСТЬ{}, // толстяк упал под градом ударов (УПАСТЬ) rus_verbs:ДВИНУТЬСЯ{}, // лодка двинулась под водой (ДВИНУТЬСЯ) rus_verbs:ЦАРИТЬ{}, // под его крышей царила холодная зима (ЦАРИТЬ) rus_verbs:ПРОВАЛИТЬСЯ{}, // под копытами его лошади провалился мост (ПРОВАЛИТЬСЯ ПОД твор) rus_verbs:ЗАДРОЖАТЬ{}, // земля задрожала под ногами (ЗАДРОЖАТЬ) rus_verbs:НАХМУРИТЬСЯ{}, // государь нахмурился под маской (НАХМУРИТЬСЯ) rus_verbs:РАБОТАТЬ{}, // работать под угрозой нельзя (РАБОТАТЬ) rus_verbs:ШЕВЕЛЬНУТЬСЯ{}, // под ногой шевельнулся камень (ШЕВЕЛЬНУТЬСЯ) rus_verbs:ВИДЕТЬ{}, // видел тебя под камнем. (ВИДЕТЬ) rus_verbs:ОСТАТЬСЯ{}, // второе осталось под водой (ОСТАТЬСЯ) rus_verbs:КИПЕТЬ{}, // вода кипела под копытами (КИПЕТЬ) rus_verbs:СИДЕТЬ{}, // может сидит под деревом (СИДЕТЬ) rus_verbs:МЕЛЬКНУТЬ{}, // под нами мелькнуло море (МЕЛЬКНУТЬ) rus_verbs:ПОСЛЫШАТЬСЯ{}, // под окном послышался шум (ПОСЛЫШАТЬСЯ) rus_verbs:ТЯНУТЬСЯ{}, // под нами тянулись облака (ТЯНУТЬСЯ) rus_verbs:ДРОЖАТЬ{}, // земля дрожала под ним (ДРОЖАТЬ) rus_verbs:ПРИЙТИСЬ{}, // хуже пришлось под землей (ПРИЙТИСЬ) rus_verbs:ГОРЕТЬ{}, // лампа горела под потолком (ГОРЕТЬ) rus_verbs:ПОЛОЖИТЬ{}, // положил под деревом плащ (ПОЛОЖИТЬ) rus_verbs:ЗАГОРЕТЬСЯ{}, // под деревьями загорелся костер (ЗАГОРЕТЬСЯ) rus_verbs:ПРОНОСИТЬСЯ{}, // под нами проносились крыши (ПРОНОСИТЬСЯ) rus_verbs:ПОТЯНУТЬСЯ{}, // под кораблем потянулись горы (ПОТЯНУТЬСЯ) rus_verbs:БЕЖАТЬ{}, // беги под серой стеной ночи (БЕЖАТЬ) rus_verbs:РАЗДАТЬСЯ{}, // под окном раздалось тяжелое дыхание (РАЗДАТЬСЯ) rus_verbs:ВСПЫХНУТЬ{}, // под потолком вспыхнула яркая лампа (ВСПЫХНУТЬ) rus_verbs:СМОТРЕТЬ{}, // просто смотрите под другим углом (СМОТРЕТЬ ПОД) rus_verbs:ДУТЬ{}, // теперь под деревьями дул ветерок (ДУТЬ) rus_verbs:СКРЫТЬСЯ{}, // оно быстро скрылось под водой (СКРЫТЬСЯ ПОД) rus_verbs:ЩЕЛКНУТЬ{}, // далеко под ними щелкнул выстрел (ЩЕЛКНУТЬ) rus_verbs:ТРЕЩАТЬ{}, // осколки стекла трещали под ногами (ТРЕЩАТЬ) rus_verbs:РАСПОЛАГАТЬСЯ{}, // под ними располагались разноцветные скамьи (РАСПОЛАГАТЬСЯ) rus_verbs:ВЫСТУПИТЬ{}, // под ногтями выступили капельки крови (ВЫСТУПИТЬ) rus_verbs:НАСТУПИТЬ{}, // под куполом базы наступила тишина (НАСТУПИТЬ) rus_verbs:ОСТАНОВИТЬСЯ{}, // повозка остановилась под самым окном (ОСТАНОВИТЬСЯ) rus_verbs:РАСТАЯТЬ{}, // магазин растаял под ночным дождем (РАСТАЯТЬ) rus_verbs:ДВИГАТЬСЯ{}, // под водой двигалось нечто огромное (ДВИГАТЬСЯ) rus_verbs:БЫТЬ{}, // под снегом могут быть трещины (БЫТЬ) rus_verbs:ЗИЯТЬ{}, // под ней зияла ужасная рана (ЗИЯТЬ) rus_verbs:ЗАЗВОНИТЬ{}, // под рукой водителя зазвонил телефон (ЗАЗВОНИТЬ) rus_verbs:ПОКАЗАТЬСЯ{}, // внезапно под ними показалась вода (ПОКАЗАТЬСЯ) rus_verbs:ЗАМЕРЕТЬ{}, // эхо замерло под высоким потолком (ЗАМЕРЕТЬ) rus_verbs:ПОЙТИ{}, // затем под кораблем пошла пустыня (ПОЙТИ) rus_verbs:ДЕЙСТВОВАТЬ{}, // боги всегда действуют под маской (ДЕЙСТВОВАТЬ) rus_verbs:БЛЕСТЕТЬ{}, // мокрый мех блестел под луной (БЛЕСТЕТЬ) rus_verbs:ЛЕТЕТЬ{}, // под ним летела серая земля (ЛЕТЕТЬ) rus_verbs:СОГНУТЬСЯ{}, // содрогнулся под ногами каменный пол (СОГНУТЬСЯ) rus_verbs:КИВНУТЬ{}, // четвертый слегка кивнул под капюшоном (КИВНУТЬ) rus_verbs:УМЕРЕТЬ{}, // колдун умер под грудой каменных глыб (УМЕРЕТЬ) rus_verbs:ОКАЗЫВАТЬСЯ{}, // внезапно под ногами оказывается знакомая тропинка (ОКАЗЫВАТЬСЯ) rus_verbs:ИСЧЕЗАТЬ{}, // серая лента дороги исчезала под воротами (ИСЧЕЗАТЬ) rus_verbs:СВЕРКНУТЬ{}, // голубые глаза сверкнули под густыми бровями (СВЕРКНУТЬ) rus_verbs:СИЯТЬ{}, // под ним сияла белая пелена облаков (СИЯТЬ) rus_verbs:ПРОНЕСТИСЬ{}, // тихий смех пронесся под куполом зала (ПРОНЕСТИСЬ) rus_verbs:СКОЛЬЗИТЬ{}, // обломки судна медленно скользили под ними (СКОЛЬЗИТЬ) rus_verbs:ВЗДУТЬСЯ{}, // под серой кожей вздулись шары мускулов (ВЗДУТЬСЯ) rus_verbs:ПРОЙТИ{}, // обломок отлично пройдет под колесами слева (ПРОЙТИ) rus_verbs:РАЗВЕВАТЬСЯ{}, // светлые волосы развевались под дыханием ветра (РАЗВЕВАТЬСЯ) rus_verbs:СВЕРКАТЬ{}, // глаза огнем сверкали под темными бровями (СВЕРКАТЬ) rus_verbs:КАЗАТЬСЯ{}, // деревянный док казался очень твердым под моими ногами (КАЗАТЬСЯ) rus_verbs:ПОСТАВИТЬ{}, // четвертый маг торопливо поставил под зеркалом широкую чашу (ПОСТАВИТЬ) rus_verbs:ОСТАВАТЬСЯ{}, // запасы остаются под давлением (ОСТАВАТЬСЯ ПОД) rus_verbs:ПЕТЬ{}, // просто мы под землей любим петь. (ПЕТЬ ПОД) rus_verbs:ПОЯВИТЬСЯ{}, // под их крыльями внезапно появился дым. (ПОЯВИТЬСЯ ПОД) rus_verbs:ОКАЗАТЬСЯ{}, // мы снова оказались под солнцем. (ОКАЗАТЬСЯ ПОД) rus_verbs:ПОДХОДИТЬ{}, // мы подходили под другим углом? (ПОДХОДИТЬ ПОД) rus_verbs:СКРЫВАТЬСЯ{}, // кто под ней скрывается? (СКРЫВАТЬСЯ ПОД) rus_verbs:ХЛЮПАТЬ{}, // под ногами Аллы хлюпала грязь (ХЛЮПАТЬ ПОД) rus_verbs:ШАГАТЬ{}, // их отряд весело шагал под дождем этой музыки. (ШАГАТЬ ПОД) rus_verbs:ТЕЧЬ{}, // под ее поверхностью медленно текла ярость. (ТЕЧЬ ПОД твор) rus_verbs:ОЧУТИТЬСЯ{}, // мы очутились под стенами замка. (ОЧУТИТЬСЯ ПОД) rus_verbs:ПОБЛЕСКИВАТЬ{}, // их латы поблескивали под солнцем. (ПОБЛЕСКИВАТЬ ПОД) rus_verbs:ДРАТЬСЯ{}, // под столами дрались за кости псы. (ДРАТЬСЯ ПОД) rus_verbs:КАЧНУТЬСЯ{}, // палуба качнулась у нас под ногами. (КАЧНУЛАСЬ ПОД) rus_verbs:ПРИСЕСТЬ{}, // конь даже присел под тяжелым телом. (ПРИСЕСТЬ ПОД) rus_verbs:ЖИТЬ{}, // они живут под землей. (ЖИТЬ ПОД) rus_verbs:ОБНАРУЖИТЬ{}, // вы можете обнаружить ее под водой? (ОБНАРУЖИТЬ ПОД) rus_verbs:ПЛЫТЬ{}, // Орёл плывёт под облаками. (ПЛЫТЬ ПОД) rus_verbs:ИСЧЕЗНУТЬ{}, // потом они исчезли под водой. (ИСЧЕЗНУТЬ ПОД) rus_verbs:держать{}, // оружие все держали под рукой. (держать ПОД) rus_verbs:ВСТРЕТИТЬСЯ{}, // они встретились под водой. (ВСТРЕТИТЬСЯ ПОД) rus_verbs:уснуть{}, // Миша уснет под одеялом rus_verbs:пошевелиться{}, // пошевелиться под одеялом rus_verbs:задохнуться{}, // задохнуться под слоем снега rus_verbs:потечь{}, // потечь под избыточным давлением rus_verbs:уцелеть{}, // уцелеть под завалами rus_verbs:мерцать{}, // мерцать под лучами софитов rus_verbs:поискать{}, // поискать под кроватью rus_verbs:гудеть{}, // гудеть под нагрузкой rus_verbs:посидеть{}, // посидеть под навесом rus_verbs:укрыться{}, // укрыться под навесом rus_verbs:утихнуть{}, // утихнуть под одеялом rus_verbs:заскрипеть{}, // заскрипеть под тяжестью rus_verbs:шелохнуться{}, // шелохнуться под одеялом инфинитив:срезать{ вид:несоверш }, глагол:срезать{ вид:несоверш }, // срезать под корень деепричастие:срезав{}, прилагательное:срезающий{ вид:несоверш }, инфинитив:срезать{ вид:соверш }, глагол:срезать{ вид:соверш }, деепричастие:срезая{}, прилагательное:срезавший{ вид:соверш }, rus_verbs:пониматься{}, // пониматься под успехом rus_verbs:подразумеваться{}, // подразумеваться под правильным решением rus_verbs:промокнуть{}, // промокнуть под проливным дождем rus_verbs:засосать{}, // засосать под ложечкой rus_verbs:подписаться{}, // подписаться под воззванием rus_verbs:укрываться{}, // укрываться под навесом rus_verbs:запыхтеть{}, // запыхтеть под одеялом rus_verbs:мокнуть{}, // мокнуть под лождем rus_verbs:сгибаться{}, // сгибаться под тяжестью снега rus_verbs:намокнуть{}, // намокнуть под дождем rus_verbs:подписываться{}, // подписываться под обращением rus_verbs:тарахтеть{}, // тарахтеть под окнами инфинитив:находиться{вид:несоверш}, глагол:находиться{вид:несоверш}, // Она уже несколько лет находится под наблюдением врача. деепричастие:находясь{}, прилагательное:находившийся{вид:несоверш}, прилагательное:находящийся{}, rus_verbs:лежать{}, // лежать под капельницей rus_verbs:вымокать{}, // вымокать под дождём rus_verbs:вымокнуть{}, // вымокнуть под дождём rus_verbs:проворчать{}, // проворчать под нос rus_verbs:хмыкнуть{}, // хмыкнуть под нос rus_verbs:отыскать{}, // отыскать под кроватью rus_verbs:дрогнуть{}, // дрогнуть под ударами rus_verbs:проявляться{}, // проявляться под нагрузкой rus_verbs:сдержать{}, // сдержать под контролем rus_verbs:ложиться{}, // ложиться под клиента rus_verbs:таять{}, // таять под весенним солнцем rus_verbs:покатиться{}, // покатиться под откос rus_verbs:лечь{}, // он лег под навесом rus_verbs:идти{}, // идти под дождем прилагательное:известный{}, // Он известен под этим именем. rus_verbs:стоять{}, // Ящик стоит под столом. rus_verbs:отступить{}, // Враг отступил под ударами наших войск. rus_verbs:царапаться{}, // Мышь царапается под полом. rus_verbs:спать{}, // заяц спокойно спал у себя под кустом rus_verbs:загорать{}, // мы загораем под солнцем ГЛ_ИНФ(мыть), // мыть руки под струёй воды ГЛ_ИНФ(закопать), ГЛ_ИНФ(спрятать), ГЛ_ИНФ(прятать), ГЛ_ИНФ(перепрятать) } fact гл_предл { if context { Гл_ПОД_твор предлог:под{} *:*{ падеж:твор } } then return true } // для глаголов вне списка - запрещаем. fact гл_предл { if context { * предлог:под{} *:*{ падеж:твор } } then return false,-10 } fact гл_предл { if context { * предлог:под{} *:*{} } then return false,-11 } #endregion Предлог_ПОД */ #region Предлог_ОБ // -------------- ПРЕДЛОГ 'ОБ' ----------------------- wordentry_set Гл_ОБ_предл= { rus_verbs:СВИДЕТЕЛЬСТВОВАТЬ{}, // Об их присутствии свидетельствовало лишь тусклое пурпурное пятно, проступавшее на камне. (СВИДЕТЕЛЬСТВОВАТЬ) rus_verbs:ЗАДУМАТЬСЯ{}, // Промышленные гиганты задумались об экологии (ЗАДУМАТЬСЯ) rus_verbs:СПРОСИТЬ{}, // Он спросил нескольких из пляжников об их кажущейся всеобщей юности. (СПРОСИТЬ) rus_verbs:спрашивать{}, // как ты можешь еще спрашивать у меня об этом? rus_verbs:забывать{}, // Мы не можем забывать об их участи. rus_verbs:ГАДАТЬ{}, // теперь об этом можно лишь гадать (ГАДАТЬ) rus_verbs:ПОВЕДАТЬ{}, // Градоначальник , выступая с обзором основных городских событий , поведал об этом депутатам (ПОВЕДАТЬ ОБ) rus_verbs:СООБЩИТЬ{}, // Иран сообщил МАГАТЭ об ускорении обогащения урана (СООБЩИТЬ) rus_verbs:ЗАЯВИТЬ{}, // Об их успешном окончании заявил генеральный директор (ЗАЯВИТЬ ОБ) rus_verbs:слышать{}, // даже они слышали об этом человеке. (СЛЫШАТЬ ОБ) rus_verbs:ДОЛОЖИТЬ{}, // вернувшиеся разведчики доложили об увиденном (ДОЛОЖИТЬ ОБ) rus_verbs:ПОГОВОРИТЬ{}, // давай поговорим об этом. (ПОГОВОРИТЬ ОБ) rus_verbs:ДОГАДАТЬСЯ{}, // об остальном нетрудно догадаться. (ДОГАДАТЬСЯ ОБ) rus_verbs:ПОЗАБОТИТЬСЯ{}, // обещал обо всем позаботиться. (ПОЗАБОТИТЬСЯ ОБ) rus_verbs:ПОЗАБЫТЬ{}, // Шура позабыл обо всем. (ПОЗАБЫТЬ ОБ) rus_verbs:вспоминать{}, // Впоследствии он не раз вспоминал об этом приключении. (вспоминать об) rus_verbs:сообщать{}, // Газета сообщает об открытии сессии парламента. (сообщать об) rus_verbs:просить{}, // мы просили об отсрочке платежей (просить ОБ) rus_verbs:ПЕТЬ{}, // эта же девушка пела обо всем совершенно открыто. (ПЕТЬ ОБ) rus_verbs:сказать{}, // ты скажешь об этом капитану? (сказать ОБ) rus_verbs:знать{}, // бы хотелось знать как можно больше об этом районе. rus_verbs:кричать{}, // Все газеты кричат об этом событии. rus_verbs:советоваться{}, // Она обо всём советуется с матерью. rus_verbs:говориться{}, // об остальном говорилось легко. rus_verbs:подумать{}, // нужно крепко обо всем подумать. rus_verbs:напомнить{}, // черный дым напомнил об опасности. rus_verbs:забыть{}, // забудь об этой роскоши. rus_verbs:думать{}, // приходится обо всем думать самой. rus_verbs:отрапортовать{}, // отрапортовать об успехах rus_verbs:информировать{}, // информировать об изменениях rus_verbs:оповестить{}, // оповестить об отказе rus_verbs:убиваться{}, // убиваться об стену rus_verbs:расшибить{}, // расшибить об стену rus_verbs:заговорить{}, // заговорить об оплате rus_verbs:отозваться{}, // Он отозвался об этой книге с большой похвалой. rus_verbs:попросить{}, // попросить об услуге rus_verbs:объявить{}, // объявить об отставке rus_verbs:предупредить{}, // предупредить об аварии rus_verbs:предупреждать{}, // предупреждать об опасности rus_verbs:твердить{}, // твердить об обязанностях rus_verbs:заявлять{}, // заявлять об экспериментальном подтверждении rus_verbs:рассуждать{}, // рассуждать об абстрактных идеях rus_verbs:говорить{}, // Не говорите об этом в присутствии третьих лиц. rus_verbs:читать{}, // он читал об этом в журнале rus_verbs:прочитать{}, // он читал об этом в учебнике rus_verbs:узнать{}, // он узнал об этом из фильмов rus_verbs:рассказать{}, // рассказать об экзаменах rus_verbs:рассказывать{}, rus_verbs:договориться{}, // договориться об оплате rus_verbs:договариваться{}, // договариваться об обмене rus_verbs:болтать{}, // Не болтай об этом! rus_verbs:проболтаться{}, // Не проболтайся об этом! rus_verbs:заботиться{}, // кто заботится об урегулировании rus_verbs:беспокоиться{}, // вы беспокоитесь об обороне rus_verbs:помнить{}, // всем советую об этом помнить rus_verbs:мечтать{} // Мечтать об успехе } fact гл_предл { if context { Гл_ОБ_предл предлог:об{} *:*{ падеж:предл } } then return true } fact гл_предл { if context { * предлог:о{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { * предлог:об{} @regex("[a-z]+[0-9]*") } then return true } // остальные глаголы не могут связываться fact гл_предл { if context { * предлог:об{} *:*{ падеж:предл } } then return false, -4 } wordentry_set Гл_ОБ_вин= { rus_verbs:СЛОМАТЬ{}, // потом об колено сломал (СЛОМАТЬ) rus_verbs:разбить{}, // ты разбил щеку об угол ящика. (РАЗБИТЬ ОБ) rus_verbs:опереться{}, // Он опёрся об стену. rus_verbs:опираться{}, rus_verbs:постучать{}, // постучал лбом об пол. rus_verbs:удариться{}, // бутылка глухо ударилась об землю. rus_verbs:убиваться{}, // убиваться об стену rus_verbs:расшибить{}, // расшибить об стену rus_verbs:царапаться{} // Днище лодки царапалось обо что-то. } fact гл_предл { if context { Гл_ОБ_вин предлог:об{} *:*{ падеж:вин } } then return true } fact гл_предл { if context { * предлог:об{} *:*{ падеж:вин } } then return false,-4 } fact гл_предл { if context { * предлог:об{} *:*{} } then return false,-5 } #endregion Предлог_ОБ #region Предлог_О // ------------------- С ПРЕДЛОГОМ 'О' ---------------------- wordentry_set Гл_О_Вин={ rus_verbs:шмякнуть{}, // Ей хотелось шмякнуть ими о стену. rus_verbs:болтать{}, // Болтали чаще всего о пустяках. rus_verbs:шваркнуть{}, // Она шваркнула трубкой о рычаг. rus_verbs:опираться{}, // Мать приподнялась, с трудом опираясь о стол. rus_verbs:бахнуться{}, // Бахнуться головой о стол. rus_verbs:ВЫТЕРЕТЬ{}, // Вытащи нож и вытри его о траву. (ВЫТЕРЕТЬ/ВЫТИРАТЬ) rus_verbs:ВЫТИРАТЬ{}, // rus_verbs:РАЗБИТЬСЯ{}, // Прибой накатился и с шумом разбился о белый песок. (РАЗБИТЬСЯ) rus_verbs:СТУКНУТЬ{}, // Сердце его глухо стукнуло о грудную кость (СТУКНУТЬ) rus_verbs:ЛЯЗГНУТЬ{}, // Он кинулся наземь, покатился, и копье лязгнуло о стену. (ЛЯЗГНУТЬ/ЛЯЗГАТЬ) rus_verbs:ЛЯЗГАТЬ{}, // rus_verbs:звенеть{}, // стрелы уже звенели о прутья клетки rus_verbs:ЩЕЛКНУТЬ{}, // камень щелкнул о скалу (ЩЕЛКНУТЬ) rus_verbs:БИТЬ{}, // волна бьет о берег (БИТЬ) rus_verbs:ЗАЗВЕНЕТЬ{}, // зазвенели мечи о щиты (ЗАЗВЕНЕТЬ) rus_verbs:колотиться{}, // сердце его колотилось о ребра rus_verbs:стучать{}, // глухо стучали о щиты рукояти мечей. rus_verbs:биться{}, // биться головой о стену? (биться о) rus_verbs:ударить{}, // вода ударила его о стену коридора. (ударила о) rus_verbs:разбиваться{}, // волны разбивались о скалу rus_verbs:разбивать{}, // Разбивает голову о прутья клетки. rus_verbs:облокотиться{}, // облокотиться о стену rus_verbs:точить{}, // точить о точильный камень rus_verbs:спотыкаться{}, // спотыкаться о спрятавшийся в траве пень rus_verbs:потереться{}, // потереться о дерево rus_verbs:ушибиться{}, // ушибиться о дерево rus_verbs:тереться{}, // тереться о ствол rus_verbs:шмякнуться{}, // шмякнуться о землю rus_verbs:убиваться{}, // убиваться об стену rus_verbs:расшибить{}, // расшибить об стену rus_verbs:тереть{}, // тереть о камень rus_verbs:потереть{}, // потереть о колено rus_verbs:удариться{}, // удариться о край rus_verbs:споткнуться{}, // споткнуться о камень rus_verbs:запнуться{}, // запнуться о камень rus_verbs:запинаться{}, // запинаться о камни rus_verbs:ударяться{}, // ударяться о бортик rus_verbs:стукнуться{}, // стукнуться о бортик rus_verbs:стукаться{}, // стукаться о бортик rus_verbs:опереться{}, // Он опёрся локтями о стол. rus_verbs:плескаться{} // Вода плещется о берег. } fact гл_предл { if context { Гл_О_Вин предлог:о{} *:*{ падеж:вин } } then return true } fact гл_предл { if context { * предлог:о{} *:*{ падеж:вин } } then return false,-5 } wordentry_set Гл_О_предл={ rus_verbs:КРИЧАТЬ{}, // она кричала о смерти! (КРИЧАТЬ) rus_verbs:РАССПРОСИТЬ{}, // Я расспросил о нем нескольких горожан. (РАССПРОСИТЬ/РАССПРАШИВАТЬ) rus_verbs:РАССПРАШИВАТЬ{}, // rus_verbs:слушать{}, // ты будешь слушать о них? rus_verbs:вспоминать{}, // вспоминать о том разговоре ему было неприятно rus_verbs:МОЛЧАТЬ{}, // О чём молчат девушки (МОЛЧАТЬ) rus_verbs:ПЛАКАТЬ{}, // она плакала о себе (ПЛАКАТЬ) rus_verbs:сложить{}, // о вас сложены легенды rus_verbs:ВОЛНОВАТЬСЯ{}, // Я волнуюсь о том, что что-то серьёзно пошло не так (ВОЛНОВАТЬСЯ О) rus_verbs:УПОМЯНУТЬ{}, // упомянул о намерении команды приобрести несколько новых футболистов (УПОМЯНУТЬ О) rus_verbs:ОТЧИТЫВАТЬСЯ{}, // Судебные приставы продолжают отчитываться о борьбе с неплательщиками (ОТЧИТЫВАТЬСЯ О) rus_verbs:ДОЛОЖИТЬ{}, // провести тщательное расследование взрыва в маршрутном такси во Владикавказе и доложить о результатах (ДОЛОЖИТЬ О) rus_verbs:ПРОБОЛТАТЬ{}, // правительство страны больше проболтало о военной реформе (ПРОБОЛТАТЬ О) rus_verbs:ЗАБОТИТЬСЯ{}, // Четверть россиян заботятся о здоровье путем просмотра телевизора (ЗАБОТИТЬСЯ О) rus_verbs:ИРОНИЗИРОВАТЬ{}, // Вы иронизируете о ностальгии по тем временем (ИРОНИЗИРОВАТЬ О) rus_verbs:СИГНАЛИЗИРОВАТЬ{}, // Кризис цен на продукты питания сигнализирует о неминуемой гиперинфляции (СИГНАЛИЗИРОВАТЬ О) rus_verbs:СПРОСИТЬ{}, // Он спросил о моём здоровье. (СПРОСИТЬ О) rus_verbs:НАПОМНИТЬ{}, // больной зуб опять напомнил о себе. (НАПОМНИТЬ О) rus_verbs:осведомиться{}, // офицер осведомился о цели визита rus_verbs:объявить{}, // В газете объявили о конкурсе. (объявить о) rus_verbs:ПРЕДСТОЯТЬ{}, // о чем предстоит разговор? (ПРЕДСТОЯТЬ О) rus_verbs:объявлять{}, // объявлять о всеобщей забастовке (объявлять о) rus_verbs:зайти{}, // Разговор зашёл о политике. rus_verbs:порассказать{}, // порассказать о своих путешествиях инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть о неразделенной любви деепричастие:спев{}, прилагательное:спевший{ вид:соверш }, прилагательное:спетый{}, rus_verbs:напеть{}, rus_verbs:разговаривать{}, // разговаривать с другом о жизни rus_verbs:рассуждать{}, // рассуждать об абстрактных идеях //rus_verbs:заботиться{}, // заботиться о престарелых родителях rus_verbs:раздумывать{}, // раздумывать о новой работе rus_verbs:договариваться{}, // договариваться о сумме компенсации rus_verbs:молить{}, // молить о пощаде rus_verbs:отзываться{}, // отзываться о книге rus_verbs:подумывать{}, // подумывать о новом подходе rus_verbs:поговаривать{}, // поговаривать о загадочном звере rus_verbs:обмолвиться{}, // обмолвиться о проклятии rus_verbs:условиться{}, // условиться о поддержке rus_verbs:призадуматься{}, // призадуматься о последствиях rus_verbs:известить{}, // известить о поступлении rus_verbs:отрапортовать{}, // отрапортовать об успехах rus_verbs:напевать{}, // напевать о любви rus_verbs:помышлять{}, // помышлять о новом деле rus_verbs:переговорить{}, // переговорить о правилах rus_verbs:повествовать{}, // повествовать о событиях rus_verbs:слыхивать{}, // слыхивать о чудище rus_verbs:потолковать{}, // потолковать о планах rus_verbs:проговориться{}, // проговориться о планах rus_verbs:умолчать{}, // умолчать о штрафах rus_verbs:хлопотать{}, // хлопотать о премии rus_verbs:уведомить{}, // уведомить о поступлении rus_verbs:горевать{}, // горевать о потере rus_verbs:запамятовать{}, // запамятовать о важном мероприятии rus_verbs:заикнуться{}, // заикнуться о прибавке rus_verbs:информировать{}, // информировать о событиях rus_verbs:проболтаться{}, // проболтаться о кладе rus_verbs:поразмыслить{}, // поразмыслить о судьбе rus_verbs:заикаться{}, // заикаться о деньгах rus_verbs:оповестить{}, // оповестить об отказе rus_verbs:печься{}, // печься о всеобщем благе rus_verbs:разглагольствовать{}, // разглагольствовать о правах rus_verbs:размечтаться{}, // размечтаться о будущем rus_verbs:лепетать{}, // лепетать о невиновности rus_verbs:грезить{}, // грезить о большой и чистой любви rus_verbs:залепетать{}, // залепетать о сокровищах rus_verbs:пронюхать{}, // пронюхать о бесплатной одежде rus_verbs:протрубить{}, // протрубить о победе rus_verbs:извещать{}, // извещать о поступлении rus_verbs:трубить{}, // трубить о поимке разбойников rus_verbs:осведомляться{}, // осведомляться о судьбе rus_verbs:поразмышлять{}, // поразмышлять о неизбежном rus_verbs:слагать{}, // слагать о подвигах викингов rus_verbs:ходатайствовать{}, // ходатайствовать о выделении материальной помощи rus_verbs:побеспокоиться{}, // побеспокоиться о правильном стимулировании rus_verbs:закидывать{}, // закидывать сообщениями об ошибках rus_verbs:базарить{}, // пацаны базарили о телках rus_verbs:балагурить{}, // мужики балагурили о новом председателе rus_verbs:балакать{}, // мужики балакали о новом председателе rus_verbs:беспокоиться{}, // Она беспокоится о детях rus_verbs:рассказать{}, // Кумир рассказал о криминале в Москве rus_verbs:возмечтать{}, // возмечтать о счастливом мире rus_verbs:вопить{}, // Кто-то вопил о несправедливости rus_verbs:сказать{}, // сказать что-то новое о ком-то rus_verbs:знать{}, // знать о ком-то что-то пикантное rus_verbs:подумать{}, // подумать о чём-то rus_verbs:думать{}, // думать о чём-то rus_verbs:узнать{}, // узнать о происшествии rus_verbs:помнить{}, // помнить о задании rus_verbs:просить{}, // просить о коде доступа rus_verbs:забыть{}, // забыть о своих обязанностях rus_verbs:сообщить{}, // сообщить о заложенной мине rus_verbs:заявить{}, // заявить о пропаже rus_verbs:задуматься{}, // задуматься о смерти rus_verbs:спрашивать{}, // спрашивать о поступлении товара rus_verbs:догадаться{}, // догадаться о причинах rus_verbs:договориться{}, // договориться о собеседовании rus_verbs:мечтать{}, // мечтать о сцене rus_verbs:поговорить{}, // поговорить о наболевшем rus_verbs:размышлять{}, // размышлять о насущном rus_verbs:напоминать{}, // напоминать о себе rus_verbs:пожалеть{}, // пожалеть о содеянном rus_verbs:ныть{}, // ныть о прибавке rus_verbs:сообщать{}, // сообщать о победе rus_verbs:догадываться{}, // догадываться о первопричине rus_verbs:поведать{}, // поведать о тайнах rus_verbs:умолять{}, // умолять о пощаде rus_verbs:сожалеть{}, // сожалеть о случившемся rus_verbs:жалеть{}, // жалеть о случившемся rus_verbs:забывать{}, // забывать о случившемся rus_verbs:упоминать{}, // упоминать о предках rus_verbs:позабыть{}, // позабыть о своем обещании rus_verbs:запеть{}, // запеть о любви rus_verbs:скорбеть{}, // скорбеть о усопшем rus_verbs:задумываться{}, // задумываться о смене работы rus_verbs:позаботиться{}, // позаботиться о престарелых родителях rus_verbs:докладывать{}, // докладывать о планах строительства целлюлозно-бумажного комбината rus_verbs:попросить{}, // попросить о замене rus_verbs:предупредить{}, // предупредить о замене rus_verbs:предупреждать{}, // предупреждать о замене rus_verbs:твердить{}, // твердить о замене rus_verbs:заявлять{}, // заявлять о подлоге rus_verbs:петь{}, // певица, поющая о лете rus_verbs:проинформировать{}, // проинформировать о переговорах rus_verbs:порассказывать{}, // порассказывать о событиях rus_verbs:послушать{}, // послушать о новинках rus_verbs:заговорить{}, // заговорить о плате rus_verbs:отозваться{}, // Он отозвался о книге с большой похвалой. rus_verbs:оставить{}, // Он оставил о себе печальную память. rus_verbs:свидетельствовать{}, // страшно исхудавшее тело свидетельствовало о долгих лишениях rus_verbs:спорить{}, // они спорили о законе глагол:написать{ aux stress="напис^ать" }, инфинитив:написать{ aux stress="напис^ать" }, // Он написал о том, что видел во время путешествия. глагол:писать{ aux stress="пис^ать" }, инфинитив:писать{ aux stress="пис^ать" }, // Он писал о том, что видел во время путешествия. rus_verbs:прочитать{}, // Я прочитал о тебе rus_verbs:услышать{}, // Я услышал о нем rus_verbs:помечтать{}, // Девочки помечтали о принце rus_verbs:слышать{}, // Мальчик слышал о приведениях rus_verbs:вспомнить{}, // Девочки вспомнили о завтраке rus_verbs:грустить{}, // Я грущу о тебе rus_verbs:осведомить{}, // о последних достижениях науки rus_verbs:рассказывать{}, // Антонио рассказывает о работе rus_verbs:говорить{}, // говорим о трех больших псах rus_verbs:идти{} // Вопрос идёт о войне. } fact гл_предл { if context { Гл_О_предл предлог:о{} *:*{ падеж:предл } } then return true } // Мы поделились впечатлениями о выставке. // ^^^^^^^^^^ ^^^^^^^^^^ fact гл_предл { if context { * предлог:о{} *:*{ падеж:предл } } then return false,-3 } fact гл_предл { if context { * предлог:о{} *:*{} } then return false,-5 } #endregion Предлог_О #region Предлог_ПО // ------------------- С ПРЕДЛОГОМ 'ПО' ---------------------- // для этих глаголов - запрещаем связывание с ПО+дат.п. wordentry_set Глаг_ПО_Дат_Запр= { rus_verbs:предпринять{}, // предпринять шаги по стимулированию продаж rus_verbs:увлечь{}, // увлечь в прогулку по парку rus_verbs:закончить{}, rus_verbs:мочь{}, rus_verbs:хотеть{} } fact гл_предл { if context { Глаг_ПО_Дат_Запр предлог:по{} *:*{ падеж:дат } } then return false,-10 } // По умолчанию разрешаем связывание в паттернах типа // Я иду по шоссе fact гл_предл { if context { * предлог:по{} *:*{ падеж:дат } } then return true } wordentry_set Глаг_ПО_Вин= { rus_verbs:ВОЙТИ{}, // лезвие вошло по рукоять (ВОЙТИ) rus_verbs:иметь{}, // все месяцы имели по тридцать дней. (ИМЕТЬ ПО) rus_verbs:материализоваться{}, // материализоваться по другую сторону барьера rus_verbs:засадить{}, // засадить по рукоятку rus_verbs:увязнуть{} // увязнуть по колено } fact гл_предл { if context { Глаг_ПО_Вин предлог:по{} *:*{ падеж:вин } } then return true } // для остальных падежей запрещаем. fact гл_предл { if context { * предлог:по{} *:*{ падеж:вин } } then return false,-5 } #endregion Предлог_ПО #region Предлог_К // ------------------- С ПРЕДЛОГОМ 'К' ---------------------- wordentry_set Гл_К_Дат={ rus_verbs:заявиться{}, // Сразу же после обеда к нам заявилась Юлия Михайловна. rus_verbs:приставлять{} , // Приставляет дуло пистолета к виску. прилагательное:НЕПРИГОДНЫЙ{}, // большинство компьютеров из этой партии оказались непригодными к эксплуатации (НЕПРИГОДНЫЙ) rus_verbs:СБЕГАТЬСЯ{}, // Они чуяли воду и сбегались к ней отовсюду. (СБЕГАТЬСЯ) rus_verbs:СБЕЖАТЬСЯ{}, // К бетонной скамье начали сбегаться люди. (СБЕГАТЬСЯ/СБЕЖАТЬСЯ) rus_verbs:ПРИТИРАТЬСЯ{}, // Менее стойких водителей буквально сметало на другую полосу, и они впритык притирались к другим машинам. (ПРИТИРАТЬСЯ) rus_verbs:РУХНУТЬ{}, // а потом ты без чувств рухнул к моим ногам (РУХНУТЬ) rus_verbs:ПЕРЕНЕСТИ{}, // Они перенесли мясо к ручью и поджарили его на костре. (ПЕРЕНЕСТИ) rus_verbs:ЗАВЕСТИ{}, // как путь мой завел меня к нему? (ЗАВЕСТИ) rus_verbs:НАГРЯНУТЬ{}, // ФБР нагрянуло с обыском к сестре бостонских террористов (НАГРЯНУТЬ) rus_verbs:ПРИСЛОНЯТЬСЯ{}, // Рабы ложились на пол, прислонялись к стене и спали. (ПРИСЛОНЯТЬСЯ,ПРИНОРАВЛИВАТЬСЯ,ПРИНОРОВИТЬСЯ) rus_verbs:ПРИНОРАВЛИВАТЬСЯ{}, // rus_verbs:ПРИНОРОВИТЬСЯ{}, // rus_verbs:СПЛАНИРОВАТЬ{}, // Вскоре она остановила свое падение и спланировала к ним. (СПЛАНИРОВАТЬ,СПИКИРОВАТЬ,РУХНУТЬ) rus_verbs:СПИКИРОВАТЬ{}, // rus_verbs:ЗАБРАТЬСЯ{}, // Поэтому он забрался ко мне в квартиру с имевшимся у него полумесяцем. (ЗАБРАТЬСЯ К, В, С) rus_verbs:ПРОТЯГИВАТЬ{}, // Оно протягивало свои длинные руки к молодому человеку, стоявшему на плоской вершине валуна. (ПРОТЯГИВАТЬ/ПРОТЯНУТЬ/ТЯНУТЬ) rus_verbs:ПРОТЯНУТЬ{}, // rus_verbs:ТЯНУТЬ{}, // rus_verbs:ПЕРЕБИРАТЬСЯ{}, // Ее губы медленно перебирались к его уху. (ПЕРЕБИРАТЬСЯ,ПЕРЕБРАТЬСЯ,ПЕРЕБАЗИРОВАТЬСЯ,ПЕРЕМЕСТИТЬСЯ,ПЕРЕМЕЩАТЬСЯ) rus_verbs:ПЕРЕБРАТЬСЯ{}, // ,,, rus_verbs:ПЕРЕБАЗИРОВАТЬСЯ{}, // rus_verbs:ПЕРЕМЕСТИТЬСЯ{}, // rus_verbs:ПЕРЕМЕЩАТЬСЯ{}, // rus_verbs:ТРОНУТЬСЯ{}, // Он отвернулся от нее и тронулся к пляжу. (ТРОНУТЬСЯ) rus_verbs:ПРИСТАВИТЬ{}, // Он поднял одну из них и приставил верхний конец к краю шахты в потолке. rus_verbs:ПРОБИТЬСЯ{}, // Отряд с невероятными приключениями, пытается пробиться к своему полку, попадает в плен и другие передряги (ПРОБИТЬСЯ) rus_verbs:хотеть{}, rus_verbs:СДЕЛАТЬ{}, // Сделайте всё к понедельнику (СДЕЛАТЬ) rus_verbs:ИСПЫТЫВАТЬ{}, // она испытывает ко мне только отвращение (ИСПЫТЫВАТЬ) rus_verbs:ОБЯЗЫВАТЬ{}, // Это меня ни к чему не обязывает (ОБЯЗЫВАТЬ) rus_verbs:КАРАБКАТЬСЯ{}, // карабкаться по горе от подножия к вершине (КАРАБКАТЬСЯ) rus_verbs:СТОЯТЬ{}, // мужчина стоял ко мне спиной (СТОЯТЬ) rus_verbs:ПОДАТЬСЯ{}, // наконец люк подался ко мне (ПОДАТЬСЯ) rus_verbs:ПРИРАВНЯТЬ{}, // Усилия нельзя приравнять к результату (ПРИРАВНЯТЬ) rus_verbs:ПРИРАВНИВАТЬ{}, // Усилия нельзя приравнивать к результату (ПРИРАВНИВАТЬ) rus_verbs:ВОЗЛОЖИТЬ{}, // Путин в Пскове возложил цветы к памятнику воинам-десантникам, погибшим в Чечне (ВОЗЛОЖИТЬ) rus_verbs:запустить{}, // Индия запустит к Марсу свой космический аппарат в 2013 г rus_verbs:ПРИСТЫКОВАТЬСЯ{}, // Роботизированный российский грузовой космический корабль пристыковался к МКС (ПРИСТЫКОВАТЬСЯ) rus_verbs:ПРИМАЗАТЬСЯ{}, // К челябинскому метеориту примазалась таинственная слизь (ПРИМАЗАТЬСЯ) rus_verbs:ПОПРОСИТЬ{}, // Попросите Лизу к телефону (ПОПРОСИТЬ К) rus_verbs:ПРОЕХАТЬ{}, // Порой школьные автобусы просто не имеют возможности проехать к некоторым населенным пунктам из-за бездорожья (ПРОЕХАТЬ К) rus_verbs:ПОДЦЕПЛЯТЬСЯ{}, // Вагоны с пассажирами подцепляются к составу (ПОДЦЕПЛЯТЬСЯ К) rus_verbs:ПРИЗВАТЬ{}, // Президент Афганистана призвал талибов к прямому диалогу (ПРИЗВАТЬ К) rus_verbs:ПРЕОБРАЗИТЬСЯ{}, // Культовый столичный отель преобразился к юбилею (ПРЕОБРАЗИТЬСЯ К) прилагательное:ЧУВСТВИТЕЛЬНЫЙ{}, // нейроны одного комплекса чувствительны к разным веществам (ЧУВСТВИТЕЛЬНЫЙ К) безлич_глагол:нужно{}, // нам нужно к воротам (НУЖНО К) rus_verbs:БРОСИТЬ{}, // огромный клюв бросил это мясо к моим ногам (БРОСИТЬ К) rus_verbs:ЗАКОНЧИТЬ{}, // к пяти утра техники закончили (ЗАКОНЧИТЬ К) rus_verbs:НЕСТИ{}, // к берегу нас несет! (НЕСТИ К) rus_verbs:ПРОДВИГАТЬСЯ{}, // племена медленно продвигались к востоку (ПРОДВИГАТЬСЯ К) rus_verbs:ОПУСКАТЬСЯ{}, // деревья опускались к самой воде (ОПУСКАТЬСЯ К) rus_verbs:СТЕМНЕТЬ{}, // к тому времени стемнело (СТЕМНЕЛО К) rus_verbs:ОТСКОЧИТЬ{}, // после отскочил к окну (ОТСКОЧИТЬ К) rus_verbs:ДЕРЖАТЬСЯ{}, // к солнцу держались спинами (ДЕРЖАТЬСЯ К) rus_verbs:КАЧНУТЬСЯ{}, // толпа качнулась к ступеням (КАЧНУТЬСЯ К) rus_verbs:ВОЙТИ{}, // Андрей вошел к себе (ВОЙТИ К) rus_verbs:ВЫБРАТЬСЯ{}, // мы выбрались к окну (ВЫБРАТЬСЯ К) rus_verbs:ПРОВЕСТИ{}, // провел к стене спальни (ПРОВЕСТИ К) rus_verbs:ВЕРНУТЬСЯ{}, // давай вернемся к делу (ВЕРНУТЬСЯ К) rus_verbs:ВОЗВРАТИТЬСЯ{}, // Среди евреев, живших в диаспоре, всегда было распространено сильное стремление возвратиться к Сиону (ВОЗВРАТИТЬСЯ К) rus_verbs:ПРИЛЕГАТЬ{}, // Задняя поверхность хрусталика прилегает к стекловидному телу (ПРИЛЕГАТЬ К) rus_verbs:ПЕРЕНЕСТИСЬ{}, // мысленно Алёна перенеслась к заливу (ПЕРЕНЕСТИСЬ К) rus_verbs:ПРОБИВАТЬСЯ{}, // сквозь болото к берегу пробивался ручей. (ПРОБИВАТЬСЯ К) rus_verbs:ПЕРЕВЕСТИ{}, // необходимо срочно перевести стадо к воде. (ПЕРЕВЕСТИ К) rus_verbs:ПРИЛЕТЕТЬ{}, // зачем ты прилетел к нам? (ПРИЛЕТЕТЬ К) rus_verbs:ДОБАВИТЬ{}, // добавить ли ее к остальным? (ДОБАВИТЬ К) rus_verbs:ПРИГОТОВИТЬ{}, // Матвей приготовил лук к бою. (ПРИГОТОВИТЬ К) rus_verbs:РВАНУТЬ{}, // человек рванул ее к себе. (РВАНУТЬ К) rus_verbs:ТАЩИТЬ{}, // они тащили меня к двери. (ТАЩИТЬ К) глагол:быть{}, // к тебе есть вопросы. прилагательное:равнодушный{}, // Он равнодушен к музыке. rus_verbs:ПОЖАЛОВАТЬ{}, // скандально известный певец пожаловал к нам на передачу (ПОЖАЛОВАТЬ К) rus_verbs:ПЕРЕСЕСТЬ{}, // Ольга пересела к Антону (ПЕРЕСЕСТЬ К) инфинитив:СБЕГАТЬ{ вид:соверш }, глагол:СБЕГАТЬ{ вид:соверш }, // сбегай к Борису (СБЕГАТЬ К) rus_verbs:ПЕРЕХОДИТЬ{}, // право хода переходит к Адаму (ПЕРЕХОДИТЬ К) rus_verbs:прижаться{}, // она прижалась щекой к его шее. (прижаться+к) rus_verbs:ПОДСКОЧИТЬ{}, // солдат быстро подскочил ко мне. (ПОДСКОЧИТЬ К) rus_verbs:ПРОБРАТЬСЯ{}, // нужно пробраться к реке. (ПРОБРАТЬСЯ К) rus_verbs:ГОТОВИТЬ{}, // нас готовили к этому. (ГОТОВИТЬ К) rus_verbs:ТЕЧЬ{}, // река текла к морю. (ТЕЧЬ К) rus_verbs:ОТШАТНУТЬСЯ{}, // епископ отшатнулся к стене. (ОТШАТНУТЬСЯ К) rus_verbs:БРАТЬ{}, // брали бы к себе. (БРАТЬ К) rus_verbs:СКОЛЬЗНУТЬ{}, // ковер скользнул к пещере. (СКОЛЬЗНУТЬ К) rus_verbs:присохнуть{}, // Грязь присохла к одежде. (присохнуть к) rus_verbs:просить{}, // Директор просит вас к себе. (просить к) rus_verbs:вызывать{}, // шеф вызывал к себе. (вызывать к) rus_verbs:присесть{}, // старик присел к огню. (присесть к) rus_verbs:НАКЛОНИТЬСЯ{}, // Ричард наклонился к брату. (НАКЛОНИТЬСЯ К) rus_verbs:выбираться{}, // будем выбираться к дороге. (выбираться к) rus_verbs:отвернуться{}, // Виктор отвернулся к стене. (отвернуться к) rus_verbs:СТИХНУТЬ{}, // огонь стих к полудню. (СТИХНУТЬ К) rus_verbs:УПАСТЬ{}, // нож упал к ногам. (УПАСТЬ К) rus_verbs:СЕСТЬ{}, // молча сел к огню. (СЕСТЬ К) rus_verbs:ХЛЫНУТЬ{}, // народ хлынул к стенам. (ХЛЫНУТЬ К) rus_verbs:покатиться{}, // они черной волной покатились ко мне. (покатиться к) rus_verbs:ОБРАТИТЬ{}, // она обратила к нему свое бледное лицо. (ОБРАТИТЬ К) rus_verbs:СКЛОНИТЬ{}, // Джон слегка склонил голову к плечу. (СКЛОНИТЬ К) rus_verbs:СВЕРНУТЬ{}, // дорожка резко свернула к южной стене. (СВЕРНУТЬ К) rus_verbs:ЗАВЕРНУТЬ{}, // Он завернул к нам по пути к месту службы. (ЗАВЕРНУТЬ К) rus_verbs:подходить{}, // цвет подходил ей к лицу. rus_verbs:БРЕСТИ{}, // Ричард покорно брел к отцу. (БРЕСТИ К) rus_verbs:ПОПАСТЬ{}, // хочешь попасть к нему? (ПОПАСТЬ К) rus_verbs:ПОДНЯТЬ{}, // Мартин поднял ружье к плечу. (ПОДНЯТЬ К) rus_verbs:ПОТЕРЯТЬ{}, // просто потеряла к нему интерес. (ПОТЕРЯТЬ К) rus_verbs:РАЗВЕРНУТЬСЯ{}, // они сразу развернулись ко мне. (РАЗВЕРНУТЬСЯ К) rus_verbs:ПОВЕРНУТЬ{}, // мальчик повернул к ним голову. (ПОВЕРНУТЬ К) rus_verbs:вызвать{}, // или вызвать к жизни? (вызвать к) rus_verbs:ВЫХОДИТЬ{}, // их земли выходят к морю. (ВЫХОДИТЬ К) rus_verbs:ЕХАТЬ{}, // мы долго ехали к вам. (ЕХАТЬ К) rus_verbs:опуститься{}, // Алиса опустилась к самому дну. (опуститься к) rus_verbs:подняться{}, // они молча поднялись к себе. (подняться к) rus_verbs:ДВИНУТЬСЯ{}, // толстяк тяжело двинулся к ним. (ДВИНУТЬСЯ К) rus_verbs:ПОПЯТИТЬСЯ{}, // ведьмак осторожно попятился к лошади. (ПОПЯТИТЬСЯ К) rus_verbs:РИНУТЬСЯ{}, // мышелов ринулся к черной стене. (РИНУТЬСЯ К) rus_verbs:ТОЛКНУТЬ{}, // к этому толкнул ее ты. (ТОЛКНУТЬ К) rus_verbs:отпрыгнуть{}, // Вадим поспешно отпрыгнул к борту. (отпрыгнуть к) rus_verbs:отступить{}, // мы поспешно отступили к стене. (отступить к) rus_verbs:ЗАБРАТЬ{}, // мы забрали их к себе. (ЗАБРАТЬ к) rus_verbs:ВЗЯТЬ{}, // потом возьму тебя к себе. (ВЗЯТЬ К) rus_verbs:лежать{}, // наш путь лежал к ним. (лежать к) rus_verbs:поползти{}, // ее рука поползла к оружию. (поползти к) rus_verbs:требовать{}, // вас требует к себе император. (требовать к) rus_verbs:поехать{}, // ты должен поехать к нему. (поехать к) rus_verbs:тянуться{}, // мордой животное тянулось к земле. (тянуться к) rus_verbs:ЖДАТЬ{}, // жди их завтра к утру. (ЖДАТЬ К) rus_verbs:ПОЛЕТЕТЬ{}, // они стремительно полетели к земле. (ПОЛЕТЕТЬ К) rus_verbs:подойти{}, // помоги мне подойти к столу. (подойти к) rus_verbs:РАЗВЕРНУТЬ{}, // мужик развернул к нему коня. (РАЗВЕРНУТЬ К) rus_verbs:ПРИВЕЗТИ{}, // нас привезли прямо к королю. (ПРИВЕЗТИ К) rus_verbs:отпрянуть{}, // незнакомец отпрянул к стене. (отпрянуть к) rus_verbs:побежать{}, // Cергей побежал к двери. (побежать к) rus_verbs:отбросить{}, // сильный удар отбросил его к стене. (отбросить к) rus_verbs:ВЫНУДИТЬ{}, // они вынудили меня к сотрудничеству (ВЫНУДИТЬ К) rus_verbs:подтянуть{}, // он подтянул к себе стул и сел на него (подтянуть к) rus_verbs:сойти{}, // по узкой тропинке путники сошли к реке. (сойти к) rus_verbs:являться{}, // по ночам к нему являлись призраки. (являться к) rus_verbs:ГНАТЬ{}, // ледяной ветер гнал их к югу. (ГНАТЬ К) rus_verbs:ВЫВЕСТИ{}, // она вывела нас точно к месту. (ВЫВЕСТИ К) rus_verbs:выехать{}, // почти сразу мы выехали к реке. rus_verbs:пододвигаться{}, // пододвигайся к окну rus_verbs:броситься{}, // большая часть защитников стен бросилась к воротам. rus_verbs:представить{}, // Его представили к ордену. rus_verbs:двигаться{}, // между тем чудище неторопливо двигалось к берегу. rus_verbs:выскочить{}, // тем временем они выскочили к реке. rus_verbs:выйти{}, // тем временем они вышли к лестнице. rus_verbs:потянуть{}, // Мальчик схватил верёвку и потянул её к себе. rus_verbs:приложить{}, // приложить к детали повышенное усилие rus_verbs:пройти{}, // пройти к стойке регистрации (стойка регистрации - проверить проверку) rus_verbs:отнестись{}, // отнестись к животным с сочуствием rus_verbs:привязать{}, // привязать за лапу веревкой к колышку, воткнутому в землю rus_verbs:прыгать{}, // прыгать к хозяину на стол rus_verbs:приглашать{}, // приглашать к доктору rus_verbs:рваться{}, // Чужие люди рвутся к власти rus_verbs:понестись{}, // понестись к обрыву rus_verbs:питать{}, // питать привязанность к алкоголю rus_verbs:заехать{}, // Коля заехал к Оле rus_verbs:переехать{}, // переехать к родителям rus_verbs:ползти{}, // ползти к дороге rus_verbs:сводиться{}, // сводиться к элементарному действию rus_verbs:добавлять{}, // добавлять к общей сумме rus_verbs:подбросить{}, // подбросить к потолку rus_verbs:призывать{}, // призывать к спокойствию rus_verbs:пробираться{}, // пробираться к партизанам rus_verbs:отвезти{}, // отвезти к родителям rus_verbs:применяться{}, // применяться к уравнению rus_verbs:сходиться{}, // сходиться к точному решению rus_verbs:допускать{}, // допускать к сдаче зачета rus_verbs:свести{}, // свести к нулю rus_verbs:придвинуть{}, // придвинуть к мальчику rus_verbs:подготовить{}, // подготовить к печати rus_verbs:подобраться{}, // подобраться к оленю rus_verbs:заторопиться{}, // заторопиться к выходу rus_verbs:пристать{}, // пристать к берегу rus_verbs:поманить{}, // поманить к себе rus_verbs:припасть{}, // припасть к алтарю rus_verbs:притащить{}, // притащить к себе домой rus_verbs:прижимать{}, // прижимать к груди rus_verbs:подсесть{}, // подсесть к симпатичной девочке rus_verbs:придвинуться{}, // придвинуться к окну rus_verbs:отпускать{}, // отпускать к другу rus_verbs:пригнуться{}, // пригнуться к земле rus_verbs:пристроиться{}, // пристроиться к колонне rus_verbs:сгрести{}, // сгрести к себе rus_verbs:удрать{}, // удрать к цыганам rus_verbs:прибавиться{}, // прибавиться к общей сумме rus_verbs:присмотреться{}, // присмотреться к покупке rus_verbs:подкатить{}, // подкатить к трюму rus_verbs:клонить{}, // клонить ко сну rus_verbs:проследовать{}, // проследовать к выходу rus_verbs:пододвинуть{}, // пододвинуть к себе rus_verbs:применять{}, // применять к сотрудникам rus_verbs:прильнуть{}, // прильнуть к экранам rus_verbs:подвинуть{}, // подвинуть к себе rus_verbs:примчаться{}, // примчаться к папе rus_verbs:подкрасться{}, // подкрасться к жертве rus_verbs:привязаться{}, // привязаться к собаке rus_verbs:забирать{}, // забирать к себе rus_verbs:прорваться{}, // прорваться к кассе rus_verbs:прикасаться{}, // прикасаться к коже rus_verbs:уносить{}, // уносить к себе rus_verbs:подтянуться{}, // подтянуться к месту rus_verbs:привозить{}, // привозить к ветеринару rus_verbs:подползти{}, // подползти к зайцу rus_verbs:приблизить{}, // приблизить к глазам rus_verbs:применить{}, // применить к уравнению простое преобразование rus_verbs:приглядеться{}, // приглядеться к изображению rus_verbs:приложиться{}, // приложиться к ручке rus_verbs:приставать{}, // приставать к девчонкам rus_verbs:запрещаться{}, // запрещаться к показу rus_verbs:прибегать{}, // прибегать к насилию rus_verbs:побудить{}, // побудить к действиям rus_verbs:притягивать{}, // притягивать к себе rus_verbs:пристроить{}, // пристроить к полезному делу rus_verbs:приговорить{}, // приговорить к смерти rus_verbs:склоняться{}, // склоняться к прекращению разработки rus_verbs:подъезжать{}, // подъезжать к вокзалу rus_verbs:привалиться{}, // привалиться к забору rus_verbs:наклоняться{}, // наклоняться к щенку rus_verbs:подоспеть{}, // подоспеть к обеду rus_verbs:прилипнуть{}, // прилипнуть к окну rus_verbs:приволочь{}, // приволочь к себе rus_verbs:устремляться{}, // устремляться к вершине rus_verbs:откатиться{}, // откатиться к исходным позициям rus_verbs:побуждать{}, // побуждать к действиям rus_verbs:прискакать{}, // прискакать к кормежке rus_verbs:присматриваться{}, // присматриваться к новичку rus_verbs:прижиматься{}, // прижиматься к борту rus_verbs:жаться{}, // жаться к огню rus_verbs:передвинуть{}, // передвинуть к окну rus_verbs:допускаться{}, // допускаться к экзаменам rus_verbs:прикрепить{}, // прикрепить к корпусу rus_verbs:отправлять{}, // отправлять к специалистам rus_verbs:перебежать{}, // перебежать к врагам rus_verbs:притронуться{}, // притронуться к реликвии rus_verbs:заспешить{}, // заспешить к семье rus_verbs:ревновать{}, // ревновать к сопернице rus_verbs:подступить{}, // подступить к горлу rus_verbs:уводить{}, // уводить к ветеринару rus_verbs:побросать{}, // побросать к ногам rus_verbs:подаваться{}, // подаваться к ужину rus_verbs:приписывать{}, // приписывать к достижениям rus_verbs:относить{}, // относить к растениям rus_verbs:принюхаться{}, // принюхаться к ароматам rus_verbs:подтащить{}, // подтащить к себе rus_verbs:прислонить{}, // прислонить к стене rus_verbs:подплыть{}, // подплыть к бую rus_verbs:опаздывать{}, // опаздывать к стилисту rus_verbs:примкнуть{}, // примкнуть к деомнстрантам rus_verbs:стекаться{}, // стекаются к стенам тюрьмы rus_verbs:подготовиться{}, // подготовиться к марафону rus_verbs:приглядываться{}, // приглядываться к новичку rus_verbs:присоединяться{}, // присоединяться к сообществу rus_verbs:клониться{}, // клониться ко сну rus_verbs:привыкать{}, // привыкать к хорошему rus_verbs:принудить{}, // принудить к миру rus_verbs:уплыть{}, // уплыть к далекому берегу rus_verbs:утащить{}, // утащить к детенышам rus_verbs:приплыть{}, // приплыть к финишу rus_verbs:подбегать{}, // подбегать к хозяину rus_verbs:лишаться{}, // лишаться средств к существованию rus_verbs:приступать{}, // приступать к операции rus_verbs:пробуждать{}, // пробуждать лекцией интерес к математике rus_verbs:подключить{}, // подключить к трубе rus_verbs:подключиться{}, // подключиться к сети rus_verbs:прилить{}, // прилить к лицу rus_verbs:стучаться{}, // стучаться к соседям rus_verbs:пристегнуть{}, // пристегнуть к креслу rus_verbs:присоединить{}, // присоединить к сети rus_verbs:отбежать{}, // отбежать к противоположной стене rus_verbs:подвезти{}, // подвезти к набережной rus_verbs:прибегнуть{}, // прибегнуть к хитрости rus_verbs:приучить{}, // приучить к туалету rus_verbs:подталкивать{}, // подталкивать к выходу rus_verbs:прорываться{}, // прорываться к выходу rus_verbs:увозить{}, // увозить к ветеринару rus_verbs:засеменить{}, // засеменить к выходу rus_verbs:крепиться{}, // крепиться к потолку rus_verbs:прибрать{}, // прибрать к рукам rus_verbs:пристраститься{}, // пристраститься к наркотикам rus_verbs:поспеть{}, // поспеть к обеду rus_verbs:привязывать{}, // привязывать к дереву rus_verbs:прилагать{}, // прилагать к документам rus_verbs:переправить{}, // переправить к дедушке rus_verbs:подогнать{}, // подогнать к воротам rus_verbs:тяготеть{}, // тяготеть к социализму rus_verbs:подбираться{}, // подбираться к оленю rus_verbs:подступать{}, // подступать к горлу rus_verbs:примыкать{}, // примыкать к первому элементу rus_verbs:приладить{}, // приладить к велосипеду rus_verbs:подбрасывать{}, // подбрасывать к потолку rus_verbs:перевозить{}, // перевозить к новому месту дислокации rus_verbs:усаживаться{}, // усаживаться к окну rus_verbs:приближать{}, // приближать к глазам rus_verbs:попроситься{}, // попроситься к бабушке rus_verbs:прибить{}, // прибить к доске rus_verbs:перетащить{}, // перетащить к себе rus_verbs:прицепить{}, // прицепить к паровозу rus_verbs:прикладывать{}, // прикладывать к ране rus_verbs:устареть{}, // устареть к началу войны rus_verbs:причалить{}, // причалить к пристани rus_verbs:приспособиться{}, // приспособиться к опозданиям rus_verbs:принуждать{}, // принуждать к миру rus_verbs:соваться{}, // соваться к директору rus_verbs:протолкаться{}, // протолкаться к прилавку rus_verbs:приковать{}, // приковать к батарее rus_verbs:подкрадываться{}, // подкрадываться к суслику rus_verbs:подсадить{}, // подсадить к арестонту rus_verbs:прикатить{}, // прикатить к финишу rus_verbs:протащить{}, // протащить к владыке rus_verbs:сужаться{}, // сужаться к основанию rus_verbs:присовокупить{}, // присовокупить к пожеланиям rus_verbs:пригвоздить{}, // пригвоздить к доске rus_verbs:отсылать{}, // отсылать к первоисточнику rus_verbs:изготовиться{}, // изготовиться к прыжку rus_verbs:прилагаться{}, // прилагаться к покупке rus_verbs:прицепиться{}, // прицепиться к вагону rus_verbs:примешиваться{}, // примешиваться к вину rus_verbs:переселить{}, // переселить к старшекурсникам rus_verbs:затрусить{}, // затрусить к выходе rus_verbs:приспособить{}, // приспособить к обогреву rus_verbs:примериться{}, // примериться к аппарату rus_verbs:прибавляться{}, // прибавляться к пенсии rus_verbs:подкатиться{}, // подкатиться к воротам rus_verbs:стягивать{}, // стягивать к границе rus_verbs:дописать{}, // дописать к роману rus_verbs:подпустить{}, // подпустить к корове rus_verbs:склонять{}, // склонять к сотрудничеству rus_verbs:припечатать{}, // припечатать к стене rus_verbs:охладеть{}, // охладеть к музыке rus_verbs:пришить{}, // пришить к шинели rus_verbs:принюхиваться{}, // принюхиваться к ветру rus_verbs:подрулить{}, // подрулить к барышне rus_verbs:наведаться{}, // наведаться к оракулу rus_verbs:клеиться{}, // клеиться к конверту rus_verbs:перетянуть{}, // перетянуть к себе rus_verbs:переметнуться{}, // переметнуться к конкурентам rus_verbs:липнуть{}, // липнуть к сокурсницам rus_verbs:поковырять{}, // поковырять к выходу rus_verbs:подпускать{}, // подпускать к пульту управления rus_verbs:присосаться{}, // присосаться к источнику rus_verbs:приклеить{}, // приклеить к стеклу rus_verbs:подтягивать{}, // подтягивать к себе rus_verbs:подкатывать{}, // подкатывать к даме rus_verbs:притрагиваться{}, // притрагиваться к опухоли rus_verbs:слетаться{}, // слетаться к водопою rus_verbs:хаживать{}, // хаживать к батюшке rus_verbs:привлекаться{}, // привлекаться к административной ответственности rus_verbs:подзывать{}, // подзывать к себе rus_verbs:прикладываться{}, // прикладываться к иконе rus_verbs:подтягиваться{}, // подтягиваться к парламенту rus_verbs:прилепить{}, // прилепить к стенке холодильника rus_verbs:пододвинуться{}, // пододвинуться к экрану rus_verbs:приползти{}, // приползти к дереву rus_verbs:запаздывать{}, // запаздывать к обеду rus_verbs:припереть{}, // припереть к стене rus_verbs:нагибаться{}, // нагибаться к цветку инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять к воротам деепричастие:сгоняв{}, rus_verbs:поковылять{}, // поковылять к выходу rus_verbs:привалить{}, // привалить к столбу rus_verbs:отпроситься{}, // отпроситься к родителям rus_verbs:приспосабливаться{}, // приспосабливаться к новым условиям rus_verbs:прилипать{}, // прилипать к рукам rus_verbs:подсоединить{}, // подсоединить к приборам rus_verbs:приливать{}, // приливать к голове rus_verbs:подселить{}, // подселить к другим новичкам rus_verbs:прилепиться{}, // прилепиться к шкуре rus_verbs:подлетать{}, // подлетать к пункту назначения rus_verbs:пристегнуться{}, // пристегнуться к креслу ремнями rus_verbs:прибиться{}, // прибиться к стае, улетающей на юг rus_verbs:льнуть{}, // льнуть к заботливому хозяину rus_verbs:привязываться{}, // привязываться к любящему хозяину rus_verbs:приклеиться{}, // приклеиться к спине rus_verbs:стягиваться{}, // стягиваться к сенату rus_verbs:подготавливать{}, // подготавливать к выходу на арену rus_verbs:приглашаться{}, // приглашаться к доктору rus_verbs:причислять{}, // причислять к отличникам rus_verbs:приколоть{}, // приколоть к лацкану rus_verbs:наклонять{}, // наклонять к горизонту rus_verbs:припадать{}, // припадать к первоисточнику rus_verbs:приобщиться{}, // приобщиться к культурному наследию rus_verbs:придираться{}, // придираться к мелким ошибкам rus_verbs:приучать{}, // приучать к лотку rus_verbs:промотать{}, // промотать к началу rus_verbs:прихлынуть{}, // прихлынуть к голове rus_verbs:пришвартоваться{}, // пришвартоваться к первому пирсу rus_verbs:прикрутить{}, // прикрутить к велосипеду rus_verbs:подплывать{}, // подплывать к лодке rus_verbs:приравниваться{}, // приравниваться к побегу rus_verbs:подстрекать{}, // подстрекать к вооруженной борьбе с оккупантами rus_verbs:изготовляться{}, // изготовляться к прыжку из стратосферы rus_verbs:приткнуться{}, // приткнуться к первой группе туристов rus_verbs:приручить{}, // приручить котика к лотку rus_verbs:приковывать{}, // приковывать к себе все внимание прессы rus_verbs:приготовляться{}, // приготовляться к первому экзамену rus_verbs:остыть{}, // Вода остынет к утру. rus_verbs:приехать{}, // Он приедет к концу будущей недели. rus_verbs:подсаживаться{}, rus_verbs:успевать{}, // успевать к стилисту rus_verbs:привлекать{}, // привлекать к себе внимание прилагательное:устойчивый{}, // переводить в устойчивую к перегреву форму rus_verbs:прийтись{}, // прийтись ко двору инфинитив:адаптировать{вид:несоверш}, // машина была адаптирована к условиям крайнего севера инфинитив:адаптировать{вид:соверш}, глагол:адаптировать{вид:несоверш}, глагол:адаптировать{вид:соверш}, деепричастие:адаптировав{}, деепричастие:адаптируя{}, прилагательное:адаптирующий{}, прилагательное:адаптировавший{ вид:соверш }, //+прилагательное:адаптировавший{ вид:несоверш }, прилагательное:адаптированный{}, инфинитив:адаптироваться{вид:соверш}, // тело адаптировалось к условиям суровой зимы инфинитив:адаптироваться{вид:несоверш}, глагол:адаптироваться{вид:соверш}, глагол:адаптироваться{вид:несоверш}, деепричастие:адаптировавшись{}, деепричастие:адаптируясь{}, прилагательное:адаптировавшийся{вид:соверш}, //+прилагательное:адаптировавшийся{вид:несоверш}, прилагательное:адаптирующийся{}, rus_verbs:апеллировать{}, // оратор апеллировал к патриотизму своих слушателей rus_verbs:близиться{}, // Шторм близится к побережью rus_verbs:доставить{}, // Эскиз ракеты, способной доставить корабль к Луне rus_verbs:буксировать{}, // Буксир буксирует танкер к месту стоянки rus_verbs:причислить{}, // Мы причислили его к числу экспертов rus_verbs:вести{}, // Наша партия ведет народ к процветанию rus_verbs:взывать{}, // Учителя взывают к совести хулигана rus_verbs:воззвать{}, // воззвать соплеменников к оружию rus_verbs:возревновать{}, // возревновать к поклонникам rus_verbs:воспылать{}, // Коля воспылал к Оле страстной любовью rus_verbs:восходить{}, // восходить к вершине rus_verbs:восшествовать{}, // восшествовать к вершине rus_verbs:успеть{}, // успеть к обеду rus_verbs:повернуться{}, // повернуться к кому-то rus_verbs:обратиться{}, // обратиться к охраннику rus_verbs:звать{}, // звать к столу rus_verbs:отправиться{}, // отправиться к парикмахеру rus_verbs:обернуться{}, // обернуться к зовущему rus_verbs:явиться{}, // явиться к следователю rus_verbs:уехать{}, // уехать к родне rus_verbs:прибыть{}, // прибыть к перекличке rus_verbs:привыкнуть{}, // привыкнуть к голоду rus_verbs:уходить{}, // уходить к цыганам rus_verbs:привести{}, // привести к себе rus_verbs:шагнуть{}, // шагнуть к славе rus_verbs:относиться{}, // относиться к прежним периодам rus_verbs:подослать{}, // подослать к врагам rus_verbs:поспешить{}, // поспешить к обеду rus_verbs:зайти{}, // зайти к подруге rus_verbs:позвать{}, // позвать к себе rus_verbs:потянуться{}, // потянуться к рычагам rus_verbs:пускать{}, // пускать к себе rus_verbs:отвести{}, // отвести к врачу rus_verbs:приблизиться{}, // приблизиться к решению задачи rus_verbs:прижать{}, // прижать к стене rus_verbs:отправить{}, // отправить к доктору rus_verbs:падать{}, // падать к многолетним минимумам rus_verbs:полезть{}, // полезть к дерущимся rus_verbs:лезть{}, // Ты сама ко мне лезла! rus_verbs:направить{}, // направить к майору rus_verbs:приводить{}, // приводить к дантисту rus_verbs:кинуться{}, // кинуться к двери rus_verbs:поднести{}, // поднести к глазам rus_verbs:подниматься{}, // подниматься к себе rus_verbs:прибавить{}, // прибавить к результату rus_verbs:зашагать{}, // зашагать к выходу rus_verbs:склониться{}, // склониться к земле rus_verbs:стремиться{}, // стремиться к вершине rus_verbs:лететь{}, // лететь к родственникам rus_verbs:ездить{}, // ездить к любовнице rus_verbs:приближаться{}, // приближаться к финише rus_verbs:помчаться{}, // помчаться к стоматологу rus_verbs:прислушаться{}, // прислушаться к происходящему rus_verbs:изменить{}, // изменить к лучшему собственную жизнь rus_verbs:проявить{}, // проявить к погибшим сострадание rus_verbs:подбежать{}, // подбежать к упавшему rus_verbs:терять{}, // терять к партнерам доверие rus_verbs:пропустить{}, // пропустить к певцу rus_verbs:подвести{}, // подвести к глазам rus_verbs:меняться{}, // меняться к лучшему rus_verbs:заходить{}, // заходить к другу rus_verbs:рвануться{}, // рвануться к воде rus_verbs:привлечь{}, // привлечь к себе внимание rus_verbs:присоединиться{}, // присоединиться к сети rus_verbs:приезжать{}, // приезжать к дедушке rus_verbs:дернуться{}, // дернуться к борту rus_verbs:подъехать{}, // подъехать к воротам rus_verbs:готовиться{}, // готовиться к дождю rus_verbs:убежать{}, // убежать к маме rus_verbs:поднимать{}, // поднимать к источнику сигнала rus_verbs:отослать{}, // отослать к руководителю rus_verbs:приготовиться{}, // приготовиться к худшему rus_verbs:приступить{}, // приступить к выполнению обязанностей rus_verbs:метнуться{}, // метнуться к фонтану rus_verbs:прислушиваться{}, // прислушиваться к голосу разума rus_verbs:побрести{}, // побрести к выходу rus_verbs:мчаться{}, // мчаться к успеху rus_verbs:нестись{}, // нестись к обрыву rus_verbs:попадать{}, // попадать к хорошему костоправу rus_verbs:опоздать{}, // опоздать к психотерапевту rus_verbs:посылать{}, // посылать к доктору rus_verbs:поплыть{}, // поплыть к берегу rus_verbs:подтолкнуть{}, // подтолкнуть к активной работе rus_verbs:отнести{}, // отнести животное к ветеринару rus_verbs:прислониться{}, // прислониться к стволу rus_verbs:наклонить{}, // наклонить к миске с молоком rus_verbs:прикоснуться{}, // прикоснуться к поверхности rus_verbs:увезти{}, // увезти к бабушке rus_verbs:заканчиваться{}, // заканчиваться к концу путешествия rus_verbs:подозвать{}, // подозвать к себе rus_verbs:улететь{}, // улететь к теплым берегам rus_verbs:ложиться{}, // ложиться к мужу rus_verbs:убираться{}, // убираться к чертовой бабушке rus_verbs:класть{}, // класть к другим документам rus_verbs:доставлять{}, // доставлять к подъезду rus_verbs:поворачиваться{}, // поворачиваться к источнику шума rus_verbs:заглядывать{}, // заглядывать к любовнице rus_verbs:занести{}, // занести к заказчикам rus_verbs:прибежать{}, // прибежать к папе rus_verbs:притянуть{}, // притянуть к причалу rus_verbs:переводить{}, // переводить в устойчивую к перегреву форму rus_verbs:подать{}, // он подал лимузин к подъезду rus_verbs:подавать{}, // она подавала соус к мясу rus_verbs:приобщаться{}, // приобщаться к культуре прилагательное:неспособный{}, // Наша дочка неспособна к учению. прилагательное:неприспособленный{}, // Эти устройства неприспособлены к работе в жару прилагательное:предназначенный{}, // Старый дом предназначен к сносу. прилагательное:внимательный{}, // Она всегда внимательна к гостям. прилагательное:назначенный{}, // Дело назначено к докладу. прилагательное:разрешенный{}, // Эта книга разрешена к печати. прилагательное:снисходительный{}, // Этот учитель снисходителен к ученикам. прилагательное:готовый{}, // Я готов к экзаменам. прилагательное:требовательный{}, // Он очень требователен к себе. прилагательное:жадный{}, // Он жаден к деньгам. прилагательное:глухой{}, // Он глух к моей просьбе. прилагательное:добрый{}, // Он добр к детям. rus_verbs:проявлять{}, // Он всегда проявлял живой интерес к нашим делам. rus_verbs:плыть{}, // Пароход плыл к берегу. rus_verbs:пойти{}, // я пошел к доктору rus_verbs:придти{}, // придти к выводу rus_verbs:заглянуть{}, // Я заглянул к вам мимоходом. rus_verbs:принадлежать{}, // Это существо принадлежит к разряду растений. rus_verbs:подготавливаться{}, // Ученики подготавливаются к экзаменам. rus_verbs:спускаться{}, // Улица круто спускается к реке. rus_verbs:спуститься{}, // Мы спустились к реке. rus_verbs:пустить{}, // пускать ко дну rus_verbs:приговаривать{}, // Мы приговариваем тебя к пожизненному веселью! rus_verbs:отойти{}, // Дом отошёл к племяннику. rus_verbs:отходить{}, // Коля отходил ко сну. rus_verbs:приходить{}, // местные жители к нему приходили лечиться rus_verbs:кидаться{}, // не кидайся к столу rus_verbs:ходить{}, // Она простудилась и сегодня ходила к врачу. rus_verbs:закончиться{}, // Собрание закончилось к вечеру. rus_verbs:послать{}, // Они выбрали своих депутатов и послали их к заведующему. rus_verbs:направиться{}, // Мы сошли на берег и направились к городу. rus_verbs:направляться{}, rus_verbs:свестись{}, // Всё свелось к нулю. rus_verbs:прислать{}, // Пришлите кого-нибудь к ней. rus_verbs:присылать{}, // Он присылал к должнику своих головорезов rus_verbs:подлететь{}, // Самолёт подлетел к лесу. rus_verbs:возвращаться{}, // он возвращается к старой работе глагол:находиться{ вид:несоверш }, инфинитив:находиться{ вид:несоверш }, деепричастие:находясь{}, прилагательное:находившийся{}, прилагательное:находящийся{}, // Япония находится к востоку от Китая. rus_verbs:возвращать{}, // возвращать к жизни rus_verbs:располагать{}, // Атмосфера располагает к работе. rus_verbs:возвратить{}, // Колокольный звон возвратил меня к прошлому. rus_verbs:поступить{}, // К нам поступила жалоба. rus_verbs:поступать{}, // К нам поступают жалобы. rus_verbs:прыгнуть{}, // Белка прыгнула к дереву rus_verbs:торопиться{}, // пассажиры торопятся к выходу rus_verbs:поторопиться{}, // поторопитесь к выходу rus_verbs:вернуть{}, // вернуть к активной жизни rus_verbs:припирать{}, // припирать к стенке rus_verbs:проваливать{}, // Проваливай ко всем чертям! rus_verbs:вбежать{}, // Коля вбежал ко мне rus_verbs:вбегать{}, // Коля вбегал ко мне глагол:забегать{ вид:несоверш }, // Коля забегал ко мне rus_verbs:постучаться{}, // Коля постучался ко мне. rus_verbs:повести{}, // Спросил я озорного Антонио и повел его к дому rus_verbs:понести{}, // Мы понесли кота к ветеринару rus_verbs:принести{}, // Я принес кота к ветеринару rus_verbs:устремиться{}, // Мы устремились к ручью. rus_verbs:подводить{}, // Учитель подводил детей к аквариуму rus_verbs:следовать{}, // Я получил приказ следовать к месту нового назначения. rus_verbs:пригласить{}, // Я пригласил к себе товарищей. rus_verbs:собираться{}, // Я собираюсь к тебе в гости. rus_verbs:собраться{}, // Маша собралась к дантисту rus_verbs:сходить{}, // Я схожу к врачу. rus_verbs:идти{}, // Маша уверенно шла к Пете rus_verbs:измениться{}, // Основные индексы рынка акций РФ почти не изменились к закрытию. rus_verbs:отыграть{}, // Российский рынок акций отыграл падение к закрытию. rus_verbs:заканчивать{}, // Заканчивайте к обеду rus_verbs:обращаться{}, // Обращайтесь ко мне в любое время rus_verbs:окончить{}, // rus_verbs:дозвониться{}, // Я не мог к вам дозвониться. глагол:прийти{}, инфинитив:прийти{}, // Антонио пришел к Элеонор rus_verbs:уйти{}, // Антонио ушел к Элеонор rus_verbs:бежать{}, // Антонио бежит к Элеонор rus_verbs:спешить{}, // Антонио спешит к Элеонор rus_verbs:скакать{}, // Антонио скачет к Элеонор rus_verbs:красться{}, // Антонио крадётся к Элеонор rus_verbs:поскакать{}, // беглецы поскакали к холмам rus_verbs:перейти{} // Антонио перешел к Элеонор } fact гл_предл { if context { Гл_К_Дат предлог:к{} *:*{ падеж:дат } } then return true } fact гл_предл { if context { Гл_К_Дат предлог:к{} @regex("[a-z]+[0-9]*") } then return true } // для остальных падежей запрещаем. fact гл_предл { if context { * предлог:к{} *:*{} } then return false,-5 } #endregion Предлог_К #region Предлог_ДЛЯ // ------------------- С ПРЕДЛОГОМ 'ДЛЯ' ---------------------- wordentry_set Гл_ДЛЯ_Род={ частица:нет{}, // для меня нет других путей. частица:нету{}, rus_verbs:ЗАДЕРЖАТЬ{}, // полиция может задержать их для выяснения всех обстоятельств и дальнейшего опознания. (ЗАДЕРЖАТЬ) rus_verbs:ДЕЛАТЬСЯ{}, // это делалось для людей (ДЕЛАТЬСЯ) rus_verbs:обернуться{}, // обернулась для греческого рынка труда банкротствами предприятий и масштабными сокращениями (обернуться) rus_verbs:ПРЕДНАЗНАЧАТЬСЯ{}, // Скорее всего тяжелый клинок вообще не предназначался для бросков (ПРЕДНАЗНАЧАТЬСЯ) rus_verbs:ПОЛУЧИТЬ{}, // ты можешь получить его для нас? (ПОЛУЧИТЬ) rus_verbs:ПРИДУМАТЬ{}, // Ваш босс уже придумал для нас веселенькую смерть. (ПРИДУМАТЬ) rus_verbs:оказаться{}, // это оказалось для них тяжелой задачей rus_verbs:ГОВОРИТЬ{}, // теперь она говорила для нас обоих (ГОВОРИТЬ) rus_verbs:ОСВОБОДИТЬ{}, // освободить ее для тебя? (ОСВОБОДИТЬ) rus_verbs:работать{}, // Мы работаем для тех, кто ценит удобство rus_verbs:СТАТЬ{}, // кем она станет для него? (СТАТЬ) rus_verbs:ЯВИТЬСЯ{}, // вы для этого явились сюда? (ЯВИТЬСЯ) rus_verbs:ПОТЕРЯТЬ{}, // жизнь потеряла для меня всякий смысл (ПОТЕРЯТЬ) rus_verbs:УТРАТИТЬ{}, // мой мир утратил для меня всякое подобие смысла (УТРАТИТЬ) rus_verbs:ДОСТАТЬ{}, // ты должен достать ее для меня! (ДОСТАТЬ) rus_verbs:БРАТЬ{}, // некоторые берут для себя (БРАТЬ) rus_verbs:ИМЕТЬ{}, // имею для вас новость (ИМЕТЬ) rus_verbs:ЖДАТЬ{}, // тебя ждут для разговора (ЖДАТЬ) rus_verbs:ПРОПАСТЬ{}, // совсем пропал для мира (ПРОПАСТЬ) rus_verbs:ПОДНЯТЬ{}, // нас подняли для охоты (ПОДНЯТЬ) rus_verbs:ОСТАНОВИТЬСЯ{}, // время остановилось для нее (ОСТАНОВИТЬСЯ) rus_verbs:НАЧИНАТЬСЯ{}, // для него начинается новая жизнь (НАЧИНАТЬСЯ) rus_verbs:КОНЧИТЬСЯ{}, // кончились для него эти игрушки (КОНЧИТЬСЯ) rus_verbs:НАСТАТЬ{}, // для него настало время действовать (НАСТАТЬ) rus_verbs:СТРОИТЬ{}, // для молодых строили новый дом (СТРОИТЬ) rus_verbs:ВЗЯТЬ{}, // возьми для защиты этот меч (ВЗЯТЬ) rus_verbs:ВЫЯСНИТЬ{}, // попытаюсь выяснить для вас всю цепочку (ВЫЯСНИТЬ) rus_verbs:ПРИГОТОВИТЬ{}, // давай попробуем приготовить для них сюрприз (ПРИГОТОВИТЬ) rus_verbs:ПОДХОДИТЬ{}, // берег моря мертвых подходил для этого идеально (ПОДХОДИТЬ) rus_verbs:ОСТАТЬСЯ{}, // внешний вид этих тварей остался для нас загадкой (ОСТАТЬСЯ) rus_verbs:ПРИВЕЗТИ{}, // для меня привезли пиво (ПРИВЕЗТИ) прилагательное:ХАРАКТЕРНЫЙ{}, // Для всей территории края характерен умеренный континентальный климат (ХАРАКТЕРНЫЙ) rus_verbs:ПРИВЕСТИ{}, // для меня белую лошадь привели (ПРИВЕСТИ ДЛЯ) rus_verbs:ДЕРЖАТЬ{}, // их держат для суда (ДЕРЖАТЬ ДЛЯ) rus_verbs:ПРЕДОСТАВИТЬ{}, // вьетнамец предоставил для мигрантов места проживания в ряде вологодских общежитий (ПРЕДОСТАВИТЬ ДЛЯ) rus_verbs:ПРИДУМЫВАТЬ{}, // придумывая для этого разнообразные причины (ПРИДУМЫВАТЬ ДЛЯ) rus_verbs:оставить{}, // или вообще решили оставить планету для себя rus_verbs:оставлять{}, rus_verbs:ВОССТАНОВИТЬ{}, // как ты можешь восстановить это для меня? (ВОССТАНОВИТЬ ДЛЯ) rus_verbs:ТАНЦЕВАТЬ{}, // а вы танцевали для меня танец семи покрывал (ТАНЦЕВАТЬ ДЛЯ) rus_verbs:ДАТЬ{}, // твой принц дал мне это для тебя! (ДАТЬ ДЛЯ) rus_verbs:ВОСПОЛЬЗОВАТЬСЯ{}, // мужчина из лагеря решил воспользоваться для передвижения рекой (ВОСПОЛЬЗОВАТЬСЯ ДЛЯ) rus_verbs:СЛУЖИТЬ{}, // они служили для разговоров (СЛУЖИТЬ ДЛЯ) rus_verbs:ИСПОЛЬЗОВАТЬСЯ{}, // Для вычисления радиуса поражения ядерных взрывов используется формула (ИСПОЛЬЗОВАТЬСЯ ДЛЯ) rus_verbs:ПРИМЕНЯТЬСЯ{}, // Применяется для изготовления алкогольных коктейлей (ПРИМЕНЯТЬСЯ ДЛЯ) rus_verbs:СОВЕРШАТЬСЯ{}, // Для этого совершался специальный магический обряд (СОВЕРШАТЬСЯ ДЛЯ) rus_verbs:ПРИМЕНИТЬ{}, // а здесь попробуем применить ее для других целей. (ПРИМЕНИТЬ ДЛЯ) rus_verbs:ПОЗВАТЬ{}, // ты позвал меня для настоящей работы. (ПОЗВАТЬ ДЛЯ) rus_verbs:НАЧАТЬСЯ{}, // очередной денек начался для Любки неудачно (НАЧАТЬСЯ ДЛЯ) rus_verbs:ПОСТАВИТЬ{}, // вас здесь для красоты поставили? (ПОСТАВИТЬ ДЛЯ) rus_verbs:умереть{}, // или умерла для всяких чувств? (умереть для) rus_verbs:ВЫБРАТЬ{}, // ты сам выбрал для себя этот путь. (ВЫБРАТЬ ДЛЯ) rus_verbs:ОТМЕТИТЬ{}, // тот же отметил для себя другое. (ОТМЕТИТЬ ДЛЯ) rus_verbs:УСТРОИТЬ{}, // мы хотим устроить для них школу. (УСТРОИТЬ ДЛЯ) rus_verbs:БЫТЬ{}, // у меня есть для тебя работа. (БЫТЬ ДЛЯ) rus_verbs:ВЫЙТИ{}, // для всего нашего поколения так вышло. (ВЫЙТИ ДЛЯ) прилагательное:ВАЖНЫЙ{}, // именно твое мнение для нас крайне важно. (ВАЖНЫЙ ДЛЯ) прилагательное:НУЖНЫЙ{}, // для любого племени нужна прежде всего сила. (НУЖЕН ДЛЯ) прилагательное:ДОРОГОЙ{}, // эти места были дороги для них обоих. (ДОРОГОЙ ДЛЯ) rus_verbs:НАСТУПИТЬ{}, // теперь для больших людей наступило время действий. (НАСТУПИТЬ ДЛЯ) rus_verbs:ДАВАТЬ{}, // старый пень давал для этого хороший огонь. (ДАВАТЬ ДЛЯ) rus_verbs:ГОДИТЬСЯ{}, // доброе старое время годится лишь для воспоминаний. (ГОДИТЬСЯ ДЛЯ) rus_verbs:ТЕРЯТЬ{}, // время просто теряет для вас всякое значение. (ТЕРЯТЬ ДЛЯ) rus_verbs:ЖЕНИТЬСЯ{}, // настало время жениться для пользы твоего клана. (ЖЕНИТЬСЯ ДЛЯ) rus_verbs:СУЩЕСТВОВАТЬ{}, // весь мир перестал существовать для них обоих. (СУЩЕСТВОВАТЬ ДЛЯ) rus_verbs:ЖИТЬ{}, // жить для себя или жить для них. (ЖИТЬ ДЛЯ) rus_verbs:открыть{}, // двери моего дома всегда открыты для вас. (ОТКРЫТЫЙ ДЛЯ) rus_verbs:закрыть{}, // этот мир будет закрыт для них. (ЗАКРЫТЫЙ ДЛЯ) rus_verbs:ТРЕБОВАТЬСЯ{}, // для этого требуется огромное количество энергии. (ТРЕБОВАТЬСЯ ДЛЯ) rus_verbs:РАЗОРВАТЬ{}, // Алексей разорвал для этого свою рубаху. (РАЗОРВАТЬ ДЛЯ) rus_verbs:ПОДОЙТИ{}, // вполне подойдет для начала нашей экспедиции. (ПОДОЙТИ ДЛЯ) прилагательное:опасный{}, // сильный холод опасен для открытой раны. (ОПАСЕН ДЛЯ) rus_verbs:ПРИЙТИ{}, // для вас пришло очень важное сообщение. (ПРИЙТИ ДЛЯ) rus_verbs:вывести{}, // мы специально вывели этих животных для мяса. rus_verbs:убрать{}, // В вагонах метро для комфорта пассажиров уберут сиденья (УБРАТЬ В, ДЛЯ) rus_verbs:оставаться{}, // механизм этого воздействия остается для меня загадкой. (остается для) rus_verbs:ЯВЛЯТЬСЯ{}, // Чай является для китайцев обычным ежедневным напитком (ЯВЛЯТЬСЯ ДЛЯ) rus_verbs:ПРИМЕНЯТЬ{}, // Для оценок будущих изменений климата применяют модели общей циркуляции атмосферы. (ПРИМЕНЯТЬ ДЛЯ) rus_verbs:ПОВТОРЯТЬ{}, // повторяю для Пети (ПОВТОРЯТЬ ДЛЯ) rus_verbs:УПОТРЕБЛЯТЬ{}, // Краски, употребляемые для живописи (УПОТРЕБЛЯТЬ ДЛЯ) rus_verbs:ВВЕСТИ{}, // Для злостных нарушителей предложили ввести повышенные штрафы (ВВЕСТИ ДЛЯ) rus_verbs:найтись{}, // у вас найдется для него работа? rus_verbs:заниматься{}, // они занимаются этим для развлечения. (заниматься для) rus_verbs:заехать{}, // Коля заехал для обсуждения проекта rus_verbs:созреть{}, // созреть для побега rus_verbs:наметить{}, // наметить для проверки rus_verbs:уяснить{}, // уяснить для себя rus_verbs:нанимать{}, // нанимать для разовой работы rus_verbs:приспособить{}, // приспособить для удовольствия rus_verbs:облюбовать{}, // облюбовать для посиделок rus_verbs:прояснить{}, // прояснить для себя rus_verbs:задействовать{}, // задействовать для патрулирования rus_verbs:приготовлять{}, // приготовлять для проверки инфинитив:использовать{ вид:соверш }, // использовать для достижения цели инфинитив:использовать{ вид:несоверш }, глагол:использовать{ вид:соверш }, глагол:использовать{ вид:несоверш }, прилагательное:использованный{}, деепричастие:используя{}, деепричастие:использовав{}, rus_verbs:напрячься{}, // напрячься для решительного рывка rus_verbs:одобрить{}, // одобрить для использования rus_verbs:одобрять{}, // одобрять для использования rus_verbs:пригодиться{}, // пригодиться для тестирования rus_verbs:готовить{}, // готовить для выхода в свет rus_verbs:отобрать{}, // отобрать для участия в конкурсе rus_verbs:потребоваться{}, // потребоваться для подтверждения rus_verbs:пояснить{}, // пояснить для слушателей rus_verbs:пояснять{}, // пояснить для экзаменаторов rus_verbs:понадобиться{}, // понадобиться для обоснования инфинитив:адаптировать{вид:несоверш}, // машина была адаптирована для условий крайнего севера инфинитив:адаптировать{вид:соверш}, глагол:адаптировать{вид:несоверш}, глагол:адаптировать{вид:соверш}, деепричастие:адаптировав{}, деепричастие:адаптируя{}, прилагательное:адаптирующий{}, прилагательное:адаптировавший{ вид:соверш }, //+прилагательное:адаптировавший{ вид:несоверш }, прилагательное:адаптированный{}, rus_verbs:найти{}, // Папа нашел для детей няню прилагательное:вредный{}, // Это вредно для здоровья. прилагательное:полезный{}, // Прогулки полезны для здоровья. прилагательное:обязательный{}, // Этот пункт обязателен для исполнения прилагательное:бесполезный{}, // Это лекарство бесполезно для него прилагательное:необходимый{}, // Это лекарство необходимо для выздоровления rus_verbs:создать{}, // Он не создан для этого дела. прилагательное:сложный{}, // задача сложна для младших школьников прилагательное:несложный{}, прилагательное:лёгкий{}, прилагательное:сложноватый{}, rus_verbs:становиться{}, rus_verbs:представлять{}, // Это не представляет для меня интереса. rus_verbs:значить{}, // Я рос в деревне и хорошо знал, что для деревенской жизни значат пруд или речка rus_verbs:пройти{}, // День прошёл спокойно для него. rus_verbs:проходить{}, rus_verbs:высадиться{}, // большой злой пират и его отчаянные помощники высадились на необитаемом острове для поиска зарытых сокровищ rus_verbs:высаживаться{}, rus_verbs:прибавлять{}, // Он любит прибавлять для красного словца. rus_verbs:прибавить{}, rus_verbs:составить{}, // Ряд тригонометрических таблиц был составлен для астрономических расчётов. rus_verbs:составлять{}, rus_verbs:стараться{}, // Я старался для вас rus_verbs:постараться{}, // Я постарался для вас rus_verbs:сохраниться{}, // Старик хорошо сохранился для своего возраста. rus_verbs:собраться{}, // собраться для обсуждения rus_verbs:собираться{}, // собираться для обсуждения rus_verbs:уполномочивать{}, rus_verbs:уполномочить{}, // его уполномочили для ведения переговоров rus_verbs:принести{}, // Я принёс эту книгу для вас. rus_verbs:делать{}, // Я это делаю для удовольствия. rus_verbs:сделать{}, // Я сделаю это для удовольствия. rus_verbs:подготовить{}, // я подготовил для друзей сюрприз rus_verbs:подготавливать{}, // я подготавливаю для гостей новый сюрприз rus_verbs:закупить{}, // Руководство района обещало закупить новые комбайны для нашего села rus_verbs:купить{}, // Руководство района обещало купить новые комбайны для нашего села rus_verbs:прибыть{} // они прибыли для участия } fact гл_предл { if context { Гл_ДЛЯ_Род предлог:для{} *:*{ падеж:род } } then return true } fact гл_предл { if context { Гл_ДЛЯ_Род предлог:для{} @regex("[a-z]+[0-9]*") } then return true } // для остальных падежей запрещаем. fact гл_предл { if context { * предлог:для{} *:*{} } then return false,-4 } #endregion Предлог_ДЛЯ #region Предлог_ОТ // попробуем иную стратегию - запретить связывание с ОТ для отдельных глаголов, разрешив для всех остальных. wordentry_set Глаг_ОТ_Род_Запр= { rus_verbs:наслаждаться{}, // свободой от обязательств rus_verbs:насладиться{}, rus_verbs:мочь{}, // Он не мог удержаться от смеха. // rus_verbs:хотеть{}, rus_verbs:желать{}, rus_verbs:чувствовать{}, // все время от времени чувствуют его. rus_verbs:планировать{}, rus_verbs:приняться{} // мы принялись обниматься от радости. } fact гл_предл { if context { Глаг_ОТ_Род_Запр предлог:от{} * } then return false } #endregion Предлог_ОТ #region Предлог_БЕЗ /* // запретить связывание с БЕЗ для отдельных глаголов, разрешив для всех остальных. wordentry_set Глаг_БЕЗ_Род_Запр= { rus_verbs:мочь{}, // Он мог читать часами без отдыха. rus_verbs:хотеть{}, rus_verbs:желать{}, rus_verbs:планировать{}, rus_verbs:приняться{} } fact гл_предл { if context { Глаг_БЕЗ_Род_Запр предлог:без{} * } then return false } */ #endregion Предлог_БЕЗ #region Предлог_КРОМЕ fact гл_предл { if context { * ПредлогДляВсе * } then return false,-5 } #endregion Предлог_КРОМЕ // ------------------------------------ // По умолчанию разрешаем все остальные сочетания. fact гл_предл { if context { * * * } then return true }
убивать на нейтральной территории
rus_verbs:убивать{},
5,485,129
[ 1, 146, 230, 145, 114, 145, 121, 145, 115, 145, 113, 146, 229, 146, 239, 225, 145, 126, 145, 113, 225, 145, 126, 145, 118, 145, 122, 146, 229, 146, 227, 145, 113, 145, 124, 146, 239, 145, 126, 145, 127, 145, 122, 225, 146, 229, 145, 118, 146, 227, 146, 227, 145, 121, 146, 229, 145, 127, 146, 227, 145, 121, 145, 121, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 8010, 67, 502, 2038, 30, 146, 230, 145, 114, 145, 121, 145, 115, 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, -100, -100, -100 ]
./partial_match/4/0xcab5bEC403ebb2bd68c7C987a512581960651097/sources/KittyCore.sol
@dev Put a kitty up for auction to be sire. Performs checks to ensure the kitty can be sired, then delegates to reverse auction. Auction contract checks input sizes If kitty is already on any auction, this will throw because it will be owned by the auction contract. Siring auction throws if inputs are invalid and clears transfer and sire approval after escrowing the kitty.
function createSiringAuction( uint256 _kittyId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) external whenNotPaused { require(_owns(msg.sender, _kittyId)); require(isReadyToBreed(_kittyId)); _approve(_kittyId, siringAuction); siringAuction.createAuction( _kittyId, _startingPrice, _endingPrice, _duration, msg.sender ); }
8,780,594
[ 1, 6426, 279, 31758, 4098, 731, 364, 279, 4062, 358, 506, 272, 577, 18, 225, 27391, 4271, 358, 3387, 326, 31758, 4098, 848, 506, 272, 2921, 16, 1508, 225, 22310, 358, 4219, 279, 4062, 18, 432, 4062, 6835, 4271, 810, 8453, 971, 31758, 4098, 353, 1818, 603, 1281, 279, 4062, 16, 333, 903, 604, 2724, 518, 903, 506, 16199, 635, 326, 279, 4062, 6835, 18, 348, 11256, 279, 4062, 1216, 309, 4540, 854, 2057, 471, 22655, 7412, 471, 272, 577, 23556, 1839, 2904, 492, 310, 326, 31758, 4098, 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, 752, 55, 11256, 37, 4062, 12, 203, 3639, 2254, 5034, 389, 8691, 4098, 548, 16, 203, 3639, 2254, 5034, 389, 18526, 5147, 16, 203, 3639, 2254, 5034, 389, 2846, 5147, 16, 203, 3639, 2254, 5034, 389, 8760, 203, 565, 262, 203, 3639, 3903, 203, 3639, 1347, 1248, 28590, 203, 565, 288, 203, 3639, 2583, 24899, 995, 87, 12, 3576, 18, 15330, 16, 389, 8691, 4098, 548, 10019, 203, 3639, 2583, 12, 291, 8367, 774, 38, 15656, 24899, 8691, 4098, 548, 10019, 203, 3639, 389, 12908, 537, 24899, 8691, 4098, 548, 16, 272, 11256, 37, 4062, 1769, 203, 3639, 272, 11256, 37, 4062, 18, 2640, 37, 4062, 12, 203, 5411, 389, 8691, 4098, 548, 16, 203, 5411, 389, 18526, 5147, 16, 203, 5411, 389, 2846, 5147, 16, 203, 5411, 389, 8760, 16, 203, 5411, 1234, 18, 15330, 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 ]
pragma solidity ^0.6.0; contract initializable5 { //inject NONSTANDARD NAMING bool private initialized; bool private initializing; modifier INITIALIZER65() { //inject NONSTANDARD NAMING require(initializing || ISCONSTRUCTOR91() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } function ISCONSTRUCTOR91() private view returns (bool) { //inject NONSTANDARD NAMING // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } contract contextupgradesafe87 is initializable5 { //inject NONSTANDARD NAMING // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __CONTEXT_INIT10() internal INITIALIZER65 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED61(); } function __CONTEXT_INIT_UNCHAINED61() internal INITIALIZER65 { //inject NONSTANDARD NAMING } function _MSGSENDER78() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA22() 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; } uint256[50] private __gap; } contract ownableupgradesafe25 is initializable5, contextupgradesafe87 { //inject NONSTANDARD NAMING address private _owner; event OWNERSHIPTRANSFERRED52(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING function __OWNABLE_INIT13() internal INITIALIZER65 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED61(); __OWNABLE_INIT_UNCHAINED84(); } function __OWNABLE_INIT_UNCHAINED84() internal INITIALIZER65 { //inject NONSTANDARD NAMING address msgSender = _MSGSENDER78(); _owner = msgSender; emit OWNERSHIPTRANSFERRED52(address(0), msgSender); } function OWNER9() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER81() { //inject NONSTANDARD NAMING require(_owner == _MSGSENDER78(), "Ownable: caller is not the owner"); _; } function RENOUNCEOWNERSHIP19() public virtual ONLYOWNER81 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED52(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP24(address newOwner) public virtual ONLYOWNER81 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED52(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } library safemath14 { //inject NONSTANDARD NAMING function ADD80(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB60(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB60(a, b, "SafeMath: subtraction overflow"); } function SUB60(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 MUL16(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 DIV54(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV54(a, b, "SafeMath: division by zero"); } function DIV54(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD56(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD56(a, b, "SafeMath: modulo by zero"); } function MOD56(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } interface ierc2086 { //inject NONSTANDARD NAMING function TOTALSUPPLY25() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF21(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER6(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE84(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE33(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM54(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER56(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL90(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library console87 { //inject NONSTANDARD NAMING address constant console_address36 = address(0x000000000000000000636F6e736F6c652e6c6f67); //inject NONSTANDARD NAMING function _SENDLOGPAYLOAD51(bytes memory payload) private view { //inject NONSTANDARD NAMING uint256 payloadLength = payload.length; address consoleAddress = console_address36; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function LOG40() internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log()")); } function LOGINT64(int p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(int)", p0)); } function LOGUINT96(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint)", p0)); } function LOGSTRING94(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string)", p0)); } function LOGBOOL52(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool)", p0)); } function LOGADDRESS2(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address)", p0)); } function LOGBYTES0(bytes memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes)", p0)); } function LOGBYTE23(byte p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(byte)", p0)); } function LOGBYTES1100(bytes1 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes1)", p0)); } function LOGBYTES273(bytes2 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes2)", p0)); } function LOGBYTES377(bytes3 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes3)", p0)); } function LOGBYTES477(bytes4 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes4)", p0)); } function LOGBYTES578(bytes5 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes5)", p0)); } function LOGBYTES61(bytes6 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes6)", p0)); } function LOGBYTES735(bytes7 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes7)", p0)); } function LOGBYTES818(bytes8 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes8)", p0)); } function LOGBYTES931(bytes9 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes9)", p0)); } function LOGBYTES1064(bytes10 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes10)", p0)); } function LOGBYTES1141(bytes11 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes11)", p0)); } function LOGBYTES1261(bytes12 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes12)", p0)); } function LOGBYTES1365(bytes13 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes13)", p0)); } function LOGBYTES1433(bytes14 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes14)", p0)); } function LOGBYTES1532(bytes15 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes15)", p0)); } function LOGBYTES1678(bytes16 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes16)", p0)); } function LOGBYTES176(bytes17 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes17)", p0)); } function LOGBYTES1833(bytes18 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes18)", p0)); } function LOGBYTES1973(bytes19 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes19)", p0)); } function LOGBYTES202(bytes20 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes20)", p0)); } function LOGBYTES2137(bytes21 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes21)", p0)); } function LOGBYTES2248(bytes22 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes22)", p0)); } function LOGBYTES2317(bytes23 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes23)", p0)); } function LOGBYTES2438(bytes24 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes24)", p0)); } function LOGBYTES2548(bytes25 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes25)", p0)); } function LOGBYTES261(bytes26 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes26)", p0)); } function LOGBYTES2793(bytes27 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes27)", p0)); } function LOGBYTES2869(bytes28 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes28)", p0)); } function LOGBYTES299(bytes29 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes29)", p0)); } function LOGBYTES3053(bytes30 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes30)", p0)); } function LOGBYTES3139(bytes31 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes31)", p0)); } function LOGBYTES3263(bytes32 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes32)", p0)); } function LOG40(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint)", p0)); } function LOG40(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string)", p0)); } function LOG40(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool)", p0)); } function LOG40(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address)", p0)); } function LOG40(uint p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function LOG40(uint p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function LOG40(uint p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function LOG40(uint p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function LOG40(string memory p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function LOG40(string memory p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string)", p0, p1)); } function LOG40(string memory p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function LOG40(string memory p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address)", p0, p1)); } function LOG40(bool p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function LOG40(bool p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function LOG40(bool p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function LOG40(bool p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function LOG40(address p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function LOG40(address p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string)", p0, p1)); } function LOG40(address p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function LOG40(address p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address)", p0, p1)); } function LOG40(uint p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function LOG40(uint p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function LOG40(uint p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function LOG40(uint p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function LOG40(uint p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function LOG40(uint p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function LOG40(uint p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function LOG40(uint p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function LOG40(uint p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function LOG40(uint p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function LOG40(uint p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function LOG40(uint p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function LOG40(uint p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function LOG40(uint p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function LOG40(uint p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function LOG40(uint p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function LOG40(string memory p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function LOG40(string memory p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function LOG40(string memory p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function LOG40(string memory p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function LOG40(string memory p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function LOG40(string memory p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function LOG40(string memory p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function LOG40(string memory p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function LOG40(string memory p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function LOG40(string memory p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function LOG40(string memory p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function LOG40(string memory p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function LOG40(string memory p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function LOG40(string memory p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function LOG40(string memory p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function LOG40(string memory p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function LOG40(bool p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function LOG40(bool p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function LOG40(bool p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function LOG40(bool p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function LOG40(bool p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function LOG40(bool p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function LOG40(bool p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function LOG40(bool p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function LOG40(bool p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function LOG40(bool p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function LOG40(bool p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function LOG40(bool p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function LOG40(bool p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function LOG40(bool p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function LOG40(bool p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function LOG40(bool p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function LOG40(address p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function LOG40(address p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function LOG40(address p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function LOG40(address p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function LOG40(address p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function LOG40(address p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function LOG40(address p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function LOG40(address p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function LOG40(address p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function LOG40(address p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function LOG40(address p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function LOG40(address p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function LOG40(address p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function LOG40(address p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function LOG40(address p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function LOG40(address p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function LOG40(uint p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } interface iuniswapv2factory11 { //inject NONSTANDARD NAMING event PAIRCREATED16(address indexed token0, address indexed token1, address pair, uint); //inject NONSTANDARD NAMING function FEETO47() external view returns (address); //inject NONSTANDARD NAMING function FEETOSETTER62() external view returns (address); //inject NONSTANDARD NAMING function GETPAIR25(address tokenA, address tokenB) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRS78(uint) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRSLENGTH45() external view returns (uint); //inject NONSTANDARD NAMING function CREATEPAIR19(address tokenA, address tokenB) external returns (address pair); //inject NONSTANDARD NAMING function SETFEETO7(address) external; //inject NONSTANDARD NAMING function SETFEETOSETTER93(address) external; //inject NONSTANDARD NAMING } contract feeapprover21 is ownableupgradesafe25 { //inject NONSTANDARD NAMING using safemath14 for uint256; function INITIALIZE58( //inject NONSTANDARD NAMING address _NANOCOREAddress, address _WETHAddress, address _uniswapFactory ) public INITIALIZER65 { ownableupgradesafe25.__OWNABLE_INIT13(); nanocoreTokenAddress = _NANOCOREAddress; WETHAddress = _WETHAddress; tokenUniswapPair = iuniswapv2factory11(_uniswapFactory).GETPAIR25(WETHAddress,nanocoreTokenAddress); feePercentX100 = 15; paused = false; // We start paused until sync post LGE happens. } address tokenUniswapPair; iuniswapv2factory11 public uniswapFactory; address internal WETHAddress; address nanocoreTokenAddress; address nanocoreVaultAddress; uint8 public feePercentX100; // max 255 = 25.5% artificial clamp uint256 public lastTotalSupplyOfLPTokens; bool paused; // Pausing transfers of the token function SETPAUSED71(bool _pause) public ONLYOWNER81 { //inject NONSTANDARD NAMING paused = _pause; } function SETFEEMULTIPLIER40(uint8 _feeMultiplier) public ONLYOWNER81 { //inject NONSTANDARD NAMING feePercentX100 = _feeMultiplier; } function SETNANOCOREVAULTADDRESS89(address _nanocoreVaultAddress) public ONLYOWNER81 { //inject NONSTANDARD NAMING nanocoreVaultAddress = _nanocoreVaultAddress; } function SYNC99() public { //inject NONSTANDARD NAMING uint256 _LPSupplyOfPairTotal = ierc2086(tokenUniswapPair).TOTALSUPPLY25(); lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal; } function CALCULATEAMOUNTSAFTERFEE82( //inject NONSTANDARD NAMING address sender, address recipient, // unusued maybe use din future uint256 amount ) public returns (uint256 transferToAmount, uint256 transferToFeeDistributorAmount) { require(paused == false, "FEE APPROVER: Transfers Paused"); uint256 _LPSupplyOfPairTotal = ierc2086(tokenUniswapPair).TOTALSUPPLY25(); // console.log("sender is " , sender); // console.log("recipient is is " , recipient, 'pair is :', tokenUniswapPair); // console.log("Old LP supply", lastTotalSupplyOfLPTokens); // console.log("Current LP supply", _LPSupplyOfPairTotal); if(sender == tokenUniswapPair) require(lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal, "Liquidity withdrawals forbidden"); // console.log('Sender is pair' , sender == tokenUniswapPair); // console.log('lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal' , lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal); if(sender == nanocoreVaultAddress || sender == tokenUniswapPair ) { // Dont have a fee when nanocorevault is sending, or infinite loop console87.LOG40("Sending without fee"); // And when pair is sending ( buys are happening, no tax on it) transferToFeeDistributorAmount = 0; transferToAmount = amount; } else { console87.LOG40("Normal fee transfer"); transferToFeeDistributorAmount = amount.MUL16(feePercentX100).DIV54(1000); transferToAmount = amount.SUB60(transferToFeeDistributorAmount); } lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal; } }
inject NONSTANDARD NAMING
function LOG40(uint p0, bool p1, uint p2, uint p3) internal view {
1,018,992
[ 1, 22170, 18708, 882, 18264, 423, 2192, 1360, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 2018, 7132, 12, 11890, 293, 20, 16, 1426, 293, 21, 16, 2254, 293, 22, 16, 2254, 293, 23, 13, 2713, 1476, 288, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity >= 0.7.0; // metodos de alcance contract Visibilidad { uint internal billetera = 300; // agrega los mismas propiedades de private uint external billetera = 300; // agrega los mismas propiedades de public function x() public view returns(uint){ // se muestra, acceso a la informacion uint data = 9; return data; } function y() private view returns(uint){ // no se muestra, denegacion uint data = 9; return data; } }
no se muestra, denegacion
function y() private view returns(uint){
895,273
[ 1, 2135, 695, 312, 3610, 2033, 16, 5545, 1332, 19861, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 677, 1435, 3238, 1476, 1135, 12, 11890, 15329, 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 ]
/** *Submitted for verification at Etherscan.io on 2022-05-03 */ // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; /** * @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); } // OpenZeppelin Contracts v4.4.1 (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0x0D31a41c93e483a69E10D067e353A9C489962F67), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } pragma solidity ^0.8.10; contract RevoltToken is ERC20 { constructor( string memory name, string memory symbol, uint256 totalSupply_ ) ERC20(name, symbol) { _mint(msg.sender, totalSupply_); } }
* @dev Implementation of the {IERC20} interface. This implementation is agnostic to the way tokens are created. This means that a supply mechanism has to be added in a derived contract using {_mint}. For a generic mechanism see {ERC20PresetMinterPauser}. TIP: For a detailed writeup see our guide to implement supply mechanisms]. We have followed general OpenZeppelin Contracts guidelines: functions revert instead returning `false` on failure. This behavior is nonetheless conventional and does not conflict with the expectations of ERC20 applications. Additionally, an {Approval} event is emitted on calls to {transferFrom}. This allows applications to reconstruct the allowance for all accounts just by listening to said events. Other implementations of the EIP may not emit these events, as it isn't required by the specification. Finally, the non-standard {decreaseAllowance} and {increaseAllowance} functions have been added to mitigate the well-known issues around setting allowances. See {IERC20-approve}./
contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; } constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function decimals() public view virtual override returns (uint8) { return 18; } function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0x0D31a41c93e483a69E10D067e353A9C489962F67), account, amount); _afterTokenTransfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } 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); } ) internal virtual {} ) internal virtual {} }
2,268,838
[ 1, 13621, 434, 326, 288, 45, 654, 39, 3462, 97, 1560, 18, 1220, 4471, 353, 279, 1600, 669, 335, 358, 326, 4031, 2430, 854, 2522, 18, 1220, 4696, 716, 279, 14467, 12860, 711, 358, 506, 3096, 316, 279, 10379, 6835, 1450, 288, 67, 81, 474, 5496, 2457, 279, 5210, 12860, 2621, 288, 654, 39, 3462, 18385, 49, 2761, 16507, 1355, 5496, 399, 2579, 30, 2457, 279, 6864, 1045, 416, 2621, 3134, 7343, 358, 2348, 14467, 1791, 28757, 8009, 1660, 1240, 10860, 7470, 3502, 62, 881, 84, 292, 267, 30131, 9875, 14567, 30, 4186, 15226, 3560, 5785, 1375, 5743, 68, 603, 5166, 18, 1220, 6885, 353, 1661, 546, 12617, 15797, 287, 471, 1552, 486, 7546, 598, 326, 26305, 434, 4232, 39, 3462, 12165, 18, 26775, 16, 392, 288, 23461, 97, 871, 353, 17826, 603, 4097, 358, 288, 13866, 1265, 5496, 1220, 5360, 12165, 358, 23243, 326, 1699, 1359, 364, 777, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 4232, 39, 3462, 353, 1772, 16, 467, 654, 39, 3462, 16, 467, 654, 39, 3462, 2277, 288, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 203, 565, 2254, 5034, 3238, 389, 4963, 3088, 1283, 31, 203, 203, 565, 533, 3238, 389, 529, 31, 203, 565, 533, 3238, 389, 7175, 31, 203, 203, 97, 203, 203, 565, 3885, 12, 1080, 3778, 508, 67, 16, 533, 3778, 3273, 67, 13, 288, 203, 3639, 389, 529, 273, 508, 67, 31, 203, 3639, 389, 7175, 273, 3273, 67, 31, 203, 565, 289, 203, 203, 565, 445, 508, 1435, 1071, 1476, 5024, 3849, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 529, 31, 203, 565, 289, 203, 203, 565, 445, 3273, 1435, 1071, 1476, 5024, 3849, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 7175, 31, 203, 565, 289, 203, 203, 565, 445, 15105, 1435, 1071, 1476, 5024, 3849, 1135, 261, 11890, 28, 13, 288, 203, 3639, 327, 6549, 31, 203, 565, 289, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 1476, 5024, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 4963, 3088, 1283, 31, 203, 565, 289, 203, 203, 565, 445, 11013, 951, 12, 2867, 2236, 13, 1071, 1476, 5024, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 70, 26488, 63, 4631, 15533, 203, 565, 289, 203, 203, 565, 445, 2 ]
pragma solidity >0.5.4; /** * @title Abstract contract that holds all the data, * events and functions for staking contract. * The staking contract will inherit this interface */ contract AbstractGoodStaking { /** * @dev Structure to store staking details. * It contains amount of tokens staked and blocknumber at which last staked. */ struct Staker { uint256 stakedToken; uint256 lastStake; } /** * @dev Mapping to store staking details for each user. */ mapping(address => Staker) public stakers; /** * @dev Emitted when `staker` stake `value` tokens of `token` */ event Staked(address indexed staker, address token, uint256 value); /** * @dev Emitted when `staker` withdraws their stake `value` tokens and contracts balance will * be reduced to`remainingBalance`. */ event StakeWithdraw( address indexed staker, address token, uint256 value, uint256 remainingBalance ); /** * @dev Emitted when fundmanager transfers intrest collected from defi protrocol. * `recipient` will receive `intrestTokenValue` as intrest. */ event InterestCollected( address recipient, address token, address intrestToken, uint256 intrestTokenValue, uint256 tokenValue, uint256 tokenPrecisionLoss ); /** * @dev stake some tokens * @param amount of Tokens to stake */ function stake(uint256 amount) external {} /** * @dev withdraw staked tokens */ function withdrawStake() external {} /** * @dev calculates the holding of intrestToken by staking contract in terms of token value. * @return It will return the token worth of intrest token that contract is holding. */ function currentTokenWorth() external view returns (uint256) {} /** * @dev calculates the tokenGain, intrestTokenGain and precisionLossToken * @return Intrest gained on lending the tokens. * @return Intrest gained on lending the tokens in terms of token rate. * @return Token's precision loss due to decimal difference. */ function currentUBIInterest() external view returns ( uint256, uint256, uint256 ) {} /** * @dev collect gained interest by fundmanager * @param recipient of intrestToken gains * @return Intrest gained on lending the tokens. * @return Intrest gained on lending the tokens in terms of token rate. * @return Token's precision loss due to decimal difference. * @return average intrest donation ratio. */ function collectUBIInterest(address recipient) external returns ( uint256, uint256, uint256, uint32 ) {} /** * @dev Invests staked tokens to defi protocol. * @param amount tokens staked. */ function mint(uint256 amount) internal {} /** * @dev Redeem invested tokens from defi protocol. * @param amount tokens to be redeemed. */ function redeem(uint256 amount) internal {} /** * @dev Calculates exchange rate for token to intrest token from defi protocol. * @return exchange rate. */ function exchangeRate() internal view returns (uint256) {} /** * @dev Returns decimal value for token. */ function tokenDecimal() internal view returns (uint256) {} /** * @dev Returns decimal value for intrest token. */ function iTokenDecimal() internal view returns (uint256) {} }
* @title Abstract contract that holds all the data, events and functions for staking contract. The staking contract will inherit this interface/
contract AbstractGoodStaking { struct Staker { uint256 stakedToken; uint256 lastStake; } address indexed staker, address token, uint256 value, uint256 remainingBalance ); address recipient, address token, address intrestToken, uint256 intrestTokenValue, uint256 tokenValue, uint256 tokenPrecisionLoss ); mapping(address => Staker) public stakers; event Staked(address indexed staker, address token, uint256 value); event StakeWithdraw( event InterestCollected( function stake(uint256 amount) external {} function withdrawStake() external {} function currentTokenWorth() external view returns (uint256) {} {} {} function mint(uint256 amount) internal {} function redeem(uint256 amount) internal {} function exchangeRate() internal view returns (uint256) {} function tokenDecimal() internal view returns (uint256) {} function iTokenDecimal() internal view returns (uint256) {} }
12,562,764
[ 1, 7469, 6835, 716, 14798, 777, 326, 501, 16, 2641, 471, 4186, 364, 384, 6159, 6835, 18, 1021, 384, 6159, 6835, 903, 6811, 333, 1560, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 4115, 18195, 510, 6159, 288, 203, 565, 1958, 934, 6388, 288, 203, 3639, 2254, 5034, 384, 9477, 1345, 31, 203, 3639, 2254, 5034, 1142, 510, 911, 31, 203, 565, 289, 203, 203, 203, 203, 3639, 1758, 8808, 384, 6388, 16, 203, 3639, 1758, 1147, 16, 203, 3639, 2254, 5034, 460, 16, 203, 3639, 2254, 5034, 4463, 13937, 203, 565, 11272, 203, 203, 3639, 1758, 8027, 16, 203, 3639, 1758, 1147, 16, 203, 3639, 1758, 509, 8792, 1345, 16, 203, 3639, 2254, 5034, 509, 8792, 1345, 620, 16, 203, 3639, 2254, 5034, 1147, 620, 16, 203, 3639, 2254, 5034, 1147, 15410, 20527, 203, 565, 11272, 203, 203, 203, 203, 203, 565, 2874, 12, 2867, 516, 934, 6388, 13, 1071, 384, 581, 414, 31, 203, 565, 871, 934, 9477, 12, 2867, 8808, 384, 6388, 16, 1758, 1147, 16, 2254, 5034, 460, 1769, 203, 565, 871, 934, 911, 1190, 9446, 12, 203, 565, 871, 5294, 395, 10808, 329, 12, 203, 565, 445, 384, 911, 12, 11890, 5034, 3844, 13, 3903, 2618, 203, 565, 445, 598, 9446, 510, 911, 1435, 3903, 2618, 203, 565, 445, 23719, 59, 7825, 1435, 3903, 1476, 1135, 261, 11890, 5034, 13, 2618, 203, 565, 2618, 203, 565, 2618, 203, 565, 445, 312, 474, 12, 11890, 5034, 3844, 13, 2713, 2618, 203, 565, 445, 283, 24903, 12, 11890, 5034, 3844, 13, 2713, 2618, 203, 565, 445, 7829, 4727, 1435, 2713, 1476, 1135, 261, 11890, 5034, 13, 2618, 203, 565, 445, 1147, 5749, 1435, 2713, 1476, 1135, 261, 11890, 5034, 13, 2618, 203, 565, 2 ]
pragma solidity ^0.4.11; contract Combiner is Ownable, Addressed{ function Combiner(address _mainAddress) Addressed(_mainAddress) { } event Debug( string debug ); event DebugGas( uint gas ); event DebugPointer( bytes32 _pointer ); enum Mode { INIT, COUNTING, FEEDBACK, CALLBACK, DONE } // ------------------------ concurrence ---------------------------------- // mapping (bytes32 => bytes32 ) public concurrence; //agreed upon consensus mapping (bytes32 => uint256 ) public weight; //amount staked on concurrence mapping (bytes32 => uint256 ) public timestamp; //amount staked on concurrence // ------------------------ ----------- ---------------------------------- // //req id //result //amount of token mapping (bytes32 => mapping (bytes32 => uint256)) public staked; mapping (bytes32 => mapping (bytes32 => uint32)) public miners; //req id //current pointer mapping ( bytes32 => bytes32 ) public current; //req id //current mode mapping (bytes32 => Mode ) public mode; mapping (bytes32 => uint32 ) public correctMiners; mapping (bytes32 => uint256 ) public reward; //a combiner is "open" if it is open to new responses function open(bytes32 _request) public constant returns (bool) { if(mode[_request] != Mode.INIT) return false; return isCombinerOpen(_request); } //a combiner is "ready" if it is ready to combine function ready(bytes32 _request) public constant returns (bool) { if(mode[_request] == Mode.DONE) return false; if(mode[_request] != Mode.INIT) return true; return isCombinerReady(_request); } //the main combine function finds a consensus, rewards miners, and delivers result function combine(bytes32 _request) public returns (Mode) { if(mode[_request] == Mode.INIT){ initializeHead(_request); mode[_request] = Mode.COUNTING; } if(mode[_request] == Mode.COUNTING){ countResponses(_request); if( current[_request]==0 ){ mode[_request] = Mode.FEEDBACK; finalizeResponses(_request); } } if(mode[_request] == Mode.FEEDBACK && msg.gas>90000){ feedbackLoop(_request); if( current[_request]==0 ){ rewardCombinerMiner(_request); // TODO TRIGGER THE CALLBACK HERE // IT SHOULD SEND THE requestId, concurrence, weight, timestamp to the callback contract at function "concurrence" mode[_request] = Mode.CALLBACK; } } if(mode[_request] == Mode.CALLBACK && msg.gas>90000){ callback(_request); mode[_request] = Mode.DONE; } if(mode[_request] == Mode.DONE){ // TODO RESET THE RESPONSES HERE TOO // YOU NEED TO GO SET THE HEAD FOR THIS REQUEST ID TO 0x0 //correctMiners[_request] = 0; //reward[_request] = 0; //current[_request] = address(0); //mode[_request] = Mode.INIT; //instead let's just revert for now //revert(); } DebugPointer(current[_request]); return mode[_request]; } //------------Internal functions ------------------------- function isCombinerOpen(bytes32 _request) internal constant returns (bool) { //make sure that the request exists and there are tokens reserved for it Main mainContract = Main(mainAddress); Token tokenContract = Token(mainContract.getContract('Token')); Requests requestsContract = Requests(mainContract.getContract('Requests')); address requestCombiner = requestsContract.getCombiner(_request); if(requestCombiner==address(0)) return false; if(requestCombiner!=address(this)) return false; if(tokenContract.reserved(_request)<=0) return false; return true; } function isCombinerReady(bytes32 _request) internal constant returns (bool) { //make sure there is at least 1 token staked on at least 1 response to be ready to combine Main mainContract = Main(mainAddress); Token tokenContract = Token(mainContract.getContract('Token')); Responses responsesContract = Responses(mainContract.getContract('Responses')); bytes32 tmpCurrent = responsesContract.heads(_request); if(tmpCurrent==0) return false; uint256 tmpStaked = 0; address miner; bytes32 result; bytes32 next; while(tmpCurrent!=0) { (miner,result,next) = responsesContract.getResponse(tmpCurrent); tmpStaked += tokenContract.staked(miner,_request,tmpCurrent); tmpCurrent = next; } return (tmpStaked>0); } function initializeHead(bytes32 _request) internal { Debug("initializeHead"); DebugGas(msg.gas); Main mainContract = Main(mainAddress); Responses responsesContract = Responses(mainContract.getContract('Responses')); current[_request] = responsesContract.heads(_request); DebugPointer(current[_request]); } function countResponses(bytes32 _request) internal { Debug("countResponses start"); DebugGas(msg.gas); Main mainContract = Main(mainAddress); Token tokenContract = Token(mainContract.getContract('Token')); Responses responsesContract = Responses(mainContract.getContract('Responses')); address miner; bytes32 result; bytes32 next; //we want to drop out if gas is less than a safe amount to iterate again while(current[_request]!=0 && msg.gas>80000){ Debug("countResponses iteration"); DebugGas(msg.gas); (miner,result,next) = responsesContract.getResponse(current[_request]); //keep track of total staked amounts for all the different results staked[_request][result] += tokenContract.staked(miner,_request,current[_request]); miners[_request][result]++; //keep track of running best and how much is staked to it // use >= here to make it 'first come first serve' if(staked[_request][result] >= weight[_request]){ timestamp[_request] = block.timestamp; weight[_request] = staked[_request][result]; concurrence[_request] = result; correctMiners[_request] = miners[_request][result]; } current[_request] = next; } DebugPointer(current[_request]); } function feedbackLoop(bytes32 _request) internal { Debug("feedbackLoop start"); DebugGas(msg.gas); Main mainContract = Main(mainAddress); Token tokenContract = Token(mainContract.getContract('Token')); Responses responsesContract = Responses(mainContract.getContract('Responses')); address miner; bytes32 result; bytes32 next; //we want to drop out if gas is less than a safe amount to iterate again while(current[_request]!=0 && msg.gas>100000){ Debug("feedbackLoop iteration"); DebugGas(msg.gas); (miner,result,next) = responsesContract.getResponse(current[_request]); uint256 amountStaked; if( concurrence[_request] == result ){ //they got it right //return to them all of tokenContract.staked(miner,current[_request]); amountStaked = tokenContract.staked(miner,_request,current[_request]); if(amountStaked>0){ tokenContract.release(_request,current[_request],miner,amountStaked); //reward with their split of the bounty if( tokenContract.reserved(_request) >= reward[_request] ){ tokenContract.reward(_request,miner,reward[_request]); } } } else { //they got it wrong //take a 10th of what they staked tokenContract.staked(miner,current[_request]) //I guess this can go back to the owner for now //but eventually that should go somewhere better amountStaked = tokenContract.staked(miner,_request,current[_request]); uint256 punishment = amountStaked/10; if(punishment<1) punishment=1; amountStaked-=punishment; tokenContract.punish(_request,current[_request],miner,punishment,owner); tokenContract.release(_request,current[_request],miner,amountStaked); //return the remaining amount of tokenContract.staked(miner,current[_request]); to them } current[_request] = next; } DebugPointer(current[_request]); } function finalizeResponses(bytes32 _request) internal { Main mainContract = Main(mainAddress); Token tokenContract = Token(mainContract.getContract('Token')); Responses responsesContract = Responses(mainContract.getContract('Responses')); //determine the reward split uint32 rewardableMiners = correctMiners[_request]; //add a little on the top to incentivize miners to run the combine loop //this causes a little to be left over and the last miner to run combine // will be rewarded with the same bounty of the actual request/consensus rewardableMiners++; //set the reward by splitting up the reserved token by how many miners //responded to the request... a little game theory will apply here, //if a request is too heavily mined it's not worth much reward[_request] = tokenContract.reserved(_request)/rewardableMiners; if(reward[_request]<1) reward[_request]=1; //reset the pointer back to the head so we can iterate through again current[_request] = responsesContract.heads(_request); } function rewardCombinerMiner(bytes32 _request) internal { Main mainContract = Main(mainAddress); Token tokenContract = Token(mainContract.getContract('Token')); uint256 amountLeft = tokenContract.reserved(_request); if(amountLeft>0){ tokenContract.reward(_request,msg.sender,amountLeft); } } function callback(bytes32 _request) internal { Main mainContract = Main(mainAddress); Token tokenContract = Token(mainContract.getContract('Token')); Responses responsesContract = Responses(mainContract.getContract('Responses')); //determine the reward split uint32 rewardableMiners = correctMiners[_request]; //add a little on the top to incentivize miners to run the combine loop //this causes a little to be left over and the last miner to run combine // will be rewarded with the same bounty of the actual request/consensus rewardableMiners++; //set the reward by splitting up the reserved token by how many miners //responded to the request... a little game theory will apply here, //if a request is too heavily mined it's not worth much reward[_request] = tokenContract.reserved(_request)/rewardableMiners; if(reward[_request]<1) reward[_request]=1; //reset the pointer back to the head so we can iterate through again if we have some later mode //what will most likely happen is we move to the RESET mode and this is set back to address(0) current[_request] = responsesContract.heads(_request); } } contract Token { mapping (bytes32 => uint256) public reserved; mapping (address => mapping (bytes32 => mapping (bytes32 => uint256))) public staked; function balanceOf(address _owner) public constant returns (uint256 balance) { } function reward(bytes32 _request, address _miner, uint256 _value) public returns (bool) { } function release(bytes32 _request, bytes32 _response, address _miner, uint256 _value) public returns (bool) { } function punish(bytes32 _request, bytes32 _response, address _miner, uint256 _value, address _to) public returns (bool) { } } contract Responses{ mapping (bytes32 => bytes32) public heads; function getResponse(bytes32 id) public constant returns (address,bytes32,bytes32) { } } contract Requests { function getCombiner(bytes32 _id) public constant returns (address) { } function getCallback(bytes32 _id) public constant returns (address) { } } import 'zeppelin-solidity/contracts/ownership/Ownable.sol'; import 'Addressed.sol';
a combiner is "ready" if it is ready to combine
function ready(bytes32 _request) public constant returns (bool) { if(mode[_request] == Mode.DONE) return false; if(mode[_request] != Mode.INIT) return true; return isCombinerReady(_request); }
12,884,733
[ 1, 69, 3894, 14522, 353, 315, 1672, 6, 309, 518, 353, 5695, 358, 8661, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 225, 445, 5695, 12, 3890, 1578, 389, 2293, 13, 1071, 5381, 1135, 261, 6430, 13, 288, 203, 565, 309, 12, 3188, 63, 67, 2293, 65, 422, 8126, 18, 26875, 13, 327, 629, 31, 203, 565, 309, 12, 3188, 63, 67, 2293, 65, 480, 8126, 18, 12919, 13, 327, 638, 31, 203, 565, 327, 353, 24107, 264, 8367, 24899, 2293, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* solium-disable function-order */ pragma solidity 0.5.17; import {IBondedECDSAKeepFactory} from "@keep-network/keep-ecdsa/contracts/api/IBondedECDSAKeepFactory.sol"; import {VendingMachine} from "./VendingMachine.sol"; import {DepositFactory} from "../proxy/DepositFactory.sol"; import {IRelay} from "@summa-tx/relay-sol/contracts/Relay.sol"; import "../external/IMedianizer.sol"; import {ITBTCSystem} from "../interfaces/ITBTCSystem.sol"; import {ISatWeiPriceFeed} from "../interfaces/ISatWeiPriceFeed.sol"; import {DepositLog} from "../DepositLog.sol"; import {TBTCDepositToken} from "./TBTCDepositToken.sol"; import "./TBTCToken.sol"; import "./FeeRebateToken.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./KeepFactorySelection.sol"; /// @title TBTC System. /// @notice This contract acts as a central point for access control, /// value governance, and price feed. /// @dev Governable values should only affect new deposit creation. contract TBTCSystem is Ownable, ITBTCSystem, DepositLog { using SafeMath for uint256; using KeepFactorySelection for KeepFactorySelection.Storage; event EthBtcPriceFeedAdditionStarted(address _priceFeed, uint256 _timestamp); event LotSizesUpdateStarted(uint64[] _lotSizes, uint256 _timestamp); event SignerFeeDivisorUpdateStarted(uint16 _signerFeeDivisor, uint256 _timestamp); event CollateralizationThresholdsUpdateStarted( uint16 _initialCollateralizedPercent, uint16 _undercollateralizedThresholdPercent, uint16 _severelyUndercollateralizedThresholdPercent, uint256 _timestamp ); event KeepFactoriesUpdateStarted( address _keepStakedFactory, address _fullyBackedFactory, address _factorySelector, uint256 _timestamp ); event EthBtcPriceFeedAdded(address _priceFeed); event LotSizesUpdated(uint64[] _lotSizes); event AllowNewDepositsUpdated(bool _allowNewDeposits); event SignerFeeDivisorUpdated(uint16 _signerFeeDivisor); event CollateralizationThresholdsUpdated( uint16 _initialCollateralizedPercent, uint16 _undercollateralizedThresholdPercent, uint16 _severelyUndercollateralizedThresholdPercent ); event KeepFactoriesUpdated( address _keepStakedFactory, address _fullyBackedFactory, address _factorySelector ); uint256 initializedTimestamp = 0; uint256 pausedTimestamp; uint256 constant pausedDuration = 10 days; ISatWeiPriceFeed public priceFeed; IRelay public relay; KeepFactorySelection.Storage keepFactorySelection; uint16 public keepSize; uint16 public keepThreshold; // Parameters governed by the TBTCSystem owner bool private allowNewDeposits = false; uint16 private signerFeeDivisor = 2000; // 1/2000 == 5bps == 0.05% == 0.0005 uint16 private initialCollateralizedPercent = 150; // percent uint16 private undercollateralizedThresholdPercent = 125; // percent uint16 private severelyUndercollateralizedThresholdPercent = 110; // percent uint64[] lotSizesSatoshis = [10**6, 10**7, 2 * 10**7, 5 * 10**7, 10**8]; // [0.01, 0.1, 0.2, 0.5, 1.0] BTC uint256 constant governanceTimeDelay = 48 hours; uint256 constant keepFactoriesUpgradeabilityPeriod = 180 days; uint256 private signerFeeDivisorChangeInitiated; uint256 private lotSizesChangeInitiated; uint256 private collateralizationThresholdsChangeInitiated; uint256 private keepFactoriesUpdateInitiated; uint16 private newSignerFeeDivisor; uint64[] newLotSizesSatoshis; uint16 private newInitialCollateralizedPercent; uint16 private newUndercollateralizedThresholdPercent; uint16 private newSeverelyUndercollateralizedThresholdPercent; address private newKeepStakedFactory; address private newFullyBackedFactory; address private newFactorySelector; // price feed uint256 constant priceFeedGovernanceTimeDelay = 90 days; uint256 ethBtcPriceFeedAdditionInitiated; IMedianizer nextEthBtcPriceFeed; constructor(address _priceFeed, address _relay) public { priceFeed = ISatWeiPriceFeed(_priceFeed); relay = IRelay(_relay); } /// @notice Initialize contracts /// @dev Only the Deposit factory should call this, and only once. /// @param _defaultKeepFactory ECDSA keep factory backed by KEEP stake. /// @param _depositFactory Deposit Factory. More info in `DepositFactory`. /// @param _masterDepositAddress Master Deposit address. More info in `Deposit`. /// @param _tbtcToken TBTCToken. More info in `TBTCToken`. /// @param _tbtcDepositToken TBTCDepositToken (TDT). More info in `TBTCDepositToken`. /// @param _feeRebateToken FeeRebateToken (FRT). More info in `FeeRebateToken`. /// @param _keepThreshold Signing group honesty threshold. /// @param _keepSize Signing group size. function initialize( IBondedECDSAKeepFactory _defaultKeepFactory, DepositFactory _depositFactory, address payable _masterDepositAddress, TBTCToken _tbtcToken, TBTCDepositToken _tbtcDepositToken, FeeRebateToken _feeRebateToken, VendingMachine _vendingMachine, uint16 _keepThreshold, uint16 _keepSize ) external onlyOwner { require(initializedTimestamp == 0, "already initialized"); keepFactorySelection.initialize(_defaultKeepFactory); keepThreshold = _keepThreshold; keepSize = _keepSize; initializedTimestamp = block.timestamp; allowNewDeposits = true; setTbtcDepositToken(_tbtcDepositToken); _vendingMachine.setExternalAddresses( _tbtcToken, _tbtcDepositToken, _feeRebateToken ); _depositFactory.setExternalDependencies( _masterDepositAddress, this, _tbtcToken, _tbtcDepositToken, _feeRebateToken, address(_vendingMachine) ); } /// @notice Returns whether new deposits should be allowed. /// @return True if new deposits should be allowed by the emergency pause button function getAllowNewDeposits() external view returns (bool) { return allowNewDeposits; } /// @notice Return the lowest lot size currently enabled for deposits. /// @return The lowest lot size, in satoshis. function getMinimumLotSize() public view returns (uint256) { return lotSizesSatoshis[0]; } /// @notice Return the largest lot size currently enabled for deposits. /// @return The largest lot size, in satoshis. function getMaximumLotSize() external view returns (uint256) { return lotSizesSatoshis[lotSizesSatoshis.length - 1]; } /// @notice One-time-use emergency function to disallow future deposit creation for 10 days. function emergencyPauseNewDeposits() external onlyOwner { require(pausedTimestamp == 0, "emergencyPauseNewDeposits can only be called once"); uint256 sinceInit = block.timestamp - initializedTimestamp; require(sinceInit < 180 days, "emergencyPauseNewDeposits can only be called within 180 days of initialization"); pausedTimestamp = block.timestamp; allowNewDeposits = false; emit AllowNewDepositsUpdated(false); } /// @notice Anyone can reactivate deposit creations after the pause duration is over. function resumeNewDeposits() external { require(! allowNewDeposits, "New deposits are currently allowed"); require(pausedTimestamp != 0, "Deposit has not been paused"); require(block.timestamp.sub(pausedTimestamp) >= pausedDuration, "Deposits are still paused"); allowNewDeposits = true; emit AllowNewDepositsUpdated(true); } function getRemainingPauseTerm() external view returns (uint256) { require(! allowNewDeposits, "New deposits are currently allowed"); return (block.timestamp.sub(pausedTimestamp) >= pausedDuration)? 0: pausedDuration.sub(block.timestamp.sub(pausedTimestamp)); } /// @notice Set the system signer fee divisor. /// @dev This can be finalized by calling `finalizeSignerFeeDivisorUpdate` /// Anytime after `governanceTimeDelay` has elapsed. /// @param _signerFeeDivisor The signer fee divisor. function beginSignerFeeDivisorUpdate(uint16 _signerFeeDivisor) external onlyOwner { require( _signerFeeDivisor > 9, "Signer fee divisor must be greater than 9, for a signer fee that is <= 10%" ); require( _signerFeeDivisor < 5000, "Signer fee divisor must be less than 5000, for a signer fee that is > 0.02%" ); newSignerFeeDivisor = _signerFeeDivisor; signerFeeDivisorChangeInitiated = block.timestamp; emit SignerFeeDivisorUpdateStarted(_signerFeeDivisor, block.timestamp); } /// @notice Set the allowed deposit lot sizes. /// @dev Lot size array should always contain 10**8 satoshis (1 BTC) and /// cannot contain values less than 50000 satoshis (0.0005 BTC) or /// greater than 10**10 satoshis (100 BTC). Lot size array must not /// have duplicates and it must be sorted. /// This can be finalized by calling `finalizeLotSizesUpdate` /// anytime after `governanceTimeDelay` has elapsed. /// @param _lotSizes Array of allowed lot sizes. function beginLotSizesUpdate(uint64[] calldata _lotSizes) external onlyOwner { bool hasSingleBitcoin = false; for (uint i = 0; i < _lotSizes.length; i++) { if (_lotSizes[i] == 10**8) { hasSingleBitcoin = true; } else if (_lotSizes[i] < 50 * 10**3) { // Failed the minimum requirement, break on out. revert("Lot sizes less than 0.0005 BTC are not allowed"); } else if (_lotSizes[i] > 10 * 10**9) { // Failed the maximum requirement, break on out. revert("Lot sizes greater than 100 BTC are not allowed"); } else if (i > 0 && _lotSizes[i] == _lotSizes[i-1]) { revert("Lot size array must not have duplicates"); } else if (i > 0 && _lotSizes[i] < _lotSizes[i-1]) { revert("Lot size array must be sorted"); } } require(hasSingleBitcoin, "Lot size array must always contain 1 BTC"); emit LotSizesUpdateStarted(_lotSizes, block.timestamp); newLotSizesSatoshis = _lotSizes; lotSizesChangeInitiated = block.timestamp; } /// @notice Set the system collateralization levels /// @dev This can be finalized by calling `finalizeCollateralizationThresholdsUpdate` /// Anytime after `governanceTimeDelay` has elapsed. /// @param _initialCollateralizedPercent default signing bond percent for new deposits /// @param _undercollateralizedThresholdPercent first undercollateralization trigger /// @param _severelyUndercollateralizedThresholdPercent second undercollateralization trigger function beginCollateralizationThresholdsUpdate( uint16 _initialCollateralizedPercent, uint16 _undercollateralizedThresholdPercent, uint16 _severelyUndercollateralizedThresholdPercent ) external onlyOwner { require( _initialCollateralizedPercent <= 300, "Initial collateralized percent must be <= 300%" ); require( _initialCollateralizedPercent > 100, "Initial collateralized percent must be >= 100%" ); require( _initialCollateralizedPercent > _undercollateralizedThresholdPercent, "Undercollateralized threshold must be < initial collateralized percent" ); require( _undercollateralizedThresholdPercent > _severelyUndercollateralizedThresholdPercent, "Severe undercollateralized threshold must be < undercollateralized threshold" ); newInitialCollateralizedPercent = _initialCollateralizedPercent; newUndercollateralizedThresholdPercent = _undercollateralizedThresholdPercent; newSeverelyUndercollateralizedThresholdPercent = _severelyUndercollateralizedThresholdPercent; collateralizationThresholdsChangeInitiated = block.timestamp; emit CollateralizationThresholdsUpdateStarted( _initialCollateralizedPercent, _undercollateralizedThresholdPercent, _severelyUndercollateralizedThresholdPercent, block.timestamp ); } /// @notice Sets the addresses of the KEEP-staked ECDSA keep factory, /// ETH-only-backed ECDSA keep factory and the selection strategy /// that will choose between the two factories for new deposits. /// When the ETH-only-backed factory and strategy are not set TBTCSystem /// will use KEEP-staked factory. When both factories and strategy /// are set, TBTCSystem load balances between two factories based on /// the selection strategy. /// @dev It can be finalized by calling `finalizeKeepFactoriesUpdate` /// any time after `governanceTimeDelay` has elapsed. This can be /// called more than once until finalized to reset the values and /// timer. An update can only be initialized before /// `keepFactoriesUpgradeabilityPeriod` elapses after system initialization; /// after that, no further updates can be initialized, though any pending /// update can be finalized. All calls must set all three properties to /// their desired value; leaving a value as 0, even if it was previously /// set, will update that value to be 0. ETH-bond-only factory or the /// strategy are allowed to be set as zero addresses. /// @param _keepStakedFactory Address of the KEEP staked based factory. /// @param _fullyBackedFactory Address of the ETH-bond-only-based factory. /// @param _factorySelector Address of the keep factory selection strategy. function beginKeepFactoriesUpdate( address _keepStakedFactory, address _fullyBackedFactory, address _factorySelector ) external onlyOwner { uint256 sinceInit = block.timestamp - initializedTimestamp; require( sinceInit < keepFactoriesUpgradeabilityPeriod, "beginKeepFactoriesUpdate can only be called within 180 days of initialization" ); // It is required that KEEP staked factory address is configured as this is // a default choice factory. Fully backed factory and factory selector // are optional for the system to work, hence they don't have to be provided. require( _keepStakedFactory != address(0), "KEEP staked factory must be a nonzero address" ); newKeepStakedFactory = _keepStakedFactory; newFullyBackedFactory = _fullyBackedFactory; newFactorySelector = _factorySelector; keepFactoriesUpdateInitiated = block.timestamp; emit KeepFactoriesUpdateStarted( _keepStakedFactory, _fullyBackedFactory, _factorySelector, block.timestamp ); } /// @notice Add a new ETH/BTC price feed contract to the priecFeed. /// @dev This can be finalized by calling `finalizeEthBtcPriceFeedAddition` /// anytime after `priceFeedGovernanceTimeDelay` has elapsed. function beginEthBtcPriceFeedAddition(IMedianizer _ethBtcPriceFeed) external onlyOwner { bool ethBtcActive; (, ethBtcActive) = _ethBtcPriceFeed.peek(); require(ethBtcActive, "Cannot add inactive feed"); nextEthBtcPriceFeed = _ethBtcPriceFeed; ethBtcPriceFeedAdditionInitiated = block.timestamp; emit EthBtcPriceFeedAdditionStarted(address(_ethBtcPriceFeed), block.timestamp); } modifier onlyAfterGovernanceDelay( uint256 _changeInitializedTimestamp, uint256 _delay ) { require(_changeInitializedTimestamp > 0, "Change not initiated"); require( block.timestamp.sub(_changeInitializedTimestamp) >= _delay, "Governance delay has not elapsed" ); _; } /// @notice Finish setting the system signer fee divisor. /// @dev `beginSignerFeeDivisorUpdate` must be called first, once `governanceTimeDelay` /// has passed, this function can be called to set the signer fee divisor to the /// value set in `beginSignerFeeDivisorUpdate` function finalizeSignerFeeDivisorUpdate() external onlyOwner onlyAfterGovernanceDelay(signerFeeDivisorChangeInitiated, governanceTimeDelay) { signerFeeDivisor = newSignerFeeDivisor; emit SignerFeeDivisorUpdated(newSignerFeeDivisor); newSignerFeeDivisor = 0; signerFeeDivisorChangeInitiated = 0; } /// @notice Finish setting the accepted system lot sizes. /// @dev `beginLotSizesUpdate` must be called first, once `governanceTimeDelay` /// has passed, this function can be called to set the lot sizes to the /// value set in `beginLotSizesUpdate` function finalizeLotSizesUpdate() external onlyOwner onlyAfterGovernanceDelay(lotSizesChangeInitiated, governanceTimeDelay) { lotSizesSatoshis = newLotSizesSatoshis; emit LotSizesUpdated(newLotSizesSatoshis); lotSizesChangeInitiated = 0; newLotSizesSatoshis.length = 0; refreshMinimumBondableValue(); } /// @notice Finish setting the system collateralization levels /// @dev `beginCollateralizationThresholdsUpdate` must be called first, once `governanceTimeDelay` /// has passed, this function can be called to set the collateralization thresholds to the /// value set in `beginCollateralizationThresholdsUpdate` function finalizeCollateralizationThresholdsUpdate() external onlyOwner onlyAfterGovernanceDelay( collateralizationThresholdsChangeInitiated, governanceTimeDelay ) { initialCollateralizedPercent = newInitialCollateralizedPercent; undercollateralizedThresholdPercent = newUndercollateralizedThresholdPercent; severelyUndercollateralizedThresholdPercent = newSeverelyUndercollateralizedThresholdPercent; emit CollateralizationThresholdsUpdated( newInitialCollateralizedPercent, newUndercollateralizedThresholdPercent, newSeverelyUndercollateralizedThresholdPercent ); newInitialCollateralizedPercent = 0; newUndercollateralizedThresholdPercent = 0; newSeverelyUndercollateralizedThresholdPercent = 0; collateralizationThresholdsChangeInitiated = 0; } /// @notice Finish setting addresses of the KEEP-staked ECDSA keep factory, /// ETH-only-backed ECDSA keep factory, and the selection strategy /// that will choose between the two factories for new deposits. /// @dev `beginKeepFactoriesUpdate` must be called first; once /// `governanceTimeDelay` has passed, this function can be called to /// set factories addresses to the values set in `beginKeepFactoriesUpdate`. function finalizeKeepFactoriesUpdate() external onlyOwner onlyAfterGovernanceDelay( keepFactoriesUpdateInitiated, governanceTimeDelay ) { keepFactorySelection.setFactories( newKeepStakedFactory, newFullyBackedFactory, newFactorySelector ); emit KeepFactoriesUpdated( newKeepStakedFactory, newFullyBackedFactory, newFactorySelector ); keepFactoriesUpdateInitiated = 0; newKeepStakedFactory = address(0); newFullyBackedFactory = address(0); newFactorySelector = address(0); } /// @notice Finish adding a new price feed contract to the priceFeed. /// @dev `beginEthBtcPriceFeedAddition` must be called first; once /// `ethBtcPriceFeedAdditionInitiated` has passed, this function can be /// called to append a new price feed. function finalizeEthBtcPriceFeedAddition() external onlyOwner onlyAfterGovernanceDelay( ethBtcPriceFeedAdditionInitiated, priceFeedGovernanceTimeDelay ) { // This process interacts with external contracts, so // Checks-Effects-Interactions it. IMedianizer _nextEthBtcPriceFeed = nextEthBtcPriceFeed; nextEthBtcPriceFeed = IMedianizer(0); ethBtcPriceFeedAdditionInitiated = 0; emit EthBtcPriceFeedAdded(address(_nextEthBtcPriceFeed)); priceFeed.addEthBtcFeed(_nextEthBtcPriceFeed); } /// @notice Gets the system signer fee divisor. /// @return The signer fee divisor. function getSignerFeeDivisor() external view returns (uint16) { return signerFeeDivisor; } /// @notice Gets the allowed lot sizes /// @return Uint64 array of allowed lot sizes function getAllowedLotSizes() external view returns (uint64[] memory){ return lotSizesSatoshis; } /// @notice Get the system undercollateralization level for new deposits function getUndercollateralizedThresholdPercent() external view returns (uint16) { return undercollateralizedThresholdPercent; } /// @notice Get the system severe undercollateralization level for new deposits function getSeverelyUndercollateralizedThresholdPercent() external view returns (uint16) { return severelyUndercollateralizedThresholdPercent; } /// @notice Get the system initial collateralized level for new deposits. function getInitialCollateralizedPercent() external view returns (uint16) { return initialCollateralizedPercent; } /// @notice Get the price of one satoshi in wei. /// @dev Reverts if the price of one satoshi is 0 wei, or if the price of /// one satoshi is 1 ether. Can only be called by a deposit with minted /// TDT. /// @return The price of one satoshi in wei. function fetchBitcoinPrice() external view returns (uint256) { require( tbtcDepositToken.exists(uint256(msg.sender)), "Caller must be a Deposit contract" ); return _fetchBitcoinPrice(); } // Difficulty Oracle function fetchRelayCurrentDifficulty() external view returns (uint256) { return relay.getCurrentEpochDifficulty(); } function fetchRelayPreviousDifficulty() external view returns (uint256) { return relay.getPrevEpochDifficulty(); } /// @notice Get the time remaining until the signer fee divisor can be updated. function getRemainingSignerFeeDivisorUpdateTime() external view returns (uint256) { return getRemainingChangeTime( signerFeeDivisorChangeInitiated, governanceTimeDelay ); } /// @notice Get the time remaining until the lot sizes can be updated. function getRemainingLotSizesUpdateTime() external view returns (uint256) { return getRemainingChangeTime( lotSizesChangeInitiated, governanceTimeDelay ); } /// @notice Get the time remaining until the collateralization thresholds can be updated. function getRemainingCollateralizationThresholdsUpdateTime() external view returns (uint256) { return getRemainingChangeTime( collateralizationThresholdsChangeInitiated, governanceTimeDelay ); } /// @notice Get the time remaining until the Keep ETH-only-backed ECDSA keep /// factory and the selection strategy that will choose between it /// and the KEEP-backed factory can be updated. function getRemainingKeepFactoriesUpdateTime() external view returns (uint256) { return getRemainingChangeTime( keepFactoriesUpdateInitiated, governanceTimeDelay ); } /// @notice Get the time remaining until the signer fee divisor can be updated. function getRemainingEthBtcPriceFeedAdditionTime() external view returns (uint256) { return getRemainingChangeTime( ethBtcPriceFeedAdditionInitiated, priceFeedGovernanceTimeDelay ); } /// @notice Get the time remaining until Keep factories can no longer be updated. function getRemainingKeepFactoriesUpgradeabilityTime() external view returns (uint256) { return getRemainingChangeTime( initializedTimestamp, keepFactoriesUpgradeabilityPeriod ); } /// @notice Refreshes the minimum bondable value required from the operator /// to join the sortition pool for tBTC. The minimum bondable value is /// equal to the current minimum lot size collateralized 150% multiplied by /// the current BTC price. /// @dev It is recommended to call this function on tBTC initialization and /// after minimum lot size update. function refreshMinimumBondableValue() public { keepFactorySelection.setMinimumBondableValue( calculateBondRequirementWei(getMinimumLotSize()), keepSize, keepThreshold ); } /// @notice Returns the time delay used for governance actions except for /// price feed additions. function getGovernanceTimeDelay() external pure returns (uint256) { return governanceTimeDelay; } /// @notice Returns the time period when keep factories upgrades are allowed. function getKeepFactoriesUpgradeabilityPeriod() public pure returns (uint256) { return keepFactoriesUpgradeabilityPeriod; } /// @notice Returns the time delay used for price feed addition governance /// actions. function getPriceFeedGovernanceTimeDelay() external pure returns (uint256) { return priceFeedGovernanceTimeDelay; } /// @notice Gets a fee estimate for creating a new Deposit. /// @return Uint256 estimate. function getNewDepositFeeEstimate() external view returns (uint256) { IBondedECDSAKeepFactory _keepFactory = keepFactorySelection.selectFactory(); return _keepFactory.openKeepFeeEstimate(); } /// @notice Request a new keep opening. /// @param _requestedLotSizeSatoshis Lot size in satoshis. /// @param _maxSecuredLifetime Duration of stake lock in seconds. /// @return Address of a new keep. function requestNewKeep( uint64 _requestedLotSizeSatoshis, uint256 _maxSecuredLifetime ) external payable returns (address) { require(tbtcDepositToken.exists(uint256(msg.sender)), "Caller must be a Deposit contract"); require(isAllowedLotSize(_requestedLotSizeSatoshis), "provided lot size not supported"); IBondedECDSAKeepFactory _keepFactory = keepFactorySelection.selectFactoryAndRefresh(); uint256 bond = calculateBondRequirementWei(_requestedLotSizeSatoshis); return _keepFactory.openKeep.value(msg.value)(keepSize, keepThreshold, msg.sender, bond, _maxSecuredLifetime); } /// @notice Check if a lot size is allowed. /// @param _requestedLotSizeSatoshis Lot size to check. /// @return True if lot size is allowed, false otherwise. function isAllowedLotSize(uint64 _requestedLotSizeSatoshis) public view returns (bool){ for( uint i = 0; i < lotSizesSatoshis.length; i++){ if (lotSizesSatoshis[i] == _requestedLotSizeSatoshis){ return true; } } return false; } /// @notice Calculates bond requirement in wei for the given lot size in /// satoshis based on the current ETHBTC price. /// @param _requestedLotSizeSatoshis Lot size in satoshis. /// @return Bond requirement in wei. function calculateBondRequirementWei( uint256 _requestedLotSizeSatoshis ) internal view returns (uint256) { uint256 lotSizeInWei = _fetchBitcoinPrice().mul(_requestedLotSizeSatoshis); return lotSizeInWei.mul(initialCollateralizedPercent).div(100); } function _fetchBitcoinPrice() internal view returns (uint256) { uint256 price = priceFeed.getPrice(); if (price == 0 || price > 10 ** 18) { // This is if a sat is worth 0 wei, or is worth >1 ether. Revert at // once. revert("System returned a bad price"); } return price; } /// @notice Get the time remaining until the function parameter timer value can be updated. function getRemainingChangeTime( uint256 _changeTimestamp, uint256 _delayAmount ) internal view returns (uint256){ require(_changeTimestamp > 0, "Update not initiated"); uint256 elapsed = block.timestamp.sub(_changeTimestamp); if (elapsed >= _delayAmount) { return 0; } else { return _delayAmount.sub(elapsed); } } }
@notice Gets the allowed lot sizes @return Uint64 array of allowed lot sizes
function getAllowedLotSizes() external view returns (uint64[] memory){ return lotSizesSatoshis; }
1,057,843
[ 1, 3002, 326, 2935, 17417, 8453, 327, 7320, 1105, 526, 434, 2935, 17417, 8453, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 26898, 48, 352, 11923, 1435, 3903, 1476, 1135, 261, 11890, 1105, 8526, 3778, 15329, 203, 3639, 327, 17417, 11923, 15163, 17636, 291, 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 ]
// SPDX-License-Identifier: MIT import "./Cause.sol"; pragma solidity 0.5.16; /// @title Factory Contract for management of Cause Contract /// @author Ashutosh Singh Parmar /// @notice Enables to create Cause contract CauseFactory { /// @notice Status of Cause Factory /// @return true if Contract operations are allowed otherwise false. bool public IsEnable; /// @notice Owner of this Factory Contract /// @dev Owner will have admin privilages for this Contract /// @return Address of the Owner of this Contract address public Admin; address[] public Causes; mapping(address => address[]) public CreatorCauseMap; //Design Factory mapping(address => CauseStatus) public CauseStatusMap; //Design: Registry of Contract Status, https://medium.com/@i6mi6/solidty-smart-contracts-design-patterns-ecfa3b1e9784 constructor() public { Admin = msg.sender; IsEnable = true; } /// @notice Structure to hold Cause status struct CauseStatus { bool Exists; bool Active; } /// @notice Event emitted when a cause is created /// @param creator Account Address which created the Cause /// @param cause Address of the newly created Cause /// @param title Title of the newly created Cause event CauseCreated(address indexed creator, address cause, string title); modifier isAdmin() { require(msg.sender == Admin, "Only admin is allowed to execute this operation."); _; } modifier isContractEnabled() { require(IsEnable, "Contract is disabled. No operation allowed."); _; } /// @notice Toggles the status of the Factory. Operations are allowed only when its enabled. Circuit breaker pattern. function ToggleContractStatus() external isAdmin { IsEnable = !IsEnable; //Design: Circuit Breaker Pattern } /// @notice Creates a new Cause with the provided parameters and emits an Event /// @param title Title for Cause /// @param detail A brief detail about Cause /// @param targetAmount Target Amount for Cause /// @param startTime Start Time for Cause /// @param endTime End Time for Cause function CreateCause(string memory title, string memory detail, uint targetAmount, uint startTime, uint endTime) public isContractEnabled { Cause causeInstance = new Cause(title, detail, targetAmount, startTime, endTime, msg.sender); Causes.push(address(causeInstance)); CreatorCauseMap[msg.sender].push(address(causeInstance)); CauseStatusMap[address(causeInstance)].Exists = true; CauseStatusMap[address(causeInstance)].Active = true; emit CauseCreated(msg.sender, address(causeInstance), title); } /// @notice Gets all the Cause Contract Addresses created by supplied Creator /// @param creator Account Address which created Causes /// @return causeAddresses Cause Contract Addresses created by Creator function GetCauses(address creator) public view returns(address[] memory causeAddresses) { return CreatorCauseMap[creator]; } /// @notice Gets all the Cause Contract Addresses created by supplied Creator /// @return causeAddresses All the Cause Contract Addresses created till now function GetAllCauses() public view returns(address[] memory causeAddresses) { return Causes; } //TODO: Provide Operation Mark Contract InActive, it will be called once fund has been withdrawn from the Contract successfully //TODO: Provide Operation to get Cause Status }
@notice Structure to hold Cause status
struct CauseStatus { bool Exists; bool Active; }
15,796,171
[ 1, 6999, 358, 6887, 21389, 1267, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1958, 21389, 1482, 288, 203, 3639, 1426, 17277, 31, 203, 3639, 1426, 8857, 31, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); function decimals() external view returns (uint8); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * Returns the address of the current owner. */ function governance() public view returns (address) { return _owner; } /** * Throws if called by any account other than the owner. */ modifier onlyGovernance() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferGovernance(address newOwner) internal virtual onlyGovernance { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: contracts/ReethMonetaryPolicyV2.sol pragma solidity =0.6.6; // This monetary policy controls the rebase mechanism in the reeth token // Rebase can only be called once a day by a non-contract // To incentivize rebase, the policy will mint reeth to the delegatecaller equal to up to the fast gas price (determined by Chainlink) // There is an absolute max price however interface PriceOracle { function getLatestREETHPrice() external view returns (uint256); function updateREETHPrice() external; // Update price oracle upon every token transfer function mainLiquidity() external view returns (address); // Returns address of REETH/ETH LP pair } interface AggregatorV3Interface { function latestRoundData() external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound); } interface UniswapLikeLPToken { function sync() external; // Call sync right after rebase call } interface ReethToken { function mint(address, uint256) external returns (bool); function isRebaseable() external view returns (bool); function reethScalingFactor() external view returns (uint256); function maxScalingFactor() external view returns (uint256); function rebase(uint256 _price, uint256 _indexDelta, bool _positive) external returns (uint256); // Epoch is stored in the token } contract ReethMonetaryPolicyV2 is Ownable, ReentrancyGuard { // Adopted from YamRebaserV2 using SafeMath for uint256; /// @notice an event emitted when deviationThreshold is changed event NewDeviationThreshold(uint256 oldDeviationThreshold, uint256 newDeviationThreshold); /// @notice Spreads out getting to the target price uint256 public rebaseLag; /// @notice Peg target uint256 public targetRate; // If the current exchange rate is within this fractional distance from the target, no supply // update is performed. Fixed point number--same format as the rate. // (ie) abs(rate - targetRate) / targetRate < deviationThreshold, then no supply change. uint256 public deviationThreshold; /// @notice More than this much time must pass between rebase operations. uint256 public minRebaseTimeIntervalSec; /// @notice Block timestamp of last rebase operation uint256 public lastRebaseTimestampSec; /// @notice The rebase window begins this many seconds into the minRebaseTimeInterval period. // For example if minRebaseTimeInterval is 24hrs, it represents the time of day in seconds. uint256 public rebaseWindowOffsetSec; /// @notice The length of the time window where a rebase operation is allowed to execute, in seconds. uint256 public rebaseWindowLengthSec; /// @notice The number of rebase cycles since inception uint256 public epoch; /// @notice Reeth token address address public reethAddress; // price oracle address address public reethPriceOracle; /// @notice list of uniswap like pairs to sync address[] public uniSyncPairs; // Used for division scaling math uint256 constant BASE = 1e18; address constant GAS_ORACLE_ADDRESS = address(0x169E633A2D1E6c10dD91238Ba11c4A708dfEF37C); // Chainlink address for fast gas oracle // Gas price maximum uint256 public maxGasPrice = 200000000000; // 200 Gwei uint256 public callerBonus = 5000; // Rebase caller gets a initial bonus of 5% event RebaseMint(uint256 _gasCost, uint256 _reethMinted, address _receiver); constructor( address _reethAddress, address _priceOracle ) public { reethAddress = _reethAddress; reethPriceOracle = _priceOracle; minRebaseTimeIntervalSec = 1 days; rebaseWindowOffsetSec = 12 hours; // 12:00 UTC rebase // 1 REETH = 1 ETH targetRate = BASE; // once daily rebase, with targeting reaching peg in 10 days rebaseLag = 10; // 5% deviationThreshold = 5 * 10**16; // 60 minutes rebaseWindowLengthSec = 1 hours; } // This is an optional function that is ran anytime a reeth transfer is made function reethTransferActions() external { require(_msgSender() == reethAddress, "Not sent from REETH token"); // We are running the price oracle update if(reethPriceOracle != address(0)){ PriceOracle oracle = PriceOracle(reethPriceOracle); oracle.updateREETHPrice(); // Update the price of reeth } } // Rebase function /** * @notice Initiates a new rebase operation, provided the minimum time period has elapsed. * * @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag * Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate * and targetRate is 1e18 */ // Users can give their gas spent to another user if they choose to (in case of bot calls) function rebase(address _delegateCaller) public { // Users will be recognized for 1.5x the eth they spend when using this oracle uint256 gasUsed = gasleft(); // Start calculate gas spent // EOA only or gov require(_msgSender() == tx.origin || _msgSender() == governance(), "Contract call not allowed unless governance"); // ensure rebasing at correct time require(inRebaseWindow() == true, "Not in rebase window"); // This comparison also ensures there is no reentrancy. require(lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) < now, "Call already executed for this epoch"); // Snap the rebase time to the start of this window. lastRebaseTimestampSec = now.sub( now.mod(minRebaseTimeIntervalSec)).add(rebaseWindowOffsetSec); PriceOracle oracle = PriceOracle(reethPriceOracle); oracle.updateREETHPrice(); // Update the price of reeth uint256 exchangeRate = oracle.getLatestREETHPrice(); require(exchangeRate > 0, "Bad oracle price"); // calculates % change to supply (uint256 offPegPerc, bool positive) = computeOffPegPerc(exchangeRate); uint256 indexDelta = offPegPerc; // Apply the Dampening factor. indexDelta = indexDelta.div(rebaseLag); ReethToken reeth = ReethToken(reethAddress); if (positive) { require(reeth.reethScalingFactor().mul(BASE.add(indexDelta)).div(BASE) < reeth.maxScalingFactor(), "new scaling factor will be too big"); } // rebase the token reeth.rebase(exchangeRate, indexDelta, positive); // sync the pools { // first sync the main pool address mainLP = oracle.mainLiquidity(); UniswapLikeLPToken lp = UniswapLikeLPToken(mainLP); lp.sync(); // Sync this pool post rebase // And any additional pairs to sync for(uint256 i = 0; i < uniSyncPairs.length; i++){ lp = UniswapLikeLPToken(uniSyncPairs[i]); lp.sync(); } } // Determine what gas price to use when minting reeth // We do this instead of updating the spent ETH oracle to incentivize calling rebase uint256 gasPrice = tx.gasprice; { uint256 fastPrice = getFastGasPrice(); if(gasPrice > fastPrice){ gasPrice = fastPrice; } if(gasPrice > maxGasPrice){ gasPrice = maxGasPrice; } } if(_delegateCaller == address(0)){ _delegateCaller = _msgSender(); } gasUsed = gasUsed.sub(gasleft()).mul(gasPrice).mul(100000 + callerBonus).div(100000); // The amount of ETH reimbursed for this transaction with bonus // Convert ETH units to REETH units and mint to delegated caller uint256 reethReturn = gasUsed.mul(10**uint256(IERC20(reethAddress).decimals())).div(1e18); reethReturn = reethReturn.mul(1e18).div(exchangeRate); if(reethReturn > 0){ reeth.mint(_delegateCaller, reethReturn); emit RebaseMint(gasUsed, reethReturn, _delegateCaller); } } /** * @return If the latest block timestamp is within the rebase time window it, returns true. * Otherwise, returns false. */ function inRebaseWindow() public view returns (bool) { // First check if reeth token is active for rebasing if(ReethToken(reethAddress).isRebaseable() == false){return false;} return (block.timestamp.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec && block.timestamp.mod(minRebaseTimeIntervalSec) < (rebaseWindowOffsetSec.add(rebaseWindowLengthSec))); } /** * @return Computes in % how far off market is from peg */ function computeOffPegPerc(uint256 rate) private view returns (uint256, bool) { if (withinDeviationThreshold(rate)) { return (0, false); } // indexDelta = (rate - targetRate) / targetRate if (rate > targetRate) { return (rate.sub(targetRate).mul(BASE).div(targetRate), true); } else { return (targetRate.sub(rate).mul(BASE).div(targetRate), false); } } /** * @param rate The current exchange rate, an 18 decimal fixed point number. * @return If the rate is within the deviation threshold from the target rate, returns true. * Otherwise, returns false. */ function withinDeviationThreshold(uint256 rate) private view returns (bool) { uint256 absoluteDeviationThreshold = targetRate.mul(deviationThreshold) .div(10 ** 18); return (rate >= targetRate && rate.sub(targetRate) < absoluteDeviationThreshold) || (rate < targetRate && targetRate.sub(rate) < absoluteDeviationThreshold); } function getFastGasPrice() public view returns (uint256) { AggregatorV3Interface gasOracle = AggregatorV3Interface(GAS_ORACLE_ADDRESS); ( , int intGasPrice, , , ) = gasOracle.latestRoundData(); // We only want the answer return uint256(intGasPrice); } // Governance only functions // Timelock variables uint256 private _timelockStart; // The start of the timelock to change governance variables uint256 private _timelockType; // The function that needs to be changed uint256 constant TIMELOCK_DURATION = 86400; // Timelock is 24 hours // Reusable timelock variables address private _timelock_address; uint256[3] private _timelock_data; modifier timelockConditionsMet(uint256 _type) { require(_timelockType == _type, "Timelock not acquired for this function"); _timelockType = 0; // Reset the type once the timelock is used require(now >= _timelockStart + TIMELOCK_DURATION, "Timelock time not met"); _; } // Change the owner of the token contract // -------------------- function startGovernanceChange(address _address) external onlyGovernance { _timelockStart = now; _timelockType = 1; _timelock_address = _address; } function finishGovernanceChange() external onlyGovernance timelockConditionsMet(1) { transferGovernance(_timelock_address); } // -------------------- // Add to the synced pairs // -------------------- function startAddSyncPair(address _address) external onlyGovernance { _timelockStart = now; _timelockType = 2; _timelock_address = _address; } function finishAddSyncPair() external onlyGovernance timelockConditionsMet(2) { uniSyncPairs.push(_timelock_address); } // -------------------- // Remove from synced pairs // -------------------- function startRemoveSyncPair(address _address) external onlyGovernance { _timelockStart = now; _timelockType = 3; _timelock_address = _address; } function finishRemoveSyncPair() external onlyGovernance timelockConditionsMet(3) { uint256 length = uniSyncPairs.length; for(uint256 i = 0; i < length; i++){ if(uniSyncPairs[i] == _timelock_address){ for(uint256 i2 = i; i2 < length-1; i2++){ uniSyncPairs[i2] =uniSyncPairs[i2 + 1]; // Shift the data down one } uniSyncPairs.pop(); //Remove last element break; } } } // -------------------- // Change the deviation threshold // -------------------- function startChangeDeviationThreshold(uint256 _threshold) external onlyGovernance { require(_threshold > 0); _timelockStart = now; _timelockType = 4; _timelock_data[0] = _threshold; } function finishChangeDeviationThreshold() external onlyGovernance timelockConditionsMet(4) { deviationThreshold = _timelock_data[0]; } // -------------------- // Change the rebase lag // -------------------- function startChangeRebaseLag(uint256 _lag) external onlyGovernance { require(_lag > 1); _timelockStart = now; _timelockType = 5; _timelock_data[0] = _lag; } function finishChangeRebaseLag() external onlyGovernance timelockConditionsMet(5) { rebaseLag = _timelock_data[0]; } // -------------------- // Change the target rate // -------------------- function startChangeTargetRate(uint256 _rate) external onlyGovernance { require(_rate > 0); _timelockStart = now; _timelockType = 6; _timelock_data[0] = _rate; } function finishChangeTargetRate() external onlyGovernance timelockConditionsMet(6) { targetRate = _timelock_data[0]; } // -------------------- // Change the rebase times // -------------------- function startChangeRebaseTimes(uint256 _UTCOffset, uint256 _windowLength, uint256 _frequency) external onlyGovernance { require(_frequency > 0); require(_UTCOffset < _frequency); require(_UTCOffset + _windowLength < _frequency); _timelockStart = now; _timelockType = 7; _timelock_data[0] = _UTCOffset; _timelock_data[1] = _windowLength; _timelock_data[2] = _frequency; } function finishChangeRebaseTimes() external onlyGovernance timelockConditionsMet(7) { rebaseWindowOffsetSec = _timelock_data[0]; rebaseWindowLengthSec = _timelock_data[1]; minRebaseTimeIntervalSec = _timelock_data[2]; } // -------------------- // Change the max gas allowed // -------------------- function startChangeMaxGasPrice(uint256 _gas) external onlyGovernance { _timelockStart = now; _timelockType = 8; _timelock_data[0] = _gas; } function finishChangeMaxGasPrice() external onlyGovernance timelockConditionsMet(8) { maxGasPrice = _timelock_data[0]; } // -------------------- // Change the caller bonus // -------------------- function startChangeCallerBonus(uint256 _bonus) external onlyGovernance { require(_bonus < 100000, "Bonus is too high"); _timelockStart = now; _timelockType = 9; _timelock_data[0] = _bonus; } function finishChangeCallerBonus() external onlyGovernance timelockConditionsMet(9) { callerBonus = _timelock_data[0]; } // -------------------- }
Start calculate gas spent
uint256 gasUsed = gasleft();
13,387,892
[ 1, 1685, 4604, 16189, 26515, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 16189, 6668, 273, 16189, 4482, 5621, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x18FAbC40661863AAB0aebc861F2CcC2f49732F19/sources/Inferno.sol
_mint(msg.sender, _totalSupply);
constructor() public payable ERC20Detailed(tokenName, tokenSymbol, tokenDecimals) { admin = msg.sender; }
3,701,328
[ 1, 67, 81, 474, 12, 3576, 18, 15330, 16, 389, 4963, 3088, 1283, 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, 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, 225, 3885, 1435, 1071, 8843, 429, 4232, 39, 3462, 40, 6372, 12, 2316, 461, 16, 1147, 5335, 16, 1147, 31809, 13, 288, 203, 565, 3981, 273, 1234, 18, 15330, 31, 203, 225, 289, 203, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/56/0xbe6878b6A8278DB96181900b444638e53DeBfc75/sources/MxxConverterRedemption.sol
* @dev - An mapping for all redemption details./
mapping(uint256 => RedeemRecord) public allRedemptions;
11,108,710
[ 1, 17, 1922, 2874, 364, 777, 283, 19117, 375, 3189, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 2874, 12, 11890, 5034, 516, 868, 24903, 2115, 13, 1071, 777, 426, 19117, 573, 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 ]
// SPDX-License-Identifier: MIT // // BBBBBBBBBBBBBBBBB UUUUUUUU UUUUUUUUMMMMMMMM MMMMMMMM NNNNNNNN NNNNNNNN // B::::::::::::::::B U::::::U U::::::UM:::::::M M:::::::M N:::::::N N::::::N // B::::::BBBBBB:::::B U::::::U U::::::UM::::::::M M::::::::M N::::::::N N::::::N // BB:::::B B:::::BUU:::::U U:::::UUM:::::::::M M:::::::::M N:::::::::N N::::::N // B::::B B:::::B U:::::U U:::::U M::::::::::M M::::::::::M ooooooooooo ooooooooooo N::::::::::N N::::::N // B::::B B:::::B U:::::D D:::::U M:::::::::::M M:::::::::::M oo:::::::::::oo oo:::::::::::oo N:::::::::::N N::::::N // B::::BBBBBB:::::B U:::::D D:::::U M:::::::M::::M M::::M:::::::Mo:::::::::::::::oo:::::::::::::::oN:::::::N::::N N::::::N // B:::::::::::::BB U:::::D D:::::U M::::::M M::::M M::::M M::::::Mo:::::ooooo:::::oo:::::ooooo:::::oN::::::N N::::N N::::::N // B::::BBBBBB:::::B U:::::D D:::::U M::::::M M::::M::::M M::::::Mo::::o o::::oo::::o o::::oN::::::N N::::N:::::::N // B::::B B:::::B U:::::D D:::::U M::::::M M:::::::M M::::::Mo::::o o::::oo::::o o::::oN::::::N N:::::::::::N // B::::B B:::::B U:::::D D:::::U M::::::M M:::::M M::::::Mo::::o o::::oo::::o o::::oN::::::N N::::::::::N // B::::B B:::::B U::::::U U::::::U M::::::M MMMMM M::::::Mo::::o o::::oo::::o o::::oN::::::N N:::::::::N // BB:::::BBBBBB::::::B U:::::::UUU:::::::U M::::::M M::::::Mo:::::ooooo:::::oo:::::ooooo:::::oN::::::N N::::::::N // B:::::::::::::::::B UU:::::::::::::UU M::::::M M::::::Mo:::::::::::::::oo:::::::::::::::oN::::::N N:::::::N // B::::::::::::::::B UU:::::::::UU M::::::M M::::::M oo:::::::::::oo oo:::::::::::oo N::::::N N::::::N // BBBBBBBBBBBBBBBBB UUUUUUUUU MMMMMMMM MMMMMMMM ooooooooooo ooooooooooo NNNNNNNN NNNNNNN // // © 2021 BUMooN.io // BUMooN Contracts Core // Copyright © 2021 BUMooN.io // 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. // <======== TAX 10% ========> // 5% to liquidity pool, // 5% redistribute to all holders, // Max Tx 2% from total supp = 20 trillion, every 2 billion coin temp threshold then auto add LP and LOCKED for fastest growth // <=========================> pragma solidity ^0.7.6; library Address { function isContract(address account) internal view returns (bool) { bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; bytes32 codehash; assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue( address target, bytes memory data, uint256 weiValue, string memory errorMessage ) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: weiValue}(data); if (success) { return returndata; } else { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; return msg.data; } } interface IBEP20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract Ownable is Context { address private _owner; address private _previousOwner; uint256 private _lockTime; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } function getUnlockTime() public view returns (uint256) { return _lockTime; } //Locks the contract for owner for the amount of time provided function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = 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 specific time" ); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; } } interface IPancakeRouter01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountToken, uint256 amountETH); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } interface IPancakeRouter02 is IPancakeRouter01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } interface IPancakeSwapV2Factory { event PairCreated( address indexed token0, address indexed token1, address pair, uint256 ); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IPancakeSwapV2Pair { event Approval( address indexed owner, address indexed spender, uint256 value ); event Transfer(address indexed from, address indexed to, uint256 value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 value ) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint256); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; event Mint(address indexed sender, uint256 amount0, uint256 amount1); event Burn( address indexed sender, uint256 amount0, uint256 amount1, address indexed to ); event Swap( address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint256); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns ( uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast ); function price0CumulativeLast() external view returns (uint256); function price1CumulativeLast() external view returns (uint256); function kLast() external view returns (uint256); function mint(address to) external returns (uint256 liquidity); function burn(address to) external returns (uint256 amount0, uint256 amount1); function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } contract Bumoon is Context, IBEP20, Ownable { using SafeMath for uint256; using Address for address; IPancakeRouter02 public PancakeSwapV2Router; address public PancakeSwapV2Pair; IPancakeSwapV2Factory factory; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => uint256) private _balances; mapping(address => bool) private _isExcludedFromFee; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcluded; address[] private _excluded; uint256 public _taxFee = 5; uint256 public _liquidityFee = 5; uint256 private _previousLiquidityFee = _liquidityFee; uint256 private _previousTaxFee = _taxFee; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 1 * 10**9 * 10**6 * 10**9; //uint256 private ttotalinit = 1 * 10**9 * 10**6 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); address public constant BURN_ADDRESS = 0x0000000000000000000000000000000000000000; uint256 private _tFeeTotal; uint256 private _rBurnTotal; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; string private _name = "BUMooN"; string private _symbol = "BUMN"; uint8 private _decimals = 9; uint256 private numTokensSellToAddToLiquidity = 2 * 10**9 * 10**9; //threshold uint256 public _maxTxAmount = 2 * 10**13 * 10**9; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor() { _rOwned[_msgSender()] = _rTotal; IPancakeRouter02 _pancakeswapV2Router = IPancakeRouter02(0x10ED43C718714eb63d5aA57B78B54704E256024E); PancakeSwapV2Pair = IPancakeSwapV2Factory( _pancakeswapV2Router.factory() ) .createPair(address(this), _pancakeswapV2Router.WETH()); factory = IPancakeSwapV2Factory(_pancakeswapV2Router.factory()); PancakeSwapV2Router = _pancakeswapV2Router; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), _msgSender(), _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 totalSupplyReflect() public view returns (uint256) { return _rTotal; } 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 entrancyGuard() 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 isExcluded(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function totalSoftBurn() public view returns (uint256) { return _rBurnTotal; } function reflect(uint256 tAmount) public onlyOwner { 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); _rBurnTotal = _rBurnTotal.add(rAmount); } 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 excludeAccount(address account) external onlyOwner() { require(!_isExcluded[account], "Account is already excluded"); if (_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeAccount(address account) external onlyOwner() { require(_isExcluded[account], "Account is already included"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _approve( address owner, address spender, uint256 amount ) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address sender, address recipient, uint256 amount ) private { require(sender != address(0), "ERC20: transfer from the zero address"); //require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (sender != owner()) require( amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount." ); uint256 contractTokenBalance = balanceOf(address(this)); if (contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && sender != PancakeSwapV2Pair && swapAndLiquifyEnabled ) { contractTokenBalance = numTokensSellToAddToLiquidity; swapAndLiquify(contractTokenBalance); } bool takeFee = true; if (_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]) { takeFee = false; } _tokenTransfer(sender, recipient, amount, takeFee); } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { uint256 half = contractTokenBalance.div(2); uint256 otherHalf = contractTokenBalance.sub(half); uint256 initialBalance = address(this).balance; swapTokensForBnb(half); uint256 newBalance = address(this).balance.sub(initialBalance); // add half for liquidity to pancake addLiquidity(otherHalf, newBalance); emit SwapAndLiquify(half, newBalance, otherHalf); } function swapTokensForBnb(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = PancakeSwapV2Router.WETH(); _approve(address(this), address(PancakeSwapV2Router), tokenAmount); PancakeSwapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(PancakeSwapV2Router), tokenAmount); //add the liquidity PancakeSwapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, 0, owner(), block.timestamp ); } function _tokenTransfer( address sender, address recipient, uint256 amount, bool takeFee ) private { if (!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if (!takeFee) restoreAllFee(); } function removeAllFee() private { if (_taxFee == 0) return; _previousTaxFee = _taxFee; _taxFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; } function _transferBothExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferStandard( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _rBurnTotal = _rBurnTotal.add(rFee); //ttotalinit = ttotalinit.sub(tFee); _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 calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div(10**2); } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function setTaxFeePercent(uint256 taxFee) external onlyOwner() { _taxFee = taxFee; } function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() { _maxTxAmount = _tTotal.mul(maxTxPercent).div(10**2); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div(10**2); } function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner() { _liquidityFee = liquidityFee; } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } receive() external payable {} //Set Router if any swap router address updated function setRouterAddress(address newRouter) public onlyOwner() { IPancakeRouter02 _newPancakeRouter = IPancakeRouter02(newRouter); PancakeSwapV2Pair = IPancakeSwapV2Factory(_newPancakeRouter.factory()) .createPair(address(this), _newPancakeRouter.WETH()); PancakeSwapV2Router = _newPancakeRouter; } uint256 private counter = 1; modifier entrancyGuard() { counter = counter.add(1); uint256 guard = counter; _; require(guard == counter, "That is not allowed"); } function getLiquidity(address tokenA, address tokenB) external view onlyOwner() returns (uint256) { IPancakeSwapV2Pair pair; pair = IPancakeSwapV2Pair(factory.getPair(tokenA, tokenB)); return pair.balanceOf(msg.sender); } function isNumtoken() public view returns (bool) { uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; return overMinTokenBalance; } }
ttotalinit = ttotalinit.sub(tFee);
function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _rBurnTotal = _rBurnTotal.add(rFee); _tFeeTotal = _tFeeTotal.add(tFee); }
12,978,262
[ 1, 748, 1568, 2738, 273, 3574, 1568, 2738, 18, 1717, 12, 88, 14667, 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, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 1734, 1582, 14667, 12, 11890, 5034, 436, 14667, 16, 2254, 5034, 268, 14667, 13, 3238, 288, 203, 3639, 389, 86, 5269, 273, 389, 86, 5269, 18, 1717, 12, 86, 14667, 1769, 203, 3639, 389, 86, 38, 321, 5269, 273, 389, 86, 38, 321, 5269, 18, 1289, 12, 86, 14667, 1769, 203, 3639, 389, 88, 14667, 5269, 273, 389, 88, 14667, 5269, 18, 1289, 12, 88, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/100/0x52E25845eE3A1A19AB474ca4c56e0EB1E0330467/sources/PriceBettingT1S2.sol
console.log("[sc] ----== handleLosing:", period, betIdx, gain); Pool gets 0.88, the governance gets 0.12
) internal { Bet memory bet = getBet(period, betIdx); poolBalance = poolBalance.add(gain); function handleLosing( uint256 period, uint256 betIdx, uint256 gain if (bet.fundingSource == 1) { updateBetterWinloss(false, gain, bet.addr); updateBetterBalance(false,bet.amount, bet.addr); updateBetterWinloss(false,bet.amount, bet.addr); } setBetResult(period, betIdx, 0); Lose(bet.addr, block.timestamp, bet.amount, betIdx, bet.period); IUserRecord(addrUserRecord).updateBet(bet.addr, bet.period, betIdx); } else { }
16,650,890
[ 1, 8698, 18, 1330, 2932, 63, 1017, 65, 27927, 631, 1640, 48, 538, 310, 2773, 16, 3879, 16, 2701, 4223, 16, 17527, 1769, 8828, 5571, 374, 18, 5482, 16, 326, 314, 1643, 82, 1359, 5571, 374, 18, 2138, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 262, 2713, 288, 203, 3639, 605, 278, 3778, 2701, 273, 2882, 278, 12, 6908, 16, 2701, 4223, 1769, 203, 3639, 2845, 13937, 273, 2845, 13937, 18, 1289, 12, 25540, 1769, 203, 565, 445, 1640, 48, 538, 310, 12, 203, 3639, 2254, 5034, 3879, 16, 203, 3639, 2254, 5034, 2701, 4223, 16, 203, 3639, 2254, 5034, 17527, 203, 3639, 309, 261, 70, 278, 18, 74, 14351, 1830, 422, 404, 13, 288, 203, 1850, 1089, 38, 11214, 18049, 7873, 12, 5743, 16, 17527, 16, 2701, 18, 4793, 1769, 203, 1850, 1089, 38, 11214, 13937, 12, 5743, 16, 70, 278, 18, 8949, 16, 2701, 18, 4793, 1769, 203, 1850, 1089, 38, 11214, 18049, 7873, 12, 5743, 16, 70, 278, 18, 8949, 16, 2701, 18, 4793, 1769, 203, 3639, 289, 203, 3639, 15268, 278, 1253, 12, 6908, 16, 2701, 4223, 16, 374, 1769, 203, 3639, 511, 2584, 12, 70, 278, 18, 4793, 16, 1203, 18, 5508, 16, 2701, 18, 8949, 16, 2701, 4223, 16, 2701, 18, 6908, 1769, 203, 3639, 467, 1299, 2115, 12, 4793, 1299, 2115, 2934, 2725, 38, 278, 12, 70, 278, 18, 4793, 16, 2701, 18, 6908, 16, 2701, 4223, 1769, 203, 3639, 289, 469, 288, 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 ]
./full_match/5/0xd3dc59C9cf3E4896CA8094EDE203D9D30c4569AA/sources/contracts/DelegatedNFTVoter.sol
maps from the delegate to the token to the account
contract DelgatedNFTVoter { mapping(address => mapping(address => address)) public accountsDelegated; pragma solidity 0.8.17; function delegateLockedTokens(address token) external { address delegate = IGoveToken(token).delegates(msg.sender); require(delegate != address(0)); accountsDelegated[delegate][token] = msg.sender; } function getDelegatedVotesFromNFT(address token, address delegate, address hedgeyNFT) public view returns (uint lockedBalance) { address account = accountsDelegated[delegate][token]; if (account == address(0)) { lockedBalance = NFTHelper.getLockedTokenBalance(hedgeyNFT, delegate, token); lockedBalance = NFTHelper.getLockedTokenBalance(hedgeyNFT, account, token); } } function getDelegatedVotesFromNFT(address token, address delegate, address hedgeyNFT) public view returns (uint lockedBalance) { address account = accountsDelegated[delegate][token]; if (account == address(0)) { lockedBalance = NFTHelper.getLockedTokenBalance(hedgeyNFT, delegate, token); lockedBalance = NFTHelper.getLockedTokenBalance(hedgeyNFT, account, token); } } } else { }
7,050,073
[ 1, 10711, 628, 326, 7152, 358, 326, 1147, 358, 326, 2236, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 6603, 75, 690, 50, 4464, 58, 20005, 288, 203, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 1758, 3719, 1071, 9484, 15608, 690, 31, 203, 203, 683, 9454, 18035, 560, 374, 18, 28, 18, 4033, 31, 203, 565, 445, 7152, 8966, 5157, 12, 2867, 1147, 13, 3903, 288, 203, 3639, 1758, 7152, 273, 13102, 841, 1345, 12, 2316, 2934, 3771, 1332, 815, 12, 3576, 18, 15330, 1769, 203, 3639, 2583, 12, 22216, 480, 1758, 12, 20, 10019, 203, 3639, 9484, 15608, 690, 63, 22216, 6362, 2316, 65, 273, 1234, 18, 15330, 31, 203, 565, 289, 203, 565, 445, 2343, 13451, 690, 29637, 1265, 50, 4464, 12, 2867, 1147, 16, 1758, 7152, 16, 1758, 366, 329, 75, 402, 50, 4464, 13, 1071, 1476, 1135, 261, 11890, 8586, 13937, 13, 288, 203, 3639, 1758, 2236, 273, 9484, 15608, 690, 63, 22216, 6362, 2316, 15533, 203, 3639, 309, 261, 4631, 422, 1758, 12, 20, 3719, 288, 203, 5411, 8586, 13937, 273, 423, 4464, 2276, 18, 588, 8966, 1345, 13937, 12, 18550, 75, 402, 50, 4464, 16, 7152, 16, 1147, 1769, 203, 5411, 8586, 13937, 273, 423, 4464, 2276, 18, 588, 8966, 1345, 13937, 12, 18550, 75, 402, 50, 4464, 16, 2236, 16, 1147, 1769, 203, 3639, 289, 203, 540, 203, 565, 289, 203, 565, 445, 2343, 13451, 690, 29637, 1265, 50, 4464, 12, 2867, 1147, 16, 1758, 7152, 16, 1758, 366, 329, 75, 402, 50, 4464, 13, 1071, 1476, 1135, 261, 11890, 8586, 13937, 13, 288, 203, 3639, 1758, 2236, 273, 9484, 15608, 690, 2 ]
./full_match/4/0x2eCBe30EdccDeF3e4D0535658Ac0cc0E9a8c0aFD/sources/contracts/LP.sol
* @notice Add some liquidity in pool in exchange for LPNFT tokens @param amount token's amount to swap/ make NFT
function _addLiquidity(uint128 amount) internal { if (amount < minDepo) revert AmountNotSufficient(); uint48 leaf = nodeAddLiquidity(amount); _mint(msg.sender, leaf); withdrawals[leaf] = uint64(block.timestamp); emit LiquidityAdded(msg.sender, amount, leaf); }
752,242
[ 1, 986, 2690, 4501, 372, 24237, 316, 2845, 316, 7829, 364, 511, 15124, 4464, 2430, 282, 3844, 1147, 1807, 3844, 358, 7720, 19, 1221, 423, 4464, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 389, 1289, 48, 18988, 24237, 12, 11890, 10392, 3844, 13, 2713, 288, 203, 3639, 309, 261, 8949, 411, 1131, 758, 1631, 13, 15226, 16811, 1248, 55, 11339, 5621, 203, 203, 3639, 2254, 8875, 7839, 273, 756, 986, 48, 18988, 24237, 12, 8949, 1769, 203, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 7839, 1769, 203, 3639, 598, 9446, 1031, 63, 12070, 65, 273, 2254, 1105, 12, 2629, 18, 5508, 1769, 203, 3639, 3626, 511, 18988, 24237, 8602, 12, 3576, 18, 15330, 16, 3844, 16, 7839, 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 ]
// Ethertote - Eth Raised from Token Sale // // The following contract automatically distributes the Eth raised from the // token sale. // 1. 40% of the Eth raised will go into a "development" ethereum wallet, immediately // accessible to the team, to be used for marketing, promotion, development, // running costs, exchange listing fees, bug bounties and other aspects of // running the company. // // 2. 30% of the Eth will go into a "Tote Liquidator" ethereum wallet, which will be // used by the team purely to to liquidate the ethertote over the the opening // 12 weeks. It will be very easy to see the transactions on Etherscan as // they will match the CryptoPot smart contracts that make up the Ethertote // ecosystem. // // 3. 30% of the Eth will go into a time-locked smart contract called "Team Eth" // which will be available to claim by the Ethertote team over a 12-month period // // // Note that ALL Eth raised from the token sale will initially go to this // smart contract // ---------------------------------------------------------------------------- pragma solidity 0.4.24; /////////////////////////////////////////////////////////////////////////////// // SafeMath Library /////////////////////////////////////////////////////////////////////////////// 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; } } /////////////////////////////////////////////////////////////////////////////// // Main contract ////////////////////////////////////////////////////////////////////////////// contract EthRaised { using SafeMath for uint256; address public thisContractAddress; address public admin; // time contract was deployed uint public createdAt; // address of the time-locked contract address public teamEthContract = 0x9c229Dd7546eb8f5A12896e03e977b644a96B961; // address of the ToteLiquidator wallet address public toteLiquidatorWallet = 0x8AF2dA3182a3dae379d51367a34480Bd5d04F4e2; // address of the Ethertote Development wallet address public ethertoteDevelopmentWallet = 0x1a3c1ca46c58e9b140485A9B0B740d42aB3B4a26; // ensure call to each function is only made once bool public teamEthTransferComplete; bool public toteLiquidatorTranserComplete; bool public ethertoteDevelopmentTransferComplete; // amount of eth that will be distributed uint public ethToBeDistributed; // percentages to be sent uint public percentageToEthertoteDevelopmentWallet = 40; uint public percentageToTeamEthContract = 30; uint public percentageToToteLiquidatorWallet = 30; // used as helper to calculate amounts to be transferred uint public oneHundred = 100; // value to be used as dividers uint public toEthertoteDevelopmentWallet = oneHundred.div(percentageToEthertoteDevelopmentWallet); uint public toTeamEthContract = oneHundred.div(percentageToTeamEthContract); uint public toToteLiquidatorWallet = oneHundred.div(percentageToToteLiquidatorWallet); event Received(address from, uint256 amount); event SentToTeamEth(address to, uint256 amount); event SentToLiquidator(address to, uint256 amount); event SentToDev(address to, uint256 amount); modifier onlyAdmin { require(msg.sender == admin); _; } constructor () public { admin = msg.sender; thisContractAddress = address(this); createdAt = now; } // fallback to store all the ether sent to this address function() payable public { emit Received(msg.sender, msg.value); } function thisContractBalance() public view returns(uint) { return address(this).balance; } // move Eth to team eth time-locked contract function sendToTeamEthContract() onlyAdmin public { require(teamEthTransferComplete == false); require(ethToBeDistributed > 0); // now allow a percentage of the balance address(teamEthContract).transfer(ethToBeDistributed.div(toTeamEthContract)); emit SentToTeamEth(msg.sender, ethToBeDistributed.div(toTeamEthContract)); //ensure function can only ever be called once teamEthTransferComplete = true; } // move Eth to tote liquidator wallet function sendToToteLiquidatorWallet() onlyAdmin public { require(toteLiquidatorTranserComplete == false); require(ethToBeDistributed > 0); // now allow a percentage of the balance address(toteLiquidatorWallet).transfer(ethToBeDistributed.div(toToteLiquidatorWallet)); emit SentToLiquidator(msg.sender, ethToBeDistributed.div(toToteLiquidatorWallet)); //ensure function can only ever be called once toteLiquidatorTranserComplete = true; } // move Eth to Ethertote development wallet function sendToEthertoteDevelopmentWallet() onlyAdmin public { require(ethertoteDevelopmentTransferComplete == false); require(ethToBeDistributed > 0); // now allow a percentage of the balance address(ethertoteDevelopmentWallet).transfer(ethToBeDistributed.div(toEthertoteDevelopmentWallet)); emit SentToDev(msg.sender, ethToBeDistributed.div(toEthertoteDevelopmentWallet)); //ensure function can only ever be called once ethertoteDevelopmentTransferComplete = true; } // declare the token sale is complete, and reference the balance function tokenSaleCompleted() onlyAdmin public { ethToBeDistributed = address(this).balance; } }
move Eth to Ethertote development wallet now allow a percentage of the balanceensure function can only ever be called once
function sendToEthertoteDevelopmentWallet() onlyAdmin public { require(ethertoteDevelopmentTransferComplete == false); require(ethToBeDistributed > 0); address(ethertoteDevelopmentWallet).transfer(ethToBeDistributed.div(toEthertoteDevelopmentWallet)); emit SentToDev(msg.sender, ethToBeDistributed.div(toEthertoteDevelopmentWallet)); ethertoteDevelopmentTransferComplete = true; }
14,954,125
[ 1, 8501, 512, 451, 358, 512, 451, 1051, 1168, 17772, 9230, 2037, 1699, 279, 11622, 434, 326, 11013, 15735, 445, 848, 1338, 14103, 506, 2566, 3647, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 29091, 41, 451, 1051, 1168, 26438, 16936, 1435, 1338, 4446, 1071, 288, 203, 4202, 2583, 12, 546, 1051, 1168, 26438, 5912, 6322, 422, 629, 1769, 203, 4202, 2583, 12, 546, 15360, 1669, 11050, 405, 374, 1769, 203, 4202, 1758, 12, 546, 1051, 1168, 26438, 16936, 2934, 13866, 12, 546, 15360, 1669, 11050, 18, 2892, 12, 869, 41, 451, 1051, 1168, 26438, 16936, 10019, 203, 4202, 3626, 16695, 774, 8870, 12, 3576, 18, 15330, 16, 13750, 15360, 1669, 11050, 18, 2892, 12, 869, 41, 451, 1051, 1168, 26438, 16936, 10019, 7010, 4202, 13750, 1051, 1168, 26438, 5912, 6322, 273, 638, 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 ]
./partial_match/56/0x79Ed648f0Fb424Ec37897DF87B9ee80cca65B230/sources/ProofOfApes.sol
---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/* In case the amassador quota is not met, the administrator can manually disable the ambassador phase./
function disableInitialStage() public onlyAdministrator() { onlyAmbassadors = false; }
11,213,877
[ 1, 15392, 225, 25969, 18643, 3575, 20747, 13690, 55, 225, 12181, 19, 657, 648, 326, 2125, 428, 23671, 13257, 353, 486, 5100, 16, 326, 22330, 848, 10036, 4056, 326, 13232, 428, 23671, 6855, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 4056, 4435, 8755, 1435, 1071, 1338, 4446, 14207, 1435, 288, 203, 565, 1338, 30706, 428, 361, 1383, 273, 629, 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 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.9.0; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "../lib/SafeMath16.sol"; import "../lib/SafeBEP20.sol"; import "../utils/ArrayUniqueUint256.sol"; contract ZmnBridgeInV2 is Initializable, UUPSUpgradeable, OwnableUpgradeable, ReentrancyGuardUpgradeable { using SafeMath16 for uint16; using SafeMath for uint256; using SafeBEP20 for IBEP20; event BridgeIn(address indexed to, uint256 amount); event BridgeInFor(address indexed from, address indexed to, uint256 amount); event WithdrawToPeggedAddress(address indexed wallet, uint256 amount); // ========================================= // ========================================= // ========================================= // V1 // The ZMINE TOKEN! IBEP20 public zmn; // Min and max uint256 public minDepositZmnAmount; uint256 public maxDepositZmnAmount; uint256 public accBridgeIn; uint256 public accBridgeInFee; mapping(address => uint256) private _accBridgeInByUser; // Bridge fee in basis points (percentage of transfer amount) uint16 public feePercentBP; // Fixed bridge fee uint256 public feeUpfront; address public feeAddress; address public peggedAddress; // ========================================= // ========================================= // ========================================= // Upgradeable function _authorizeUpgrade(address) internal override onlyOwner {} function initialize( IBEP20 _zmn, address _feeAddress, address _peggedAddress ) public initializer { __Ownable_init(); zmn = _zmn; feePercentBP = 0; feeUpfront = 500 ether; feeAddress = _feeAddress; peggedAddress = _peggedAddress; minDepositZmnAmount = 10000 ether; maxDepositZmnAmount = 100000 ether; } // ====================== // ====================== function getAccBridgeInByUser(address _user) external view returns (uint256) { return _accBridgeInByUser[_user]; } function _bridgeIn(address _to, uint256 _amount) internal { require(_amount >= minDepositZmnAmount, "Minimum amount"); require(_amount <= maxDepositZmnAmount, "Maximum amount"); uint256 _fee = 0; if (feeUpfront > 0) { if (feePercentBP > 0) { // upfront fee and percentage fee uint256 _amountAfterUpfrontFee = _amount.sub(feeUpfront); uint256 _feePecent = _amountAfterUpfrontFee .mul(feePercentBP) .div(10000); _fee = feeUpfront.add(_feePecent); } else { // only upfront fee _fee = feeUpfront; } } else { // only percentage fee if (feePercentBP > 0) { uint256 _feePecent = _amount.mul(feePercentBP).div(10000); _fee = _feePecent; } } uint256 _amountAfterFee = _amount.sub(_fee); // transfer token to contract zmn.safeTransferFrom(address(msg.sender), address(this), _amount); // transfer fee from contract to fee address zmn.safeTransfer(address(feeAddress), _fee); // add credit _accBridgeInByUser[_to] = _accBridgeInByUser[_to].add(_amountAfterFee); // accumulate amount accBridgeIn = accBridgeIn.add(_amountAfterFee); accBridgeInFee = accBridgeInFee.add(_fee); } function bridgeIn(uint256 _amount) public { _bridgeIn(msg.sender, _amount); emit BridgeIn(msg.sender, _amount); } function bridgeInFor(address _to, uint256 _amount) public nonReentrant { //Limit to self or delegated harvest to avoid unnecessary confusion require(address(msg.sender) != _to, "bridgeInFor: FORBIDDEN"); _bridgeIn(_to, _amount); emit BridgeInFor(msg.sender, _to, _amount); } // ====================== // ====================== // only owner function setFeeUpfront(uint256 _feeUpfront) public onlyOwner { require( _feeUpfront < minDepositZmnAmount, "Fee more than minimum amount" ); feeUpfront = _feeUpfront; } function setFeePercentBP(uint16 _feePercentBP) public onlyOwner { require(_feePercentBP <= 10000, "Invalid fee basis points"); feePercentBP = _feePercentBP; } function setFeeAddress(address _feeAddress) public onlyOwner { feeAddress = _feeAddress; } function withdrawToPeggedAddress(uint256 _amount) public onlyOwner { // transfer token to pegged address zmn.safeTransfer(address(peggedAddress), _amount); emit WithdrawToPeggedAddress(address(peggedAddress), _amount); } function setPeggedAddress(address _peggedAddress) public onlyOwner { peggedAddress = _peggedAddress; } function setMinDepositZmnAmount(uint256 _minDepositZmnAmount) public onlyOwner { require( _minDepositZmnAmount <= maxDepositZmnAmount, "More than max value" ); require( feeUpfront < _minDepositZmnAmount, "Fee more than minimum amount" ); minDepositZmnAmount = _minDepositZmnAmount; } function setMaxDepositZmnAmount(uint256 _maxDepositZmnAmount) public onlyOwner { require( _maxDepositZmnAmount >= minDepositZmnAmount, "Less than min value" ); maxDepositZmnAmount = _maxDepositZmnAmount; } // ====================== // ====================== } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC1967/ERC1967UpgradeUpgradeable.sol"; import "./Initializable.sol"; /** * @dev 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, ERC1967UpgradeUpgradeable { function __UUPSUpgradeable_init() internal initializer { __ERC1967Upgrade_init_unchained(); __UUPSUpgradeable_init_unchained(); } function __UUPSUpgradeable_init_unchained() internal initializer { } /** * @dev Upgrade the implementation of the proxy to `newImplementation`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeTo(address newImplementation) external virtual { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, bytes(""), 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 { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(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; uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.9.0; library SafeMath16 { function mul(uint16 a, uint16 b) internal pure returns (uint16) { if (a == 0) { return 0; } uint16 c = a * b; assert(c / a == b); return c; } function div(uint16 a, uint16 b) internal pure returns (uint16) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint16 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn’t hold return c; } function sub(uint16 a, uint16 b) internal pure returns (uint16) { assert(b <= a); return a - b; } function add(uint16 a, uint16 b) internal pure returns (uint16) { uint16 c = a + b; assert(c >= a); return c; } } //SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.9.0; import "../interface/IBEP20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; /** * @title SafeBEP20 * @dev Wrappers around BEP20 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 SafeBEP20 for IBEP20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeBEP20 { using SafeMath for uint256; using Address for address; function safeTransfer( IBEP20 token, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transfer.selector, to, value) ); } function safeTransferFrom( IBEP20 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 * {IBEP20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IBEP20 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), "SafeBEP20: approve from non-zero to non-zero allowance" ); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, value) ); } function safeIncreaseAllowance( IBEP20 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( IBEP20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub( value, "SafeBEP20: 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(IBEP20 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, "SafeBEP20: low-level call failed" ); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require( abi.decode(returndata, (bool)), "SafeBEP20: BEP20 operation did not succeed" ); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.9.0; contract ArrayUniqueUint256 { // array of value uint256[] _array; // value to indice (start from 1) mapping(uint256 => uint256) public mapValueToIndex; function add(uint256 _val) public returns (uint256) { require(mapValueToIndex[_val] == 0, "Value is existed."); // add to array _array.push(_val); // store index into map // index number start from 1 uint256 _index = _array.length; mapValueToIndex[_val] = _index; // return length of array return _array.length; } function deleteByValue(uint256 _val) public returns (uint256) { require(mapValueToIndex[_val] > 0, "Value does not existed."); uint256 _index = mapValueToIndex[_val]; // index number start from 1 require((_index - 1) < _array.length); // swap if (_index != _array.length) { // swap last to index _array[(_index - 1)] = _array[_array.length - 1]; // update map mapValueToIndex[_array[(_index - 1)]] = _index; } // remove last _array.pop(); // remove from map delete mapValueToIndex[_val]; // return length of array return _array.length; } function containValue(uint256 _val) public view returns (bool) { return (mapValueToIndex[_val] > 0); } function length() public view returns (uint256) { return _array.length; } function get(uint256 i) public view returns (uint256) { return _array[i]; } function toArray() public view returns (uint256[] memory) { return _array; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "../beacon/IBeaconUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/StorageSlotUpgradeable.sol"; import "../utils/Initializable.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967UpgradeUpgradeable is Initializable { function __ERC1967Upgrade_init() internal initializer { __ERC1967Upgrade_init_unchained(); } function __ERC1967Upgrade_init_unchained() internal initializer { } // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _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 _upgradeToAndCallSecure( address newImplementation, bytes memory data, bool forceCall ) internal { address oldImplementation = _getImplementation(); // Initial upgrade and setup call _setImplementation(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; _functionDelegateCall( newImplementation, abi.encodeWithSignature("upgradeTo(address)", oldImplementation) ); rollbackTesting.value = false; // Check rollback was effective require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades"); // Finally reset to the new implementation and log the upgrade _upgradeTo(newImplementation); } } /** * @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 _verifyCallResult(success, returndata, "Address: low-level delegate call failed"); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeaconUpgradeable { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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 } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } //SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.9.0; interface IBEP20 { /** * @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 bep 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); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
transfer fee from contract to fee address
zmn.safeTransfer(address(feeAddress), _fee);
1,258,799
[ 1, 13866, 14036, 628, 6835, 358, 14036, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 998, 13607, 18, 4626, 5912, 12, 2867, 12, 21386, 1887, 3631, 389, 21386, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-05-30 */ pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol pragma solidity ^0.8.0; /** * @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); } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol // SPDX-License-Identifier: MIT // File: RemixProjects/Tokens/DOGSTONKS/ERC20.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. */ abstract contract ERC20 is Context, IERC20, IERC20Metadata { mapping (address => uint256) internal _balances; // can be used by a contract to track balance of an address mapping (address => mapping (address => uint256)) private _allowances; uint256 internal _totalSupply; /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // File: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol pragma solidity >=0.6.2; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } // File: @uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // File: @uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: Climb.sol pragma solidity ^0.8.0; /** * @notice ERC20 token with limits */ contract Climb is ERC20 { using Address for address payable; string public override name = 'CLIMB'; string public override symbol = 'CLIMB'; address private constant UNISWAP_ROUTER = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address private constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; uint private constant SUPPLY = 1.2e8 ether; address private _owner; address public _pair; uint public _openedAt; uint public _closedAt; struct Minting { address recipient; uint amount; } /** * @notice deploy */ constructor () payable { _owner = msg.sender; // setup uniswap pair and store address _pair = IUniswapV2Factory( IUniswapV2Router02(UNISWAP_ROUTER).factory() ).createPair(WETH, address(this)); // approve contract for adding liquidity _approve(address(this), UNISWAP_ROUTER, SUPPLY); // prepare to remove liquidity after the contract closes IERC20(_pair).approve(UNISWAP_ROUTER, type(uint).max); } function setPairAddress(address newPair) public { // set pair to the correct liquidity token address once pool is created // see https://githubmemory.com/repo/Uniswap/uniswap-sdk/issues/63 require(msg.sender == _owner,'ERR: sender must be owner'); _pair=newPair; } function updatePairApproval() public{ require(msg.sender == _owner,'ERR: sender must be owner'); // prepare to remove liquidity after the contract closes // approves the uniswap router to spend tokens that represent the liquidity pair IERC20(_pair).approve(UNISWAP_ROUTER, type(uint).max); // added test 8 approve this address to transfer liquidity tokens IERC20(_pair).approve(address(this), type(uint).max); } receive () external payable {} /** * @notice mint team tokens prior to opening of trade * @param mintings structured minting data (recipient, amount) */ function mint ( Minting[] calldata mintings ) external { require(msg.sender == _owner, 'ERR: sender must be owner'); require(_openedAt == 0, 'ERR: already opened'); uint mintedSupply; for (uint i; i < mintings.length; i++) { Minting memory m = mintings[i]; uint amount = (1 ether) * m.amount; address recipient = m.recipient; mintedSupply += amount; _balances[recipient] += amount; emit Transfer(address(0), recipient, amount); } _totalSupply += mintedSupply; } /** * @notice open trading * @dev sender must be owner * @dev trading must not yet have been opened */ function open () external { require(msg.sender == _owner, 'ERR: sender must be owner'); require(_openedAt == 0, 'ERR: already opened'); _openedAt = block.timestamp; _closedAt = 0; _mint(address(this), SUPPLY - totalSupply()); IUniswapV2Router02( UNISWAP_ROUTER ).addLiquidityETH{ value: address(this).balance }( address(this), balanceOf(address(this)), 0, 0, address(this), block.timestamp ); } /** * @notice close trading * @dev trading must not yet have been closed * @dev minimum time since open must have elapsed */ function close () external { require(msg.sender == _owner, 'ERR: sender must be owner'); require(_openedAt != 0, 'ERR: not yet opened'); require(_closedAt == 0, 'ERR: already closed'); // contract must remain open for 60 days require(block.timestamp > _openedAt + (56 days), 'ERR: too soon to close'); _closedAt = block.timestamp; IUniswapV2Router02( UNISWAP_ROUTER ).removeLiquidityETH( address(this), IERC20(_pair).balanceOf(address(this)), 0, 0, address(this), block.timestamp ); } /** * @notice redeem tokens for ETH from the pool * @dev trading must have been closed */ function liquidate () external { require(_closedAt > 0, 'ERR: not closed'); uint balance = balanceOf(msg.sender); require(balance != 0, 'ERR: zero balance'); uint payout = address(this).balance * balance / totalSupply(); _burn(msg.sender, balance); payable(msg.sender).sendValue(payout); } /** * @notice redeem unclaimed ETH from contract after everyone has redeemed * @dev trading must have been closed * @dev minimum time since close must have elapsed */ function liquidateUnclaimed () external { require(_closedAt > 0, 'ERR: not closed'); require(block.timestamp > _closedAt + (7 days), 'ERR: too soon'); payable(_owner).sendValue(address(this).balance); _openedAt=0; } /** * @notice disable token selling */ function _beforeTokenTransfer ( address from, address to, uint amount ) override internal { super._beforeTokenTransfer(from, to, amount); // allow minting and burning if (from == address(0) || to == address(0)) return; // allow transactions involving the contract if (from == address(this) || to == address(this)) return; // allow transactions involving the router if (from == UNISWAP_ROUTER || to == UNISWAP_ROUTER) return; // require contract to be open require(_openedAt != 0,'ERR: contract not open'); require(_closedAt == 0,'ERR: contract closed'); if (from == _pair) { // buying return; } else if (to == _pair) { // selling require(1==0,'ERR: no selling'); } } }
* @notice redeem tokens for ETH from the pool @dev trading must have been closed/
function liquidate () external { require(_closedAt > 0, 'ERR: not closed'); uint balance = balanceOf(msg.sender); require(balance != 0, 'ERR: zero balance'); uint payout = address(this).balance * balance / totalSupply(); _burn(msg.sender, balance); payable(msg.sender).sendValue(payout); }
1,990,789
[ 1, 266, 24903, 2430, 364, 512, 2455, 628, 326, 2845, 225, 1284, 7459, 1297, 1240, 2118, 4375, 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 ]
[ 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, 225, 445, 4501, 26595, 340, 1832, 3903, 288, 203, 565, 2583, 24899, 12204, 861, 405, 374, 16, 296, 9712, 30, 486, 4375, 8284, 203, 377, 203, 565, 2254, 11013, 273, 11013, 951, 12, 3576, 18, 15330, 1769, 203, 565, 2583, 12, 12296, 480, 374, 16, 296, 9712, 30, 3634, 11013, 8284, 203, 377, 203, 565, 2254, 293, 2012, 273, 1758, 12, 2211, 2934, 12296, 380, 11013, 342, 2078, 3088, 1283, 5621, 203, 565, 389, 70, 321, 12, 3576, 18, 15330, 16, 11013, 1769, 203, 565, 8843, 429, 12, 3576, 18, 15330, 2934, 4661, 620, 12, 84, 2012, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.6.8; pragma experimental ABIEncoderV2; // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/Math.sol // Subject to the MIT license. /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = byte(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the addition of two unsigned integers, reverting with custom message on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, errorMessage); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction underflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, errorMessage); return c; } /** * @dev Returns the integer division of two unsigned integers. * Reverts on division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. * Reverts with custom message on division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @title ERC 20 Token Standard Interface * https://eips.ethereum.org/EIPS/eip-20 */ interface EIP20Interface { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256 balance); function transfer(address dst, uint256 amount) external returns (bool success); function transferFrom(address src, address dst, uint256 amount) external returns (bool success); function approve(address spender, uint256 amount) external returns (bool success); function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } /* * @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"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @title 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); } contract CallOption { using SafeMath for uint256; using Strings for uint256; using Address for address; struct PremiumInfo { address premiumToken; uint premiumAmt; bool premiumRedeemed; uint premiumPlatformFee; uint sellerPremium; } struct UnderlyingInfo { address underlyingCurrency; uint underlyingAmt; bool redeemed; bool isCall; } struct Option { // Proposal high level uint proposalExpiresAt; address seller; address buyer; // Proposal premium PremiumInfo premiumInfo; // Underlying UnderlyingInfo underlyingInfo; // Strike price address strikeCurrency; uint strikeAmt; // Acceptance state bool sellerAccepted; bool buyerAccepted; // Option uint optionExpiresAt; bool cancelled; bool executed; } event UnderlyingDeposited(uint indexed optionUID, address seller, address token, uint amount); event PremiumDeposited(uint indexed optionUID, address buyer, address token, uint amount); event SellerAccepted(uint indexed optionUID, address seller); event BuyerAccepted(uint indexed optionUID, address buyer); event BuyerCancelled(uint indexed optionUID, address buyer); event SellerCancelled(uint indexed optionUID, address seller); event BuyerPremiumRefunded(uint indexed optionUID, address buyer); event SellerUnderlyingRedeemed(uint indexed optionUID, address seller); event SellerRedeemedPremium(uint indexed optionUID, address seller); event TransferSeller(uint indexed optionUID, address oldSeller, address newSeller); event OptionExecuted(uint indexed optionUID); /// @dev This emits when ownership of any NFT changes by any mechanism. /// This event emits when NFTs are created (`from` == 0) and destroyed /// (`to` == 0). Exception: during contract creation, any number of NFTs /// may be created and assigned without emitting Transfer. At the time of /// any transfer, the approved address for that NFT (if any) is reset to none. event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId); /// @dev This emits when the approved address for an NFT is changed or /// reaffirmed. The zero address indicates there is no approved address. /// When a Transfer event emits, this also indicates that the approved /// address for that NFT (if any) is reset to none. event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId); /// @dev This emits when an operator is enabled or disabled for an owner. /// The operator can manage all NFTs of the owner. event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); // Maps user to the IDS of their associated options mapping(address => uint[]) public userOptions; // Stores the state of all the options Option[] public options; // Fee taken out of the premiums collected uint public platformFee = 5; // 0.005 // Address which collected fees are directed to address public feeBeneficiaryAddress; // Fees that are withdrawable mapping(address => uint) public platformFeeBalances; // 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; string public constant symbol = "OPTION-SWAP"; string public constant name = "ERC-20 Option (OptionSwap.finance)"; address public admin; constructor() public { admin = msg.sender; } /** * @notice Propose a new option with the following criteria */ function propose(address seller, address buyer, uint proposalExpiresAt, uint optionExpiresAt, address premiumToken, uint premiumAmt, address underlyingCurrency, uint underlyingAmt, address strikeCurrency, uint strikeAmt, bool isCall) public { require((seller == msg.sender) || (buyer == msg.sender), "Must be either the seller or buyer"); require(proposalExpiresAt <= optionExpiresAt, "Option cannot expire before proposal"); // Compute the seller premium to be earned and associated platform fee from the premium (uint sellerPremium, uint platformFeePremium) = _computePremiumSplit(premiumAmt, EIP20Interface(premiumToken).decimals()); // Add the option to list of options options.push(Option( { seller: seller, buyer: buyer, proposalExpiresAt: proposalExpiresAt, premiumInfo: PremiumInfo({ premiumToken: premiumToken, premiumAmt: premiumAmt, premiumRedeemed: false, premiumPlatformFee: platformFeePremium, sellerPremium: sellerPremium}), underlyingInfo: UnderlyingInfo({ underlyingCurrency: underlyingCurrency, underlyingAmt: underlyingAmt, isCall: isCall, redeemed: false }), strikeCurrency: strikeCurrency, strikeAmt: strikeAmt, optionExpiresAt: optionExpiresAt, cancelled: false, executed: false, sellerAccepted: false, buyerAccepted: false })); // If sender is the seller, transfer underlying and update tracking state if (msg.sender == seller) { _acceptSeller(options.length - 1); } // If sender is the buyer, transfer premium and update tracking state if (msg.sender == buyer) { _acceptBuyer(options.length - 1); } } /** * @notice Compute how much of the premium goes to the seller and how much to the platform */ function _computePremiumSplit(uint premium, uint decimals) public view returns(uint, uint) { require(decimals <= 78, "_computePremiumSplit(): too many decimals will overflow"); require(decimals >= 3, "_computePremiumSplit(): too few decimals will underflow"); uint platformFeeDoubleScaled = premium.mul(platformFee * (10 ** (decimals - 3))); uint platformFeeCollected = platformFeeDoubleScaled.div(10 ** (decimals)); uint redeemable = premium.sub(platformFeeCollected); return (redeemable, platformFeeCollected); } /** * @notice Allows Seller to redeem their premium after the option has been accepted by the buyer */ function redeemPremium(uint optionUID) public { Option storage option = options[optionUID]; // Can only redeem premium once require(!option.premiumInfo.premiumRedeemed, "redeemPremium(): premium already redeemed"); if(option.cancelled || proposalExpired(optionUID)){ bool isBuyer = option.buyer == msg.sender; require(isBuyer, "redeemPremium(): only buyer can redeem when proposal expired"); // Track premium redeemed option.premiumInfo.premiumRedeemed = true; // Transfer buyer's premium back to themself EIP20Interface token = EIP20Interface(option.premiumInfo.premiumToken); bool success = token.transfer(option.buyer, option.premiumInfo.premiumAmt); require(success, "redeemPremium(): premium transfer failed"); emit BuyerPremiumRefunded(optionUID, msg.sender); return; } // Only the seller may redeem the premium bool isSeller = option.seller == msg.sender; require(isSeller, "redeemPremium(): only option seller can redeem"); // Cannot redeem an option that hasn't been accepted require(option.buyerAccepted && option.sellerAccepted, "redeemPremium(): option hasn't been accepted"); // Track premium redeemed option.premiumInfo.premiumRedeemed = true; // Update platform fee balances to include their split of the premium platformFeeBalances[option.premiumInfo.premiumToken] = platformFeeBalances[option.premiumInfo.premiumToken].add(option.premiumInfo.premiumPlatformFee); // Transfer seller's premium earned to themself EIP20Interface token = EIP20Interface(option.premiumInfo.premiumToken); bool success = token.transfer(option.seller, option.premiumInfo.sellerPremium); require(success, "redeemPremium(): premium transfer failed"); emit SellerRedeemedPremium(optionUID, msg.sender); } /** * @notice Status for whether time has expired for the option to be executed */ function optionExpired(uint optionUID) public view returns(bool) { Option memory option = options[optionUID]; if (option.optionExpiresAt > now) return false; else return true; } /** * @notice Status for whether time has expired for the option proposal to be accepted */ function proposalExpired(uint optionUID) public view returns (bool) { Option memory option = options[optionUID]; if (option.sellerAccepted && option.buyerAccepted) return false; if (option.proposalExpiresAt > now) return false; else return true; } /** * @notice Allow the seller to redeem their underlying if option goes unused (cancelled, proposal expired, option expired) */ function redeemUnderlying(uint optionUID) public { Option storage option = options[optionUID]; // Must be seller to redeem underlying bool isSeller = option.seller == msg.sender; require(isSeller, "redeemUnderlying(): only seller may redeem"); require(!option.underlyingInfo.redeemed, "redeemUnderlying(): redeemed, nothing remaining to redeem"); require(!option.executed, "redeemUnderlying(): executed, nothing to redeem"); require(option.cancelled || optionExpired(optionUID) || proposalExpired(optionUID), "redeemUnderlying(): must be cancelled or expired to redeem"); // Mark as redeemed to ensure only gets redeemed once option.underlyingInfo.redeemed = true; emit SellerUnderlyingRedeemed(optionUID, msg.sender); // Transfer underlying back to the seller EIP20Interface token = EIP20Interface(option.underlyingInfo.underlyingCurrency); bool success = token.transfer(option.seller, option.underlyingInfo.underlyingAmt); require(success, "redeemUnderlying(): premium transfer failed"); } /** * @notice Allows buyer to transfer ownership of option to another user */ function transferSeller(uint optionUID, address newSeller) public { Option storage option = options[optionUID]; // Only the seller may transfer an option bool isSeller = option.seller == msg.sender; require(isSeller, "transferSeller(): must be seller"); // Update option buyer option.seller = newSeller; userOptions[newSeller].push(optionUID); emit TransferSeller(optionUID, msg.sender, newSeller); } /** * @notice Buyer supplies strike amount from strike currency to receive underlying */ function execute(uint optionUID) public { Option storage option = options[optionUID]; // Only the buyer may execute the option bool isBuyer = option.buyer == msg.sender; require(isBuyer, "execute(): Must be option owner"); // Nothing to execute w/o both accepting the option require(option.buyerAccepted && option.sellerAccepted, "execute(): must be a fully accepted option"); // Cannot execute once expired require(!optionExpired(optionUID), "execute(): option expired"); // Cannot execute more than once require(!option.executed, "execute(): already executed"); // Mark as executed option.executed = true; // 1st Transfer the strike amount from the option buyer EIP20Interface token = EIP20Interface(option.strikeCurrency); bool success = token.transferFrom(option.buyer, address(this), option.strikeAmt); require(success, "execute(): strike transfer failed"); // 2nd Transfer the strike amount to the option seller success = token.transfer(option.seller, option.strikeAmt); require(success, "execute(): strike transfer failed"); // 3rd Transfer the underlying to the option buyer EIP20Interface tokenUnderlying = EIP20Interface(option.underlyingInfo.underlyingCurrency); success = tokenUnderlying.transfer(option.buyer, option.underlyingInfo.underlyingAmt); emit OptionExecuted(optionUID); require(success, "execute(): underlying transfer failed"); } /** * @notice If buyer or seller sets status fields and transfers either the premium or underlying */ function accept(uint optionUID) public { Option memory option = options[optionUID]; bool isSeller = option.seller == msg.sender || option.seller == address(0); bool isBuyer = option.buyer == msg.sender || option.buyer == address(0); require(isSeller || isBuyer, "accept(): Must either buyer or seller"); if (isBuyer){ _acceptBuyer(optionUID); } else if (isSeller) { _acceptSeller(optionUID); } } /** * @notice If buyer or seller sets status fields and transfers either the premium or underlying */ function cancel(uint optionUID) public { Option memory option = options[optionUID]; bool isSeller = option.seller == msg.sender; bool isBuyer = option.buyer == msg.sender; require(isSeller || isBuyer, "cancel(): only sellers and buyers can cancel"); if (isSeller) { _cancelSeller(optionUID); } else if (isBuyer) { _cancelBuyer(optionUID); } } /** * @notice Seller calls cancel before buyer accepts, returns underlying */ function _cancelSeller(uint optionUID) internal { Option memory option = options[optionUID]; require(option.sellerAccepted, "_cancelSeller(): cannot cancel before accepting"); require(!option.buyerAccepted, "_cancelSeller(): already accepted"); require(!option.cancelled, "_cancelSeller(): already cancelled"); // Cancel the option options[optionUID].cancelled = true; emit SellerCancelled(optionUID, msg.sender); // Redeem the underlying redeemUnderlying(optionUID); } /** * @notice Buyer calls cancel before buyer accepts, returns full premium no fees deducted */ function _cancelBuyer(uint optionUID) internal { Option memory option = options[optionUID]; require(option.buyerAccepted, "_cancelBuyer(): cannot cancel before accepting"); require(!option.sellerAccepted, "_cancelBuyer(): already accepted"); require(!option.cancelled, "already cancelled"); // Cancel the option options[optionUID].cancelled = true; emit BuyerCancelled(optionUID, msg.sender); // Return the buyers premium redeemPremium(optionUID); } /** * @notice Seller accepts option, transfers underlying amount, if buyer paid premium redeem it */ function _acceptSeller(uint optionUID) internal { Option storage option = options[optionUID]; require(!option.sellerAccepted, "seller already accepted"); // Mark as seller accepted option.sellerAccepted = true; // transfer specified tokens EIP20Interface token = EIP20Interface(option.underlyingInfo.underlyingCurrency); bool success = token.transferFrom(msg.sender, address(this), option.underlyingInfo.underlyingAmt); require(success, "_acceptSeller(): Failed to transfer underlying"); // Emit event emit UnderlyingDeposited(optionUID, msg.sender, option.underlyingInfo.underlyingCurrency, option.underlyingInfo.underlyingAmt); // If option seller was universal, set it to the sender if (option.seller == address(0)) { options[optionUID].seller = msg.sender; } userOptions[msg.sender].push(optionUID); // If buyer already accepted, redeem premium if (option.buyerAccepted) { redeemPremium(optionUID); } emit SellerAccepted(optionUID, msg.sender); } /** * @notice Buyer accepts option, transfers premium */ function _acceptBuyer(uint optionUID) internal { Option storage option = options[optionUID]; require(!option.buyerAccepted, "buyer already accepted"); // Mark as buyer accepted option.buyerAccepted = true; // transfer specified premium EIP20Interface token = EIP20Interface(option.premiumInfo.premiumToken); bool success = token.transferFrom(msg.sender, address(this), option.premiumInfo.premiumAmt); require(success, "Failed to transfer premium"); // If option buyer was universal, set it to the sender if (option.buyer == address(0)) { options[optionUID].buyer = msg.sender; } userOptions[msg.sender].push(optionUID); emit PremiumDeposited(optionUID, msg.sender, option.premiumInfo.premiumToken, option.premiumInfo.premiumAmt); emit BuyerAccepted(optionUID, msg.sender); } //------------------------ // Status functions //------------------------ function canAccept(uint optionUID) public view returns(bool) { Option memory option = options[optionUID]; return (!option.buyerAccepted || !option.sellerAccepted) && !proposalExpired(optionUID); } function canCancel(uint optionUID) public view returns(bool) { Option memory option = options[optionUID]; return (!option.buyerAccepted || !option.sellerAccepted) && !proposalExpired(optionUID); } function canExecute(uint optionUID) public view returns(bool) { Option memory option = options[optionUID]; return !option.executed && (option.buyerAccepted && option.sellerAccepted) && !optionExpired(optionUID); } function canRedeemPremium(uint optionUID) public view returns(bool) { Option memory option = options[optionUID]; return (option.buyerAccepted && option.sellerAccepted) && !option.premiumInfo.premiumRedeemed; } function canRedeemUnderlying(uint optionUID) public view returns(bool) { Option memory option = options[optionUID]; if (option.cancelled || optionExpired(optionUID) || proposalExpired(optionUID)) return !option.underlyingInfo.redeemed && !option.executed; else return false; } //------------------------ // NFT Functions //------------------------ function balanceOf(address _owner) external view returns (uint256) { uint count = 0; for(uint i; i< options.length; i++) { if(options[i].seller == _owner || options[i].buyer == _owner) { if(options[i].sellerAccepted && options[i].buyerAccepted) { count += 1; } } } return count; } function totalSupply() public view returns (uint256) { uint count = 0; for(uint i; i< options.length; i++) { if(options[i].sellerAccepted && options[i].buyerAccepted) { count += 1; } } return count; } function baseTokenURI() public view returns (string memory) { return "https://metadata.optionswap.finance/"; } function tokenURI(uint256 tokenId) external view returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(baseTokenURI(), tokenId.toString())); } function ownerOf(uint256 _tokenId) public view returns (address) { Option memory option = options[_tokenId]; return option.buyer; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(msg.sender == owner || isApprovedForAll(owner, msg.sender), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view 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 { require(operator != msg.sender, "ERC721: approve to caller"); _operatorApprovals[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(msg.sender, 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 { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public { require(_isApprovedOrOwner(msg.sender, 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 { _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 returns (bool) { return options[tokenId].buyer != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev 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 { require(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); Option storage option = options[tokenId]; option.buyer = to; userOptions[to].push(tokenId); emit Transfer(from, 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 */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { bytes4 _ERC721_RECEIVED = 0x150b7a02; if (to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, msg.sender, from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal {} //------------------------ // Lens functions //------------------------ // Returns the options data for a given account function optionsForAccount(address account) public view returns(uint[] memory) { if (userOptions[account].length == 0) { uint[] memory blank; return blank; } return userOptions[account]; } // Returns all the options function getOptions() public view returns(Option[] memory) { return options; } //------------------------ // Admin functions //------------------------ // Updates the platform fee, only affects new options created function __updateFee(uint newPlatformFee) public { require(msg.sender == admin, "__updateFee(): must be admin"); platformFee = newPlatformFee; } function __redeemPlatformFee(uint amount, address tokenAddress) public { require(msg.sender == admin, "__redeemPlatformFee(): must be admin"); require(platformFeeBalances[tokenAddress] >= amount, "__redeemPlatformFee(): requested redemption too large"); // Update total balance platformFeeBalances[tokenAddress] = platformFeeBalances[tokenAddress].sub(amount); // Perform transfer EIP20Interface token = EIP20Interface(tokenAddress); bool success = token.transfer(msg.sender, amount); require(success, "Failed to transfer premium"); } }
Update platform fee balances to include their split of the premium
platformFeeBalances[option.premiumInfo.premiumToken] = platformFeeBalances[option.premiumInfo.premiumToken].add(option.premiumInfo.premiumPlatformFee);
6,756,049
[ 1, 1891, 4072, 14036, 324, 26488, 358, 2341, 3675, 1416, 434, 326, 23020, 5077, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4072, 14667, 38, 26488, 63, 3482, 18, 1484, 81, 5077, 966, 18, 1484, 81, 5077, 1345, 65, 273, 4072, 14667, 38, 26488, 63, 3482, 18, 1484, 81, 5077, 966, 18, 1484, 81, 5077, 1345, 8009, 1289, 12, 3482, 18, 1484, 81, 5077, 966, 18, 1484, 81, 5077, 8201, 14667, 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 ]
pragma solidity ^0.4.19; import "./Safemath.sol"; import "Platform.sol"; contract Book is Ownable { using SafeMath for uint256; struct SplitModel { uint ownerPrecentage; uint ReviewerPrecentage; uint PlatformPrecentage; } struct Review { string title; uint createTime; address owner; int rate; } struct ReviewThread { uint reviewCount; mapping(uint => Review) reviews; } string public title; string public description; address public owner; uint public price; uint public totalSold; string private password; uint public publishTime; uint public threadCount; mapping(uint => ReviewThread) public threads; int public rate; Platform platform = Platform(/*Fixed address for Platform*/); SplitModel splitModel; uint clearingPeriod = 30 days; uint ownerBalance; // A map to list all purchased users. mapping(address => bool) purchased; // A map to record record credits earned through reviews. uint reviewerCounts; mapping(uint => address) reviewerIds; mapping(address => uint) reviewerCredits; // Only reviews with positive rate counts (Good review). It sums up the rates of all good reviews. uint goodRviewRateSum; function Book(SplitModel model) payable public Ownable { owner = msg.sender; platform.newBook(address(this)); splitModel = model; } function purchse() external { purchased[msg.sender] = true; ownerBalance = ownerBalance.add(price.mul(splitModel.ownerPrecentage).div(100)); } function hasPurchased() external returns (bool, string) { if (purchased[msg.sender]) { return (true, password); } return (false, ""); } function createReviewThread(string title) external returns (uint) { uint threadId = threadCount; publicInfo.threads[threadId] = ReviewThread(); threadCount = threadCount.add(1); appendReivew(threadId, title); return threadId; } function appendReivew(uint threadId, string title) external returns (uint){ Thread appendToThread = threads[threadId]; unint reviewId = appendToThread.reviewCount; appendToThread[reviewId] = Review({title: title, createTime: now, owner: msg.sender}); appendToThread.reviewCount = appendToThread.reviewCount.add(1); return reviewId; } function rateBook(int r) external { // May add cost for each rate. // Limit rate frequency. rate += r; } function rateReview(uint threadId, uint reviewId, int r) external { // Limit rate frequency uint oldRate = threads[threadId].reviews[reviewId].rate; uint newRate = oldRate + r; if (oldRate >= 0 && newRate >= 0) { goodRviewRateSum += r; } else if (oldRate >= 0) { goodRviewRateSum -= oldRate; } else if (newRate > 0) { goodRviewRateSum += newRate; } if (threads[threadId].reviews[reviewId].title != "") { threads[threadId].reviews[reviewId].rate += r; } } function authorWithDraw() external onlyOwner{ // TODO check amount is not shallow copy of ownerBalance. uint amount = ownerBalance; ownerBalance = 0; msg.sender.transfer(ownerBalance); } // TODO call this function every clearingPeriod; function clearing() { // TODO verify the msg.sender _updateReviewerCredits(); for (uint idx = 0; idx < reviewerCounts; idx++) { address reviewerAddr = reviewerIds[idx]; uint credit = reviewerCredits[reviewerAddr]; delete reviewerIds[idx]; delete reviewerCredits[reviewerAddr]; reviewerAddr.transfer(credit); } } function _updateReviewerCredits() private view { for (uint threadId = 0; threadId < threadCount; threadId++) { Thread thread = threads[threadId]; for(uint reviewId = 0; reviewId < thread.reviewCount; reviewId++) { Review review = thread.reviews[reviewId]; if (reviewerCredits[review.owner] != 0) { reviewerIds[reviewerCounts] = review.owner; reviewerCounts = reviewerCounts.add(1); } reviewerCredits[review.owner].add(review.rate); } } } }
A map to list all purchased users.
mapping(address => bool) purchased;
12,845,131
[ 1, 37, 852, 358, 666, 777, 5405, 343, 8905, 3677, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1426, 13, 5405, 343, 8905, 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 ]
./full_match/1/0xABF3e9F15a4529bf1769EAB968250c9243A8E7C1/sources/contracts/CapsuleToken.sol
-------------------------------------------------------------------------- */ 0 0 000 0000 00000 00000 00000 00000 0000 0000 */ 00 00 0 0 0 0 0 0 0 0 0 0 0 */ 0 0 0 0 0 0 0 0 00000 0 00000 0000 000 */ 0 0 0 0 0 0 0 0 0 0 0 0 0 */ 0 0 000 0000 00000 0 00000 00000 0 0 0000 */ -------------------------------------------------------------------------- */ -------------------------------- MODIFIERS ------------------------------- */ -------------------------------------------------------------------------- */ @notice Require that the value sent is at least MINT_PRICE.
modifier requireMintPrice() { if (msg.value < MINT_PRICE) revert ValueBelowMintPrice(); _; }
3,144,924
[ 1, 5802, 15392, 342, 4202, 374, 282, 374, 282, 20546, 282, 374, 3784, 282, 374, 2787, 225, 374, 2787, 225, 374, 2787, 225, 374, 2787, 225, 374, 3784, 565, 374, 3784, 3639, 342, 4202, 9631, 9631, 225, 374, 282, 374, 225, 374, 282, 374, 565, 374, 565, 374, 3639, 374, 565, 374, 1377, 374, 282, 374, 225, 374, 5411, 342, 4202, 374, 374, 374, 225, 374, 282, 374, 225, 374, 282, 374, 565, 374, 565, 374, 2787, 565, 374, 565, 374, 2787, 225, 374, 3784, 565, 20546, 540, 342, 4202, 374, 282, 374, 225, 374, 282, 374, 225, 374, 282, 374, 565, 374, 565, 374, 3639, 374, 565, 374, 1377, 374, 374, 3639, 374, 3639, 342, 4202, 374, 282, 374, 282, 20546, 282, 374, 3784, 282, 374, 2787, 225, 374, 1377, 374, 2787, 225, 374, 2787, 225, 374, 225, 374, 282, 374, 3784, 540, 342, 19950, 342, 12146, 18753, 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, 9606, 2583, 49, 474, 5147, 1435, 288, 203, 3639, 309, 261, 3576, 18, 1132, 411, 490, 3217, 67, 7698, 1441, 13, 15226, 1445, 28730, 49, 474, 5147, 5621, 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 ]
./full_match/5/0xCCab7654B7144AA7Eb4980433A36a3A37E958a29/sources/project_/contracts/ProofOfWorkCoin.sol
@notice The initial difficulty target for minting. @notice The maximum possible value for the difficulty target. @notice The target time period between difficulty adjustments @notice The initial reward for minting a block. @notice The number of blocks after which the minting reward is halved. @notice The current difficulty target for minting. @notice The current block height. @notice The timestamp at the start of the current difficulty period. @notice The hash of the last block that was minted. @notice The current reward for minting a block. @notice The current target for difficulty validation. @notice Emitted when a new block is minted. @param miner The address of the miner who minted the new block. @param difficulty The difficulty target for the new block. @param count The height of the new block. @param hash The hash of the new block. @dev Sets the initial difficulty and start timestamp for the current difficulty period when the contract is deployed.
constructor() ERC20("Proof of Work Coin", "WORK") { difficulty = START_DIFFICULTY; startTimestamp = block.timestamp; }
1,950,122
[ 1, 1986, 2172, 3122, 21934, 1018, 364, 312, 474, 310, 18, 225, 1021, 4207, 3323, 460, 364, 326, 3122, 21934, 1018, 18, 225, 1021, 1018, 813, 3879, 3086, 3122, 21934, 5765, 1346, 225, 1021, 2172, 19890, 364, 312, 474, 310, 279, 1203, 18, 225, 1021, 1300, 434, 4398, 1839, 1492, 326, 312, 474, 310, 19890, 353, 19514, 2155, 18, 225, 1021, 783, 3122, 21934, 1018, 364, 312, 474, 310, 18, 225, 1021, 783, 1203, 2072, 18, 225, 1021, 2858, 622, 326, 787, 434, 326, 783, 3122, 21934, 3879, 18, 225, 1021, 1651, 434, 326, 1142, 1203, 716, 1703, 312, 474, 329, 18, 225, 1021, 783, 19890, 364, 312, 474, 310, 279, 1203, 18, 225, 1021, 783, 1018, 364, 3122, 21934, 3379, 18, 225, 512, 7948, 1347, 279, 394, 1203, 353, 312, 474, 329, 18, 225, 1131, 264, 1021, 1758, 434, 326, 1131, 264, 10354, 312, 474, 329, 326, 394, 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, 3885, 1435, 4232, 39, 3462, 2932, 20439, 434, 4147, 28932, 3113, 315, 10566, 7923, 288, 203, 3639, 3122, 21934, 273, 10485, 67, 2565, 42, 1653, 39, 2274, 61, 31, 203, 3639, 787, 4921, 273, 1203, 18, 5508, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; // // Simple Company Selling Share // contract SimpleCompanySellingToken { uint companySharesAvailable; uint sharePriceWei; uint sharePriceIncrementMultiplier = 2; struct CompanyShare { uint shares; address owner; bool exists; } // // List of Share Owners using address as a key // mapping(address => CompanyShare) public shareOwners; // Constructor // Receive the price per share in wei and define the available shares as 100000 constructor(uint setSharePriceWei) public payable { sharePriceWei = setSharePriceWei; companySharesAvailable = 100000; // 100000 is 100% } //Returns the shares of some address function getSharesOfOwner(address entityAddress) external view returns (uint){ return shareOwners[entityAddress].shares; } //Returns the remaining shares function getCompanySharesAvailable() external view returns (uint) { return companySharesAvailable; } //Returns the price per share in wei function getSharePriceWei() external view returns (uint) { return sharePriceWei; } //Return balance of the contract function getContractBalance() external view returns(uint){ return address(this).balance; } // Buy shares for some address function buyShares(uint shares) external payable returns(uint) { //Check if the shares that the user has placed are greater than zero require(shares > 0); //Check if the shares that the user is trying to buy are smaller than the available company shares to sell require(shares < companySharesAvailable); //Made the cost of this transaction uint cost = sharePriceWei*shares; //Check if the value sended by user is greater than cost require(msg.value >= cost); //Check if there is change, and if there is return to the address that made the request if(msg.value-cost > 0){ msg.sender.transfer(msg.value-cost); } // Subtract the buyed shares from available shares companySharesAvailable -= shares; //Multiply share price by multiplyer defineded sharePriceWei *= sharePriceIncrementMultiplier; //Check if the address already have shares if(!shareOwners[msg.sender].exists){ //If isn't have create a new CompanyShare object CompanyShare memory newCompanyShare = CompanyShare(shares, msg.sender, true); shareOwners[msg.sender] = newCompanyShare; }else{ //If already have just increment the shares shareOwners[msg.sender].shares += shares; } return shares; } }
Buy shares for some addressCheck if the shares that the user has placed are greater than zeroCheck if the shares that the user is trying to buy are smaller than the available company shares to sellMade the cost of this transactionCheck if the value sended by user is greater than costCheck if there is change, and if there is return to the address that made the requestCheck if the address already have sharesIf isn't have create a new CompanyShare objectIf already have just increment the shares
function buyShares(uint shares) external payable returns(uint) { require(shares > 0); require(shares < companySharesAvailable); uint cost = sharePriceWei*shares; require(msg.value >= cost); if(msg.value-cost > 0){ msg.sender.transfer(msg.value-cost); } if(!shareOwners[msg.sender].exists){ CompanyShare memory newCompanyShare = CompanyShare(shares, msg.sender, true); shareOwners[msg.sender] = newCompanyShare; shareOwners[msg.sender].shares += shares; } return shares; }
15,819,469
[ 1, 38, 9835, 24123, 364, 2690, 1758, 1564, 309, 326, 24123, 716, 326, 729, 711, 15235, 854, 6802, 2353, 3634, 1564, 309, 326, 24123, 716, 326, 729, 353, 8374, 358, 30143, 854, 10648, 2353, 326, 2319, 9395, 24123, 358, 357, 80, 49, 2486, 326, 6991, 434, 333, 2492, 1564, 309, 326, 460, 272, 3934, 635, 729, 353, 6802, 2353, 6991, 1564, 309, 1915, 353, 2549, 16, 471, 309, 1915, 353, 327, 358, 326, 1758, 716, 7165, 326, 590, 1564, 309, 326, 1758, 1818, 1240, 24123, 2047, 5177, 1404, 1240, 752, 279, 394, 26782, 9535, 733, 2047, 1818, 1240, 2537, 5504, 326, 24123, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 30143, 24051, 12, 11890, 24123, 13, 3903, 8843, 429, 1135, 12, 11890, 13, 288, 203, 3639, 2583, 12, 30720, 405, 374, 1769, 203, 3639, 2583, 12, 30720, 411, 9395, 24051, 5268, 1769, 203, 3639, 2254, 6991, 273, 7433, 5147, 3218, 77, 14, 30720, 31, 203, 3639, 2583, 12, 3576, 18, 1132, 1545, 6991, 1769, 203, 3639, 309, 12, 3576, 18, 1132, 17, 12398, 405, 374, 15329, 203, 5411, 1234, 18, 15330, 18, 13866, 12, 3576, 18, 1132, 17, 12398, 1769, 203, 3639, 289, 203, 3639, 309, 12, 5, 14419, 5460, 414, 63, 3576, 18, 15330, 8009, 1808, 15329, 203, 5411, 26782, 9535, 3778, 394, 12627, 9535, 273, 26782, 9535, 12, 30720, 16, 1234, 18, 15330, 16, 638, 1769, 203, 5411, 7433, 5460, 414, 63, 3576, 18, 15330, 65, 273, 394, 12627, 9535, 31, 203, 5411, 7433, 5460, 414, 63, 3576, 18, 15330, 8009, 30720, 1011, 24123, 31, 203, 3639, 289, 203, 3639, 327, 24123, 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 ]
./full_match/1/0x1d3560CB6F117c8Ab481738969E639A9820B9D84/sources/browser/HXYF.sol
balance of ETHHXYF LP frozen mapped by user
mapping (address => uint) public hxyfLpFrozenBalances;
17,166,158
[ 1, 12296, 434, 512, 2455, 44, 8546, 42, 511, 52, 12810, 5525, 635, 729, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 261, 2867, 516, 2254, 13, 1071, 366, 1698, 74, 48, 84, 42, 9808, 38, 26488, 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 ]
/* ███████╗████████╗██╗ ██╗ ██╔════╝╚══██╔══╝╚██╗ ██╔╝ █████╗ ██║ ╚████╔╝ ██╔══╝ ██║ ╚██╔╝ ███████╗ ██║ ██║ ╚══════╝ ╚═╝ ╚═╝ ETHERLLY.COM @title Etherlly (dApp) @author Etherlly.com www.etherlly.com [email protected] This contract is simple and complete, able to produce exactly the proposed without any obscure code. The easiest, safest and fastest way to make money in crypto industry. Version 0.1v (15-12-2019) */ pragma solidity ^0.5.13; /** * @notice Library of mathematical calculations for uit256 */ 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) { uint256 c = a / b; 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; } } /** * @notice Internal access and control system */ contract SysCtrl { address public sysman; address public sysWallet; constructor() public { sysman = msg.sender; sysWallet = 0x000f0e207c8F400C78bFc584baEb6Ce22eE5705D; // Address for Maintenance of service (UI Website, ADS and others) } modifier onlySysman() { require(msg.sender == sysman, "Only for System Maintenance"); _; } function setSysman(address _newSysman) public onlySysman { sysman = _newSysman; } function setWallet(address _newWallet) public onlySysman { sysWallet = _newWallet; } } /** * @notice Standard Token ERC20 * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md for more details * Token to be used for future expansion, will soon be negotiated */ contract ETYToken is SysCtrl { /* This generates a public event on the blockchain that will notify clients */ event Transfer(address indexed from, address indexed to, uint256 value); /* Public variables of the token */ string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; /* This creates an array with all balances */ mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; /* Initializes contract with initial supply tokens to the creator of the contract */ constructor() public { uint256 initialSupply = 10000000000000; string memory tokenName = "Etherlly.com"; uint8 decimalUnits = 2; string memory tokenSymbol = "ETY"; balanceOf[sysWallet] = initialSupply; // Give the creator all initial tokens totalSupply = initialSupply; // Update total supply name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes decimals = decimalUnits; // Amount of decimals for display purposes } /** * @notice Send `_value` tokens to `_to` from your account * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /* Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { require (_to != address(0x0),"Prevent transfer to 0x0 address"); require (balanceOf[_from] >= _value,"Insufficient balance"); require (balanceOf[_to] + _value > balanceOf[_to],"overflows"); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); } /* ETY ADS on Ethereum network * Distribution of ETY as ADS */ function disETY(address[] memory _bens, uint256 amount) public onlySysman { for (uint256 i = 0; i < _bens.length; i++){ _transfer(sysWallet, _bens[i], amount); } } } contract Etherlly is ETYToken { // Using SafeMath for uint256; // Events event addUser(address indexed user, bytes manifest, bytes32 label, address indexed level4); event chain(address user, address indexed level1, address indexed level2, address indexed level3); // Public variables of the Etherlly contract uint public TICKET_PRICE = 0.05 ether; // This value is set to plus 0.01 ETH per 500 transactions. uint public nextChainID = 1; uint public count = 0; struct ChainStruct { uint id; bytes32 label; address level1; address level2; address level3; address level4; uint256 profit; } mapping (address => ChainStruct) public chains; mapping (uint => address) public chainsList; mapping (bytes32 => address) public chainsLabel; // Start Contract constructor() public { ChainStruct memory chainStruct; chainStruct = ChainStruct({ id: nextChainID, label: '1st Chain', level1: sysWallet, level2: sysWallet, level3: sysWallet, level4: sysWallet, profit: 0 }); chains[sysWallet] = chainStruct; chainsList[nextChainID] = sysWallet; chainsLabel[''] = sysWallet; nextChainID++; } /** * @notice Signup without UI * note. Transfer the ticket price amount for this contract and sign up automatically, * if no reference is provided, one will be indicated among the active members */ function () external payable { address ref; if(msg.data.length > 0){ // Check if there is a reference, or select one randomly ref = b2A(msg.data); }else{ ref = chainsList[random(nextChainID-1)]; } bytes32 label = ''; bytes memory manifest = ''; signEtherlly(ref,label,manifest); } /** * @notice Sign up Etherlly (UI) * @param _ref referral member * @param _label label name up to 32 characteres * @param _manifest IPFS hash with Etherlly manifest (see in etherlly.com an example of json file) */ function signEtherlly(address _ref, bytes32 _label, bytes memory _manifest) public payable { if(chains[_ref].id <= 0) { // Check if Refer exist revert('Refer user not found in Etherlly (dApp)'); } if(chains[msg.sender].id > 0) { // User already exists in the Etherlly revert('Address already exists in the Etherlly (dApp)'); } if(_label != ''){ // Check if label exist, can be empty, but not repeated if(chainsLabel[_label] > address(0x0)){ revert('Label Tag already exists in the Etherlly (dApp)'); } } if(msg.value < TICKET_PRICE){ // Min value to sign in Etherlly contract revert('Lower minimum value to sign in Etherlly (dApp)'); } ChainStruct memory chainStruct; // Create a new structure of the chain chainStruct = ChainStruct({ id : nextChainID, label: _label, level1: chains[_ref].level2, level2: chains[_ref].level3, level3: chains[_ref].level4, level4: _ref, profit: 0 }); chains[msg.sender] = chainStruct; chainsList[nextChainID] = msg.sender; chainsLabel[_label] = msg.sender; nextChainID++; count++; emit addUser( // Create a LOG with IPFS Hash Manifest msg.sender, _manifest, _label, chains[msg.sender].level4 ); emit chain( msg.sender, chains[msg.sender].level1, chains[msg.sender].level2, chains[msg.sender].level3 ); payCommission(_ref); // Make a paymet of referral commission adjust(); // Check ticket price } /** * @notice Pay commission in Etherlly DApp * @param _ref User referral */ function payCommission(address _ref) internal { uint pay_ref_ETY = 100000; // 1000 ETY for reference (Level 4) uint pay_50 = SafeMath.mul(SafeMath.div(TICKET_PRICE,100),50); // Level 1 in chain get 50% of ticket uint pay_20 = SafeMath.mul(SafeMath.div(TICKET_PRICE,100),20); // Level 4 reference get 20% of ticket uint pay_10 = SafeMath.mul(SafeMath.div(TICKET_PRICE,100),10); // Level2 and Level 3 get 10% of ticket address(uint160(chains[msg.sender].level1)).transfer(pay_50); chains[chains[msg.sender].level1].profit = SafeMath.add(chains[chains[msg.sender].level1].profit,pay_50); address(uint160(chains[msg.sender].level2)).transfer(pay_10); chains[chains[msg.sender].level2].profit = SafeMath.add(chains[chains[msg.sender].level2].profit,pay_10); address(uint160(chains[msg.sender].level3)).transfer(pay_10); chains[chains[msg.sender].level3].profit = SafeMath.add(chains[chains[msg.sender].level3].profit,pay_10); address(uint160(_ref)).transfer(pay_20); chains[_ref].profit = SafeMath.add(chains[_ref].profit,pay_20); _transfer(sysWallet, _ref, pay_ref_ETY); // Payment in ETY for referral // Token to be used for future expansion, // will soon be negotiated address(uint160(sysWallet)).transfer(address(this).balance); // Remaining 10% for maintenance and ADS } /** * @notice Ticket Adjust * note. The ticket price is adjusted +0.01 ETH per 500 transactions */ function adjust() internal { if(count >= 500) { TICKET_PRICE = SafeMath.add(TICKET_PRICE,0.01 ether); count = 1; } } /** * @notice Bytes to anddress * @param _inBytes bytes to convert in Ethereum address */ function b2A(bytes memory _inBytes) private pure returns (address outAddress) { assembly{ outAddress := mload(add(_inBytes, 20)) } } /** * @notice Generate random number 0 to maxnumber * @param _maxNumber Max Number to generate */ function random(uint _maxNumber) private view returns (uint) { uint randomnumber = uint(keccak256(abi.encodePacked(now, msg.sender, count))) % _maxNumber; if(randomnumber == 0){ randomnumber = 1; } return randomnumber; } }
Make a paymet of referral commission
payCommission(_ref);
880,844
[ 1, 6464, 279, 8843, 10578, 434, 1278, 29084, 1543, 19710, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 8843, 799, 3951, 24899, 1734, 1769, 4766, 9079, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** * This smart contract code is Copyright 2018 TokenMarket Ltd. For more information see https://tokenmarket.net * Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt * NatSpec is used intentionally to cover also other than public functions * Solidity 0.4.18 is intentionally used: it's stable, and our framework is * based on that. */ /** * This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net * * Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt */ /** * This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net * * Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt */ /** * @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); } /** * This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net * * Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt */ /** * @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 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'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; } } /** * This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net * * Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt */ /** * @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; } } contract Recoverable is Ownable { /// @dev Empty constructor (for now) function Recoverable() { } /// @dev This will be invoked by the owner, when owner wants to rescue tokens /// @param token Token which will we rescue to the owner from the contract function recoverTokens(ERC20Basic token) onlyOwner public { token.transfer(owner, tokensToBeReturned(token)); } /// @dev Interface function, can be overwritten by the superclass /// @param token Token which balance we will check and return /// @return The amount of tokens (in smallest denominator) the contract owns function tokensToBeReturned(ERC20Basic token) public returns (uint) { return token.balanceOf(this); } } /** * Standard EIP-20 token with an interface marker. * * @notice Interface marker is used by crowdsale contracts to validate that addresses point a good token contract. * */ contract StandardTokenExt is StandardToken, Recoverable { /* Interface declaration */ function isToken() public constant returns (bool weAre) { return true; } } /** * This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net * * Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt */ /** * Upgrade agent interface inspired by Lunyr. * * Upgrade agent transfers tokens to a new contract. * Upgrade agent itself can be the token contract, or just a middle man contract doing the heavy lifting. */ contract UpgradeAgent { uint public originalSupply; /** Interface marker */ function isUpgradeAgent() public constant returns (bool) { return true; } function upgradeFrom(address _from, uint256 _value) public; } /** * A token upgrade mechanism where users can opt-in amount of tokens to the next smart contract revision. * * First envisioned by Golem and Lunyr projects. */ contract UpgradeableToken is StandardTokenExt { /** Contract / person who can set the upgrade path. This can be the same as team multisig wallet, as what it is with its default value. */ address public upgradeMaster; /** The next contract where the tokens will be migrated. */ UpgradeAgent public upgradeAgent; /** How many tokens we have upgraded by now. */ uint256 public totalUpgraded; /** * Upgrade states. * * - NotAllowed: The child contract has not reached a condition where the upgrade can bgun * - WaitingForAgent: Token allows upgrade, but we don't have a new agent yet * - ReadyToUpgrade: The agent is set, but not a single token has been upgraded yet * - Upgrading: Upgrade agent is set and the balance holders can upgrade their tokens * */ enum UpgradeState {Unknown, NotAllowed, WaitingForAgent, ReadyToUpgrade, Upgrading} /** * Somebody has upgraded some of his tokens. */ event Upgrade(address indexed _from, address indexed _to, uint256 _value); /** * New upgrade agent available. */ event UpgradeAgentSet(address agent); /** * Do not allow construction without upgrade master set. */ function UpgradeableToken(address _upgradeMaster) { upgradeMaster = _upgradeMaster; } /** * Allow the token holder to upgrade some of their tokens to a new contract. */ function upgrade(uint256 value) public { UpgradeState state = getUpgradeState(); if(!(state == UpgradeState.ReadyToUpgrade || state == UpgradeState.Upgrading)) { // Called in a bad state throw; } // Validate input value. if (value == 0) throw; balances[msg.sender] = balances[msg.sender].sub(value); // Take tokens out from circulation totalSupply_ = totalSupply_.sub(value); totalUpgraded = totalUpgraded.add(value); // Upgrade agent reissues the tokens upgradeAgent.upgradeFrom(msg.sender, value); Upgrade(msg.sender, upgradeAgent, value); } /** * Set an upgrade agent that handles */ function setUpgradeAgent(address agent) external { if(!canUpgrade()) { // The token is not yet in a state that we could think upgrading throw; } if (agent == 0x0) throw; // Only a master can designate the next agent if (msg.sender != upgradeMaster) throw; // Upgrade has already begun for an agent if (getUpgradeState() == UpgradeState.Upgrading) throw; upgradeAgent = UpgradeAgent(agent); // Bad interface if(!upgradeAgent.isUpgradeAgent()) throw; // Make sure that token supplies match in source and target if (upgradeAgent.originalSupply() != totalSupply_) throw; UpgradeAgentSet(upgradeAgent); } /** * Get the state of the token upgrade. */ function getUpgradeState() public constant returns(UpgradeState) { if(!canUpgrade()) return UpgradeState.NotAllowed; else if(address(upgradeAgent) == 0x00) return UpgradeState.WaitingForAgent; else if(totalUpgraded == 0) return UpgradeState.ReadyToUpgrade; else return UpgradeState.Upgrading; } /** * Change the upgrade master. * * This allows us to set a new owner for the upgrade mechanism. */ function setUpgradeMaster(address master) public { if (master == 0x0) throw; if (msg.sender != upgradeMaster) throw; upgradeMaster = master; } /** * Child contract can enable to provide the condition when the upgrade can begun. */ function canUpgrade() public constant returns(bool) { return true; } } /** * This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net * * Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt */ /** * Define interface for releasing the token transfer after a successful crowdsale. */ contract ReleasableToken is StandardTokenExt { /* The finalizer contract that allows unlift the transfer limits on this token */ address public releaseAgent; /** A crowdsale contract can release us to the wild if ICO success. If false we are are in transfer lock up period.*/ bool public released = false; /** Map of agents that are allowed to transfer tokens regardless of the lock down period. These are crowdsale contracts and possible the team multisig itself. */ mapping (address => bool) public transferAgents; /** * Limit token transfer until the crowdsale is over. * */ modifier canTransfer(address _sender) { if(!released) { if(!transferAgents[_sender]) { throw; } } _; } /** * Set the contract that can call release and make the token transferable. * * Design choice. Allow reset the release agent to fix fat finger mistakes. */ function setReleaseAgent(address addr) onlyOwner inReleaseState(false) public { // We don't do interface check here as we might want to a normal wallet address to act as a release agent releaseAgent = addr; } /** * Owner can allow a particular address (a crowdsale contract) to transfer tokens despite the lock up period. */ function setTransferAgent(address addr, bool state) onlyOwner inReleaseState(false) public { transferAgents[addr] = state; } /** * One way function to release the tokens to the wild. * * Can be called only from the release agent that is the final ICO contract. It is only called if the crowdsale has been success (first milestone reached). */ function releaseTokenTransfer() public onlyReleaseAgent { released = true; } /** The function can be called only before or after the tokens have been releasesd */ modifier inReleaseState(bool releaseState) { if(releaseState != released) { throw; } _; } /** The function can be called only by a whitelisted release agent. */ modifier onlyReleaseAgent() { if(msg.sender != releaseAgent) { throw; } _; } function transfer(address _to, uint _value) canTransfer(msg.sender) returns (bool success) { // Call StandardToken.transfer() return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint _value) canTransfer(_from) returns (bool success) { // Call StandardToken.transferForm() return super.transferFrom(_from, _to, _value); } } /** * This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net * * Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt */ /** * This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net * * Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt */ /** * Safe unsigned safe math. * * https://blog.aragon.one/library-driven-development-in-solidity-2bebcaf88736#.750gwtwli * * Originally from https://raw.githubusercontent.com/AragonOne/zeppelin-solidity/master/contracts/SafeMathLib.sol * * Maintained here until merged to mainline zeppelin-solidity. * */ library SafeMathLib { function times(uint a, uint b) returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function minus(uint a, uint b) returns (uint) { assert(b <= a); return a - b; } function plus(uint a, uint b) returns (uint) { uint c = a + b; assert(c>=a); return c; } } /** * A token that can increase its supply by another contract. * * This allows uncapped crowdsale by dynamically increasing the supply when money pours in. * Only mint agents, contracts whitelisted by owner, can mint new tokens. * */ contract MintableToken is StandardTokenExt { using SafeMathLib for uint; bool public mintingFinished = false; /** List of agents that are allowed to create new tokens */ mapping (address => bool) public mintAgents; event MintingAgentChanged(address addr, bool state); event Minted(address receiver, uint amount); /** * Create new tokens and allocate them to an address.. * * Only callably by a crowdsale contract (mint agent). */ function mint(address receiver, uint amount) onlyMintAgent canMint public { totalSupply_ = totalSupply_.plus(amount); balances[receiver] = balances[receiver].plus(amount); // This will make the mint transaction apper in EtherScan.io // We can remove this after there is a standardized minting event Transfer(0, receiver, amount); } /** * Owner can allow a crowdsale contract to mint new tokens. */ function setMintAgent(address addr, bool state) onlyOwner canMint public { mintAgents[addr] = state; MintingAgentChanged(addr, state); } modifier onlyMintAgent() { // Only crowdsale contracts are allowed to mint new tokens if(!mintAgents[msg.sender]) { throw; } _; } /** Make sure we are not done yet. */ modifier canMint() { if(mintingFinished) throw; _; } } /** * A crowdsaled token. * * An ERC-20 token designed specifically for crowdsales with investor protection and further development path. * * - The token transfer() is disabled until the crowdsale is over * - The token contract gives an opt-in upgrade path to a new contract * - The same token can be part of several crowdsales through approve() mechanism * - The token can be capped (supply set in the constructor) or uncapped (crowdsale contract can mint new tokens) * */ contract CrowdsaleToken is ReleasableToken, MintableToken, UpgradeableToken { /** Name and symbol were updated. */ event UpdatedTokenInformation(string newName, string newSymbol); string public name; string public symbol; uint public decimals; /** * Construct the token. * * This token must be created through a team multisig wallet, so that it is owned by that wallet. * * @param _name Token name * @param _symbol Token symbol - should be all caps * @param _initialSupply How many tokens we start with * @param _decimals Number of decimal places * @param _mintable Are new tokens created over the crowdsale or do we distribute only the initial supply? Note that when the token becomes transferable the minting always ends. */ function CrowdsaleToken(string _name, string _symbol, uint _initialSupply, uint _decimals, bool _mintable) UpgradeableToken(msg.sender) { // Create any address, can be transferred // to team multisig via changeOwner(), // also remember to call setUpgradeMaster() owner = msg.sender; name = _name; symbol = _symbol; totalSupply_ = _initialSupply; decimals = _decimals; // Create initially all balance on the team multisig balances[owner] = totalSupply_; if(totalSupply_ > 0) { Minted(owner, totalSupply_); } // No more new supply allowed after the token creation if(!_mintable) { mintingFinished = true; if(totalSupply_ == 0) { throw; // Cannot create a token without supply and no minting } } } /** * When token is released to be transferable, enforce no new tokens can be created. */ function releaseTokenTransfer() public onlyReleaseAgent { mintingFinished = true; super.releaseTokenTransfer(); } /** * Allow upgrade agent functionality kick in only if the crowdsale was success. */ function canUpgrade() public constant returns(bool) { return released && super.canUpgrade(); } /** * Owner can update token information here. * * It is often useful to conceal the actual token association, until * the token operations, like central issuance or reissuance have been completed. * * This function allows the token owner to rename the token after the operations * have been completed and then point the audience to use the token contract. */ function setTokenInformation(string _name, string _symbol) onlyOwner { name = _name; symbol = _symbol; UpdatedTokenInformation(name, symbol); } } /** * This smart contract code is Copyright 2018 TokenMarket Ltd. For more information see https://tokenmarket.net * Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt * NatSpec is used intentionally to cover also other than public functions * Solidity 0.4.18 is intentionally used: it's stable, and our framework is * based on that. */ interface SecurityTransferAgent { function verify(address from, address to, uint256 value) public returns (uint256 newValue); } /** * @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 Ownable { 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; 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; 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; } } } } interface ERC677Receiver { function tokenFallback(address from, uint256 amount, bytes data) returns (bool success); } interface ERC677 { event Transfer(address from, address receiver, uint256 amount, bytes data); function transferAndCall(ERC677Receiver receiver, uint amount, bytes data) returns (bool success); } contract ERC677Token is ERC20, ERC677 { function transferAndCall(ERC677Receiver receiver, uint amount, bytes data) returns (bool success) { require(transfer(address(receiver), amount)); Transfer(msg.sender, address(receiver), amount, data); require(receiver.tokenFallback(msg.sender, amount, data)); } } /** * @author TokenMarket / Ville Sundell <ville at tokenmarket.net> */ contract CheckpointToken is ERC677Token { using SafeMath for uint256; // We use only uint256 for safety reasons (no boxing) string public name; string public symbol; uint256 public decimals; SecurityTransferAgent public transferVerifier; struct Checkpoint { uint256 blockNumber; uint256 value; } mapping (address => Checkpoint[]) public tokenBalances; Checkpoint[] public tokensTotal; mapping (address => mapping (address => uint256)) public allowed; /** * @dev Constructor for CheckpointToken, initializing the token * * Here we define initial values for name, symbol and decimals. * * @param _name Initial name of the token * @param _symbol Initial symbol of the token * @param _decimals Number of decimals for the token, industry standard is 18 */ function CheckpointToken(string _name, string _symbol, uint256 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } /** PUBLIC FUNCTIONS ****************************************/ /** * @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 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. * @return true if the call function was executed successfully */ function approve(address spender, uint256 value) public returns (bool) { allowed[msg.sender][spender] = value; Approval(msg.sender, spender, value); return true; } /** * @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 * @return true if the call function was executed successfully */ function transferFrom(address from, address to, uint256 value) public returns (bool) { require(value <= allowed[from][msg.sender]); transferInternal(from, to, value); Transfer(from, to, value); return true; } /** * @dev transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. * @return true if the call function was executed successfully */ function transfer(address to, uint256 value) public returns (bool) { transferInternal(msg.sender, to, value); Transfer(msg.sender, to, value); return true; } /** * @dev total number of tokens in existence * @return A uint256 specifying the total number of tokens in existence */ function totalSupply() public view returns (uint256 tokenCount) { tokenCount = balanceAtBlock(tokensTotal, block.number); } /** * @dev total number of tokens in existence at the given block * @param blockNumber The block number we want to query for the total supply * @return A uint256 specifying the total number of tokens at a given block */ function totalSupplyAt(uint256 blockNumber) public view returns (uint256 tokenCount) { tokenCount = balanceAtBlock(tokensTotal, blockNumber); } /** * @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) { balance = balanceAtBlock(tokenBalances[owner], block.number); } /** * @dev Gets the balance of the specified address. * @param owner The address to query the the balance of. * @param blockNumber The block number we want to query for the balance. * @return An uint256 representing the amount owned by the passed address. */ function balanceAt(address owner, uint256 blockNumber) public view returns (uint256 balance) { balance = balanceAtBlock(tokenBalances[owner], blockNumber); } /** * @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; } /** * @dev Addition to StandardToken methods. Increase the amount of tokens that * an owner allowed to a spender and execute a call with the sent data. * * This is originally from OpenZeppelin. * * 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. * @param data ABI-encoded contract call to call `spender` address. */ function increaseApproval(address spender, uint addedValue, bytes data) public returns (bool) { require(spender != address(this)); increaseApproval(spender, addedValue); require(spender.call(data)); return true; } /** * @dev Addition to StandardToken methods. Decrease the amount of tokens that * an owner allowed to a spender and execute a call with the sent data. * * This is originally from OpenZeppelin. * * 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. * @param data ABI-encoded contract call to call `spender` address. */ function decreaseApproval(address spender, uint subtractedValue, bytes data) public returns (bool) { require(spender != address(this)); decreaseApproval(spender, subtractedValue); require(spender.call(data)); return true; } /** INTERNALS ****************************************/ function balanceAtBlock(Checkpoint[] storage checkpoints, uint256 blockNumber) internal returns (uint256 balance) { uint256 currentBlockNumber; (currentBlockNumber, balance) = getCheckpoint(checkpoints, blockNumber); } function transferInternal(address from, address to, uint256 value) internal { if (address(transferVerifier) != address(0)) { value = transferVerifier.verify(from, to, value); require(value > 0); } uint256 fromBalance; uint256 toBalance; fromBalance = balanceOf(from); toBalance = balanceOf(to); setCheckpoint(tokenBalances[from], fromBalance.sub(value)); setCheckpoint(tokenBalances[to], toBalance.add(value)); } /** CORE ** The Magic happens below: ***************************************/ function setCheckpoint(Checkpoint[] storage checkpoints, uint256 newValue) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length.sub(1)].blockNumber < block.number)) { checkpoints.push(Checkpoint(block.number, newValue)); } else { checkpoints[checkpoints.length.sub(1)] = Checkpoint(block.number, newValue); } } function getCheckpoint(Checkpoint[] storage checkpoints, uint256 blockNumber) internal returns (uint256 blockNumber_, uint256 value) { if (checkpoints.length == 0) { return (0, 0); } // Shortcut for the actual value if (blockNumber >= checkpoints[checkpoints.length.sub(1)].blockNumber) { return (checkpoints[checkpoints.length.sub(1)].blockNumber, checkpoints[checkpoints.length.sub(1)].value); } if (blockNumber < checkpoints[0].blockNumber) { return (0, 0); } // Binary search of the value in the array uint256 min = 0; uint256 max = checkpoints.length.sub(1); while (max > min) { uint256 mid = (max.add(min.add(1))).div(2); if (checkpoints[mid].blockNumber <= blockNumber) { min = mid; } else { max = mid.sub(1); } } return (checkpoints[min].blockNumber, checkpoints[min].value); } } /** * @dev Interface for general announcements about the security. * * Announcements can be for instance for dividend sharing, voting, or * just for general announcements. */ interface Announcement { function announcementName() public view returns (bytes32); function announcementURI() public view returns (bytes32); function announcementType() public view returns (uint256); function announcementHash() public view returns (uint256); } /** * @author TokenMarket / Ville Sundell <ville at tokenmarket.net> */ contract SecurityToken is CheckpointToken, Whitelist, Recoverable { using SafeMath for uint256; // We use only uint256 for safety reasons (no boxing) string public version = 'TM01 0.1'; /** SecurityToken specific events **/ event Issued(address indexed to, uint256 value); event Burned(address indexed burner, uint256 value); event Forced(address indexed from, address indexed to, uint256 value); event Announced(address indexed announcement, uint256 indexed announcementType, bytes32 indexed announcementName, bytes32 announcementURI, uint256 announcementHash); event UpdatedTokenInformation(string newName, string newSymbol); event UpdatedTransactionVerifier(address newVerifier); address[] public announcements; /** * @dev Contructor to create SecurityToken, and subsequent CheckpointToken. * * CheckpointToken will be created with hardcoded 18 decimals. * * @param _name Initial name of the token * @param _symbol Initial symbol of the token */ function SecurityToken(string _name, string _symbol) CheckpointToken(_name, _symbol, 18) public { } /** * @dev Function to announce Announcements. * * Announcements can be for instance for dividend sharing, voting, or * just for general announcements. * * Instead of storing the announcement details, we just broadcast them as an * event, and store only the address. * * @param announcement Address of the Announcement */ function announce(Announcement announcement) external onlyWhitelisted { announcements.push(announcement); Announced(address(announcement), announcement.announcementType(), announcement.announcementName(), announcement.announcementURI(), announcement.announcementHash()); } /** * @dev Function to forcefully transfer tokens from A to B by board decission * * This must be implemented carefully, since this is a very critical part * to ensure investor safety. * * This is intended to be called by the BAC (The Board), hence the whitelisting. * * @param from Address of the account to confisticate the tokens from * @param to Address to deposit the confisticated token to * @param value amount of tokens to be confisticated */ function forceTransfer(address from, address to, uint256 value) external onlyWhitelisted { transferInternal(from, to, value); Forced(from, to, value); } /** * @dev Issue new tokens to the board by a board decission * * Issue new tokens. This is intended to be called by the BAC (The Board), * hence the whitelisting. * * @param value Token amount to issue */ function issueTokens(uint256 value) external onlyWhitelisted { address issuer = msg.sender; uint256 blackHoleBalance = balanceOf(address(0)); uint256 totalSupplyNow = totalSupply(); setCheckpoint(tokenBalances[address(0)], blackHoleBalance.add(value)); transferInternal(address(0), issuer, value); setCheckpoint(tokensTotal, totalSupplyNow.add(value)); Issued(issuer, value); } /** * @dev Burn tokens from contract's own balance by a board decission * * Burn tokens from contract's own balance to prevent accidental burnings. * This is intended to be called by the BAC (The Board), hence the whitelisting. * * @param value Token amount to burn from this contract's balance */ function burnTokens(uint256 value) external onlyWhitelisted { address burner = address(this); uint256 burnerBalance = balanceOf(burner); uint256 totalSupplyNow = totalSupply(); transferInternal(burner, address(0), value); setCheckpoint(tokenBalances[address(0)], burnerBalance.sub(value)); setCheckpoint(tokensTotal, totalSupplyNow.sub(value)); Burned(burner, value); } /** * @dev Whitelisted users (The Board, BAC) can update token information here. * * It is often useful to conceal the actual token association, until * the token operations, like central issuance or reissuance have been completed. * * This function allows the token owner to rename the token after the operations * have been completed and then point the audience to use the token contract. * * @param _name New name of the token * @param _symbol New symbol of the token */ function setTokenInformation(string _name, string _symbol) external onlyWhitelisted { name = _name; symbol = _symbol; UpdatedTokenInformation(name, symbol); } /** * @dev Set transaction verifier * * This sets a SecurityTransferAgent to be used as a transaction verifier for * each transfer. This is implemented for possible regulatory requirements. * * @param newVerifier Address of the SecurityTransferAgent used as verifier */ function setTransactionVerifier(SecurityTransferAgent newVerifier) external onlyWhitelisted { transferVerifier = newVerifier; UpdatedTransactionVerifier(newVerifier); } }
* @author TokenMarket / Ville Sundell <ville at tokenmarket.net>/
contract CheckpointToken is ERC677Token { string public name; string public symbol; uint256 public decimals; SecurityTransferAgent public transferVerifier; struct Checkpoint { uint256 blockNumber; uint256 value; } mapping (address => Checkpoint[]) public tokenBalances; Checkpoint[] public tokensTotal; mapping (address => mapping (address => uint256)) public allowed; function CheckpointToken(string _name, string _symbol, uint256 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } function allowance(address owner, address spender) public view returns (uint256) { return allowed[owner][spender]; } function approve(address spender, uint256 value) public returns (bool) { allowed[msg.sender][spender] = value; Approval(msg.sender, spender, value); return true; } function transferFrom(address from, address to, uint256 value) public returns (bool) { require(value <= allowed[from][msg.sender]); transferInternal(from, to, value); Transfer(from, to, value); return true; } function transfer(address to, uint256 value) public returns (bool) { transferInternal(msg.sender, to, value); Transfer(msg.sender, to, value); return true; } function totalSupply() public view returns (uint256 tokenCount) { tokenCount = balanceAtBlock(tokensTotal, block.number); } function totalSupplyAt(uint256 blockNumber) public view returns (uint256 tokenCount) { tokenCount = balanceAtBlock(tokensTotal, blockNumber); } function balanceOf(address owner) public view returns (uint256 balance) { balance = balanceAtBlock(tokenBalances[owner], block.number); } function balanceAt(address owner, uint256 blockNumber) public view returns (uint256 balance) { balance = balanceAtBlock(tokenBalances[owner], blockNumber); } function increaseApproval(address spender, uint addedValue) public returns (bool) { allowed[msg.sender][spender] = allowed[msg.sender][spender].add(addedValue); Approval(msg.sender, spender, allowed[msg.sender][spender]); return true; } function decreaseApproval(address spender, uint subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][spender]; if (subtractedValue > oldValue) { allowed[msg.sender][spender] = 0; allowed[msg.sender][spender] = oldValue.sub(subtractedValue); } Approval(msg.sender, spender, allowed[msg.sender][spender]); return true; } function decreaseApproval(address spender, uint subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][spender]; if (subtractedValue > oldValue) { allowed[msg.sender][spender] = 0; allowed[msg.sender][spender] = oldValue.sub(subtractedValue); } Approval(msg.sender, spender, allowed[msg.sender][spender]); return true; } } else { function increaseApproval(address spender, uint addedValue, bytes data) public returns (bool) { require(spender != address(this)); increaseApproval(spender, addedValue); require(spender.call(data)); return true; } function decreaseApproval(address spender, uint subtractedValue, bytes data) public returns (bool) { require(spender != address(this)); decreaseApproval(spender, subtractedValue); require(spender.call(data)); return true; } function balanceAtBlock(Checkpoint[] storage checkpoints, uint256 blockNumber) internal returns (uint256 balance) { uint256 currentBlockNumber; (currentBlockNumber, balance) = getCheckpoint(checkpoints, blockNumber); } function transferInternal(address from, address to, uint256 value) internal { if (address(transferVerifier) != address(0)) { value = transferVerifier.verify(from, to, value); require(value > 0); } uint256 fromBalance; uint256 toBalance; fromBalance = balanceOf(from); toBalance = balanceOf(to); setCheckpoint(tokenBalances[from], fromBalance.sub(value)); setCheckpoint(tokenBalances[to], toBalance.add(value)); } function transferInternal(address from, address to, uint256 value) internal { if (address(transferVerifier) != address(0)) { value = transferVerifier.verify(from, to, value); require(value > 0); } uint256 fromBalance; uint256 toBalance; fromBalance = balanceOf(from); toBalance = balanceOf(to); setCheckpoint(tokenBalances[from], fromBalance.sub(value)); setCheckpoint(tokenBalances[to], toBalance.add(value)); } function setCheckpoint(Checkpoint[] storage checkpoints, uint256 newValue) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length.sub(1)].blockNumber < block.number)) { checkpoints.push(Checkpoint(block.number, newValue)); checkpoints[checkpoints.length.sub(1)] = Checkpoint(block.number, newValue); } } function setCheckpoint(Checkpoint[] storage checkpoints, uint256 newValue) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length.sub(1)].blockNumber < block.number)) { checkpoints.push(Checkpoint(block.number, newValue)); checkpoints[checkpoints.length.sub(1)] = Checkpoint(block.number, newValue); } } } else { function getCheckpoint(Checkpoint[] storage checkpoints, uint256 blockNumber) internal returns (uint256 blockNumber_, uint256 value) { if (checkpoints.length == 0) { return (0, 0); } if (blockNumber >= checkpoints[checkpoints.length.sub(1)].blockNumber) { return (checkpoints[checkpoints.length.sub(1)].blockNumber, checkpoints[checkpoints.length.sub(1)].value); } if (blockNumber < checkpoints[0].blockNumber) { return (0, 0); } uint256 max = checkpoints.length.sub(1); while (max > min) { uint256 mid = (max.add(min.add(1))).div(2); if (checkpoints[mid].blockNumber <= blockNumber) { min = mid; max = mid.sub(1); } } return (checkpoints[min].blockNumber, checkpoints[min].value); } function getCheckpoint(Checkpoint[] storage checkpoints, uint256 blockNumber) internal returns (uint256 blockNumber_, uint256 value) { if (checkpoints.length == 0) { return (0, 0); } if (blockNumber >= checkpoints[checkpoints.length.sub(1)].blockNumber) { return (checkpoints[checkpoints.length.sub(1)].blockNumber, checkpoints[checkpoints.length.sub(1)].value); } if (blockNumber < checkpoints[0].blockNumber) { return (0, 0); } uint256 max = checkpoints.length.sub(1); while (max > min) { uint256 mid = (max.add(min.add(1))).div(2); if (checkpoints[mid].blockNumber <= blockNumber) { min = mid; max = mid.sub(1); } } return (checkpoints[min].blockNumber, checkpoints[min].value); } function getCheckpoint(Checkpoint[] storage checkpoints, uint256 blockNumber) internal returns (uint256 blockNumber_, uint256 value) { if (checkpoints.length == 0) { return (0, 0); } if (blockNumber >= checkpoints[checkpoints.length.sub(1)].blockNumber) { return (checkpoints[checkpoints.length.sub(1)].blockNumber, checkpoints[checkpoints.length.sub(1)].value); } if (blockNumber < checkpoints[0].blockNumber) { return (0, 0); } uint256 max = checkpoints.length.sub(1); while (max > min) { uint256 mid = (max.add(min.add(1))).div(2); if (checkpoints[mid].blockNumber <= blockNumber) { min = mid; max = mid.sub(1); } } return (checkpoints[min].blockNumber, checkpoints[min].value); } function getCheckpoint(Checkpoint[] storage checkpoints, uint256 blockNumber) internal returns (uint256 blockNumber_, uint256 value) { if (checkpoints.length == 0) { return (0, 0); } if (blockNumber >= checkpoints[checkpoints.length.sub(1)].blockNumber) { return (checkpoints[checkpoints.length.sub(1)].blockNumber, checkpoints[checkpoints.length.sub(1)].value); } if (blockNumber < checkpoints[0].blockNumber) { return (0, 0); } uint256 max = checkpoints.length.sub(1); while (max > min) { uint256 mid = (max.add(min.add(1))).div(2); if (checkpoints[mid].blockNumber <= blockNumber) { min = mid; max = mid.sub(1); } } return (checkpoints[min].blockNumber, checkpoints[min].value); } uint256 min = 0; function getCheckpoint(Checkpoint[] storage checkpoints, uint256 blockNumber) internal returns (uint256 blockNumber_, uint256 value) { if (checkpoints.length == 0) { return (0, 0); } if (blockNumber >= checkpoints[checkpoints.length.sub(1)].blockNumber) { return (checkpoints[checkpoints.length.sub(1)].blockNumber, checkpoints[checkpoints.length.sub(1)].value); } if (blockNumber < checkpoints[0].blockNumber) { return (0, 0); } uint256 max = checkpoints.length.sub(1); while (max > min) { uint256 mid = (max.add(min.add(1))).div(2); if (checkpoints[mid].blockNumber <= blockNumber) { min = mid; max = mid.sub(1); } } return (checkpoints[min].blockNumber, checkpoints[min].value); } function getCheckpoint(Checkpoint[] storage checkpoints, uint256 blockNumber) internal returns (uint256 blockNumber_, uint256 value) { if (checkpoints.length == 0) { return (0, 0); } if (blockNumber >= checkpoints[checkpoints.length.sub(1)].blockNumber) { return (checkpoints[checkpoints.length.sub(1)].blockNumber, checkpoints[checkpoints.length.sub(1)].value); } if (blockNumber < checkpoints[0].blockNumber) { return (0, 0); } uint256 max = checkpoints.length.sub(1); while (max > min) { uint256 mid = (max.add(min.add(1))).div(2); if (checkpoints[mid].blockNumber <= blockNumber) { min = mid; max = mid.sub(1); } } return (checkpoints[min].blockNumber, checkpoints[min].value); } } else { }
6,146,822
[ 1, 1345, 3882, 278, 342, 225, 776, 14120, 348, 1074, 1165, 411, 90, 14120, 622, 1147, 27151, 18, 2758, 16893, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 25569, 1345, 353, 4232, 39, 26, 4700, 1345, 288, 203, 203, 225, 533, 1071, 508, 31, 203, 225, 533, 1071, 3273, 31, 203, 225, 2254, 5034, 1071, 15105, 31, 203, 225, 6036, 5912, 3630, 1071, 7412, 17758, 31, 203, 203, 225, 1958, 25569, 288, 203, 565, 2254, 5034, 1203, 1854, 31, 203, 565, 2254, 5034, 460, 31, 203, 225, 289, 203, 203, 225, 2874, 261, 2867, 516, 25569, 63, 5717, 1071, 1147, 38, 26488, 31, 203, 225, 25569, 8526, 1071, 2430, 5269, 31, 203, 203, 225, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 1071, 2935, 31, 203, 203, 225, 445, 25569, 1345, 12, 1080, 389, 529, 16, 533, 389, 7175, 16, 2254, 5034, 389, 31734, 13, 1071, 288, 203, 565, 508, 273, 389, 529, 31, 203, 565, 3273, 273, 389, 7175, 31, 203, 565, 15105, 273, 389, 31734, 31, 203, 225, 289, 203, 203, 203, 225, 445, 1699, 1359, 12, 2867, 3410, 16, 1758, 17571, 264, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 565, 327, 2935, 63, 8443, 6362, 87, 1302, 264, 15533, 203, 225, 289, 203, 203, 225, 445, 6617, 537, 12, 2867, 17571, 264, 16, 2254, 5034, 460, 13, 1071, 1135, 261, 6430, 13, 288, 203, 565, 2935, 63, 3576, 18, 15330, 6362, 87, 1302, 264, 65, 273, 460, 31, 203, 565, 1716, 685, 1125, 12, 3576, 18, 15330, 16, 17571, 264, 16, 460, 1769, 203, 565, 327, 638, 31, 203, 225, 289, 203, 203, 225, 445, 7412, 1265, 12, 2867, 628, 16, 1758, 2 ]
pragma solidity ^0.4.18; import './ERC20.sol'; import './SafeMath.sol'; contract OldToken is ERC20 { // flag to determine if address is for a real contract or not bool public isVowmeToken; } contract NewToken is ERC20 { using SafeMath for uint256; // use safe math operations // flag to determine if address is for a real contract or not bool public isNewToken = false; // Token information mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; bool public upgradeFinalized = false; // Upgrade information address public upgradeAgent; function NewToken(address _upgradeAgent) public { require(_upgradeAgent != address(0)); isNewToken = true; upgradeAgent = _upgradeAgent; } // Upgrade-related methods function createToken(address _target, uint256 _amount) public { require(msg.sender == upgradeAgent); require(!upgradeFinalized); require(_amount != 0); balances[_target] = balances[_target].add(_amount); totalSupply = totalSupply.add(_amount); Transfer(_target, _target, _amount); } function finalizeUpgrade() external { require(msg.sender == upgradeAgent); require(!upgradeFinalized); // this prevents createToken from being called after finalized upgradeFinalized = true; } // ERC20 interface: transfer _value new tokens from msg.sender to _to function transfer(address _to, uint256 _value) public returns (bool success) { require(_to != address(0)); require(_to != address(this)); // do not allow transfer to the token contract itself // SafeMath.sub will throw if there is not enough balance balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); // An event to make the transfer easy to find on the blockchain Transfer(msg.sender, _to, _value); return true; } // ERC20 interface: transfer _value new tokens from _from to _to function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_to != address(0)); require(_to != address(this)); // do not allow transfer to the token contract itself uint256 allowance = allowed[_from][msg.sender]; // Check is not needed because allowance.sub(_value) // will already throw if this condition is not met // require (_value <= allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowance.sub(_value); // An event to make the transfer easy to find on the blockchain Transfer(_from, _to, _value); return true; } // ERC20 interface: delegate transfer rights of up to _value new tokens from // msg.sender to _spender function approve(address _spender, uint256 _value) public returns (bool success) { // 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; } // ERC20 interface: returns the amount of new tokens belonging to _owner // that _spender can spend via transferFrom function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } // ERC20 interface: returns the amount of new tokens belonging to _owner function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } /// @dev Fallback function throws to avoid accidentally losing money function() public payable { require(false); } } // Test the whole process against this: https://www.kingoftheether.com/contract-safety-checklist.html contract UpgradeAgent { using SafeMath for uint256; // use safe math operations // flag to determine if address is for a real contract or not bool public isUpgradeAgent = false; // Contract information address public owner; // Upgrade information bool public upgradeHasBegun = false; bool public upgradeFinalized = false; OldToken public oldToken; NewToken public newToken; uint256 public originalSupply; // the original total supply of old tokens event NewTokenSet(address _token); event UpgradeHasBegun(); event InvariantCheck(uint256 _oldTokenSupply, uint256 _newTokenSupply, uint256 _originalSupply, uint256 _value); function UpgradeAgent(address _oldToken) public { require(_oldToken != 0); oldToken = OldToken(_oldToken); require(oldToken.isVowmeToken()); owner = msg.sender; isUpgradeAgent = true; } /// @notice Check to make sure that the current sum of old and /// new version tokens is still equal to the original number of old version /// tokens /// @param _value The number of VME to upgrade function safetyInvariantCheck(uint256 _value) public { require(newToken.isNewToken()); // abort if new token contract has not been set uint oldSupply = oldToken.totalSupply(); uint newSupply = newToken.totalSupply(); InvariantCheck(oldSupply, newSupply, originalSupply, _value); require(oldSupply.add(newSupply) == originalSupply.sub(_value)); } /// @notice Gets the original token supply in oldToken. /// Called by oldToken after reaching the success state function setOriginalSupply() external { originalSupply = oldToken.totalSupply(); } /// @notice Sets the new token contract address /// @param _newToken The address of the new token contract function setNewToken(address _newToken) external { require(msg.sender == owner); require(_newToken != address(0)); require(!upgradeHasBegun); // cannot change token after upgrade has begun newToken = NewToken(_newToken); require(newToken.isNewToken()); NewTokenSet(newToken); } /// @notice Sets flag to prevent changing newToken after upgrade function setUpgradeHasBegun() internal { if (!upgradeHasBegun) { upgradeHasBegun = true; UpgradeHasBegun(); } } /// @notice Creates new version tokens from the new token /// contract /// @param _from The address of the token upgrader /// @param _value The number of tokens to upgrade function upgradeFrom(address _from, uint256 _value) external { require(msg.sender == address(oldToken)); // only upgrade from oldToken require(newToken.isNewToken()); // need a real newToken! require(!upgradeFinalized); // can't upgrade after being finalized setUpgradeHasBegun(); // Right here oldToken has already been updated, but corresponding // VME have not been created in the newToken contract yet safetyInvariantCheck(_value); newToken.createToken(_from, _value); // Right here totalSupply invariant must hold safetyInvariantCheck(0); } function finalizeUpgrade() external { require(msg.sender == owner); require(!upgradeFinalized); safetyInvariantCheck(0); upgradeFinalized = true; newToken.finalizeUpgrade(); } /// @dev Fallback function throws to avoid accidentally losing money function() public payable { require(false); } }
flag to determine if address is for a real contract or not Token information Upgrade information
contract NewToken is ERC20 { bool public isNewToken = false; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; bool public upgradeFinalized = false; address public upgradeAgent; function NewToken(address _upgradeAgent) public { require(_upgradeAgent != address(0)); isNewToken = true; upgradeAgent = _upgradeAgent; } function createToken(address _target, uint256 _amount) public { require(msg.sender == upgradeAgent); require(!upgradeFinalized); require(_amount != 0); balances[_target] = balances[_target].add(_amount); totalSupply = totalSupply.add(_amount); Transfer(_target, _target, _amount); } function finalizeUpgrade() external { require(msg.sender == upgradeAgent); require(!upgradeFinalized); upgradeFinalized = true; } function transfer(address _to, uint256 _value) public returns (bool success) { require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_to != address(0)); uint256 allowance = allowed[_from][msg.sender]; balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowance.sub(_value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { require(_value == 0 || allowed[msg.sender][_spender] == 0); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } function() public payable { require(false); } }
12,847,431
[ 1, 6420, 358, 4199, 309, 1758, 353, 364, 279, 2863, 6835, 578, 486, 3155, 1779, 17699, 1779, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 1166, 1345, 353, 4232, 39, 3462, 288, 203, 203, 565, 1426, 1071, 10783, 1345, 273, 629, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 324, 26488, 31, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 2935, 31, 203, 203, 565, 1426, 1071, 8400, 7951, 1235, 273, 629, 31, 203, 203, 565, 1758, 1071, 8400, 3630, 31, 203, 203, 565, 445, 1166, 1345, 12, 2867, 389, 15097, 3630, 13, 1071, 288, 203, 3639, 2583, 24899, 15097, 3630, 480, 1758, 12, 20, 10019, 203, 3639, 10783, 1345, 273, 638, 31, 203, 3639, 8400, 3630, 273, 389, 15097, 3630, 31, 203, 565, 289, 203, 203, 565, 445, 752, 1345, 12, 2867, 389, 3299, 16, 2254, 5034, 389, 8949, 13, 1071, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 8400, 3630, 1769, 203, 3639, 2583, 12, 5, 15097, 7951, 1235, 1769, 203, 3639, 2583, 24899, 8949, 480, 374, 1769, 203, 203, 3639, 324, 26488, 63, 67, 3299, 65, 273, 324, 26488, 63, 67, 3299, 8009, 1289, 24899, 8949, 1769, 203, 3639, 2078, 3088, 1283, 273, 2078, 3088, 1283, 18, 1289, 24899, 8949, 1769, 203, 3639, 12279, 24899, 3299, 16, 389, 3299, 16, 389, 8949, 1769, 203, 565, 289, 203, 203, 565, 445, 12409, 10784, 1435, 3903, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 8400, 3630, 1769, 203, 3639, 2583, 12, 5, 15097, 7951, 1235, 1769, 203, 3639, 8400, 7951, 1235, 273, 638, 31, 203, 565, 289, 203, 203, 565, 445, 7412, 12, 2867, 389, 869, 16, 2 ]
// SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity 0.8.4; import "./mixins/OZ/ERC721Upgradeable.sol"; import "./mixins/roles/WethioAdminRole.sol"; import "./mixins/roles/WethioOperatorRole.sol"; import "./mixins/WethioMarketNode.sol"; import "./mixins/WethioTreasuryNode.sol"; import "./mixins/NFT721Metadata.sol"; import "./mixins/NFT721Mint.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; /** * @title Wethio NFTs implemented using the ERC-721 standard. * @dev This top level file holds no data directly to ease future upgrades. */ contract WethioNFT is WethioTreasuryNode, WethioAdminRole, WethioOperatorRole, ERC721Upgradeable, WethioMarketNode, NFT721Metadata, NFT721Mint, OwnableUpgradeable { /** * @notice Called once to configure the contract after the initial deployment. * @dev This farms the initialize call out to inherited contracts as needed. */ function initialize( address treasury, address market, string memory name, string memory symbol, string memory baseURI ) public initializer { WethioTreasuryNode._initializeWethioTreasuryNode(treasury); WethioMarketNode._initializeWethioMarketNode(market); ERC721Upgradeable.__ERC721_init(name, symbol); NFT721Mint._initializeNFT721Mint(); _updateBaseURI(baseURI); __Ownable_init(); } /** * @notice Allows a Wethio admin to update NFT config variables. * @dev This must be called right after the initial call to `initialize`. */ function adminUpdateConfig( string memory _baseURI, address market, address treasury ) external onlyWethioAdmin { _updateBaseURI(_baseURI); _updateWethioMarket(market); _updateWethioTreasury(treasury); } /** * @dev This is a no-op, just an explicit override to address compile errors due to inheritance. */ function _burn(uint256 tokenId) internal virtual override(ERC721Upgradeable, NFT721Metadata, NFT721Mint) { super._burn(tokenId); } } // SPDX-License-Identifier: MIT // solhint-disable /** * Copied from the OpenZeppelin repository in order to make `_tokenURIs` internal instead of private. */ pragma solidity 0.8.4; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721EnumerableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165StorageUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableMapUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165StorageUpgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable, IERC721EnumerableUpgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet; using EnumerableMapUpgradeable for EnumerableMapUpgradeable.UintToAddressMap; using StringsUpgradeable for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping(address => EnumerableSetUpgradeable.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMapUpgradeable.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) internal _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require( owner != address(0), "ERC721: balance query for the zero address" ); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return _tokenOwners.get( tokenId, "ERC721: owner query for nonexistent token" ); } /** * @dev See {IERC721Metadata-name}. */ function name() public view override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory _tokenURI = _tokenURIs[tokenId]; // If there is no base URI, return the token URI. if (bytes(_baseURI).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(_baseURI, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(_baseURI, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = 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 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 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 returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require( _exists(tokenId), "ERC721: operator query for nonexistent token" ); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require( 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); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require( _exists(tokenId), "ERC721Metadata: URI set of nonexistent token" ); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall( abi.encodeWithSelector( IERC721ReceiverUpgradeable(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer" ); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} uint256[41] private __gap; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity 0.8.4; import "../../interfaces/IAdminRole.sol"; import "../WethioTreasuryNode.sol"; /** * @notice Allows a contract to leverage the admin role defined by the Wethio treasury. */ abstract contract WethioAdminRole is WethioTreasuryNode { // This file uses 0 data slots (other than what's included via WethioTreasuryNode) modifier onlyWethioAdmin() { require( _isWethioAdmin(), "WethioAdminRole: caller does not have the Admin role" ); _; } function _isWethioAdmin() internal view returns (bool) { return IAdminRole(getWethioTreasury()).isAdmin(msg.sender); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity 0.8.4; import "../../interfaces/IOperatorRole.sol"; import "../WethioTreasuryNode.sol"; /** * @notice Allows a contract to leverage the operator role defined by the Wethio treasury. */ abstract contract WethioOperatorRole is WethioTreasuryNode { // This file uses 0 data slots (other than what's included via WethioTreasuryNode) function _isWethioOperator() internal view returns (bool) { return IOperatorRole(getWethioTreasury()).isOperator(msg.sender); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity 0.8.4; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; /** * @notice A mixin that stores a reference to the Wethio market contract. */ abstract contract WethioMarketNode is Initializable { using AddressUpgradeable for address; address private market; /** * @dev Called once after the initial deployment to set the Wethio treasury address. */ function _initializeWethioMarketNode(address _market) internal initializer { require( _market.isContract(), "Wethio MarketNode: Address is not a contract" ); market = _market; } /** * @notice Returns the address of the Wethio market. */ function getWethioMarket() public view returns (address) { return market; } /** * @notice Updates the address of the Wethio treasury. */ function _updateWethioMarket(address _market) internal { require( _market.isContract(), "Wethio MarketNode: Address is not a contract" ); market = _market; } uint256[1000] private __gap; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity 0.8.4; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; /** * @notice A mixin that stores a reference to the Wethio treasury contract. */ abstract contract WethioTreasuryNode is Initializable { using AddressUpgradeable for address; address private treasury; /** * @dev Called once after the initial deployment to set the Wethio treasury address. */ function _initializeWethioTreasuryNode(address _treasury) internal initializer { require( _treasury.isContract(), "WethioTreasuryNode: Address is not a contract" ); treasury = _treasury; } /** * @notice Returns the address of the Wethio treasury. */ function getWethioTreasury() public view returns (address) { return treasury; } /** * @notice Updates the address of the Wethio treasury. */ function _updateWethioTreasury(address _treasury) internal { require( _treasury.isContract(), "WethioTreasuryNode: Address is not a contract" ); treasury = _treasury; } uint256[1000] private __gap; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity 0.8.4; import "./OZ/ERC721Upgradeable.sol"; import "./roles/WethioAdminRole.sol"; /** * @notice A mixin to extend the OpenZeppelin metadata implementation. */ abstract contract NFT721Metadata is WethioAdminRole, ERC721Upgradeable { using StringsUpgradeable for uint256; /** * @dev Stores hashes minted by a creator to prevent duplicates. */ mapping(address => mapping(string => bool)) private creatorToIPFSHashToMinted; event BaseURIUpdated(string baseURI); event TokenUriUpdated( uint256 indexed tokenId, string indexed indexedTokenUri, string tokenPath ); modifier onlyCreatorAndOwner(uint256 tokenId) { require( ownerOf(tokenId) == msg.sender || _isWethioAdmin(), "NFT721Creator: Caller does not own the NFT or not the admin" ); _; } /** * @notice Checks if the creator has already minted a given NFT. */ function getHasCreatorMintedTokenUri( address creator, string memory tokenUri ) external view returns (bool) { return creatorToIPFSHashToMinted[creator][tokenUri]; } /** * @notice Sets the token uri. */ function _setTokenUriPath(uint256 tokenId, string memory _tokenIPFSPath) internal { require( bytes(_tokenIPFSPath).length >= 46, "NFT721Metadata: Invalid IPFS path" ); require( !creatorToIPFSHashToMinted[msg.sender][_tokenIPFSPath], "NFT721Metadata: NFT was already minted" ); creatorToIPFSHashToMinted[msg.sender][_tokenIPFSPath] = true; _setTokenURI(tokenId, _tokenIPFSPath); } function _updateBaseURI(string memory _baseURI) internal { _setBaseURI(_baseURI); emit BaseURIUpdated(_baseURI); } /** * @notice Allows the creator to burn if they currently own the NFT. */ function burn(uint256 tokenId) public onlyCreatorAndOwner(tokenId) { _burn(tokenId); } /** * @dev Remove the record when burned. */ function _burn(uint256 tokenId) internal virtual override { delete creatorToIPFSHashToMinted[msg.sender][_tokenURIs[tokenId]]; super._burn(tokenId); } uint256[1000] private __gap; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity 0.8.4; import "./OZ/ERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "./WethioMarketNode.sol"; import "./NFT721Metadata.sol"; import "./roles/WethioAdminRole.sol"; /** * @notice Allows creators to mint NFTs. */ abstract contract NFT721Mint is WethioAdminRole, ERC721Upgradeable, WethioMarketNode, NFT721Metadata { using AddressUpgradeable for address; uint256 private nextTokenId; event Minted( address indexed creator, uint256 indexed tokenId, string tokenUri ); /** * @notice Gets the tokenId of the next NFT minted. */ function getNextTokenId() public view returns (uint256) { return nextTokenId; } /** * @dev Called once after the initial deployment to set the initial tokenId. */ function _initializeNFT721Mint() internal initializer { // Use ID 1 for the first NFT tokenId nextTokenId = 0; } /** * @notice Allows a creator to mint an NFT. */ function mintAndApproveMarket(string memory tokenPath) public returns (uint256 tokenId) { tokenId = nextTokenId++; _mint(address(msg.sender), tokenId); _setTokenUriPath(tokenId, tokenPath); setApprovalForAll(getWethioMarket(), true); emit Minted(msg.sender, tokenId, tokenPath); } /** * @dev Explicit override to address compile errors. */ function _burn(uint256 tokenId) internal virtual override(ERC721Upgradeable, NFT721Metadata) { super._burn(tokenId); } uint256[1000] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal onlyInitializing { __Context_init_unchained(); __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); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721EnumerableUpgradeable is IERC721Upgradeable { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165Storage.sol) pragma solidity ^0.8.0; import "./ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Storage based implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165StorageUpgradeable is Initializable, ERC165Upgradeable { function __ERC165Storage_init() internal onlyInitializing { __ERC165_init_unchained(); __ERC165Storage_init_unchained(); } function __ERC165Storage_init_unchained() internal onlyInitializing { } /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return super.supportsInterface(interfaceId) || _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // 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 { __Context_init_unchained(); } 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; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol) pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableMap.sol) pragma solidity ^0.8.0; import "./EnumerableSetUpgradeable.sol"; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMapUpgradeable { using EnumerableSetUpgradeable for EnumerableSetUpgradeable.Bytes32Set; // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct Map { // Storage of keys EnumerableSetUpgradeable.Bytes32Set _keys; mapping(bytes32 => bytes32) _values; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set( Map storage map, bytes32 key, bytes32 value ) private returns (bool) { map._values[key] = value; return map._keys.add(key); } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { delete map._values[key]; return map._keys.remove(key); } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._keys.contains(key); } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._keys.length(); } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { bytes32 key = map._keys.at(index); return (key, map._values[key]); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { bytes32 value = map._values[key]; if (value == bytes32(0)) { return (_contains(map, key), bytes32(0)); } else { return (true, value); } } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { bytes32 value = map._values[key]; require(value != 0 || _contains(map, key), "EnumerableMap: nonexistent key"); return value; } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get( Map storage map, bytes32 key, string memory errorMessage ) private view returns (bytes32) { bytes32 value = map._values[key]; require(value != 0 || _contains(map, key), errorMessage); return value; } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set( UintToAddressMap storage map, uint256 key, address value ) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get( UintToAddressMap storage map, uint256 key, string memory errorMessage ) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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 a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal onlyInitializing { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity 0.8.4; /** * @notice Interface for AdminRole which wraps the default admin role from * OpenZeppelin's AccessControl for easy integration. */ interface IAdminRole { function isAdmin(address account) external view returns (bool); } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity 0.8.4; /** * @notice Interface for OperatorRole which wraps a role from * OpenZeppelin's AccessControl for easy integration. */ interface IOperatorRole { function isOperator(address account) external view returns (bool); }
* @dev Library for managing an enumerable variant of Solidity's type. Maps have the following properties: - Entries are added, removed, and checked for existence in constant time (O(1)). - Entries are enumerated in O(n). No guarantees are made on the ordering. ``` contract Example { using EnumerableMap for EnumerableMap.UintToAddressMap; EnumerableMap.UintToAddressMap private myMap; } ``` As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are supported./ To implement this library for multiple types with as little code repetition as possible, we write it in terms of a generic Map type with bytes32 keys and values. The Map implementation uses private functions, and user-facing implementations (such as Uint256ToAddressMap) are just wrappers around the underlying Map. This means that we can only create new EnumerableMaps for types that fit in bytes32.
library EnumerableMapUpgradeable { using EnumerableSetUpgradeable for EnumerableSetUpgradeable.Bytes32Set; struct Map { EnumerableSetUpgradeable.Bytes32Set _keys; mapping(bytes32 => bytes32) _values; } function _set( Map storage map, bytes32 key, bytes32 value ) private returns (bool) { map._values[key] = value; return map._keys.add(key); } function _remove(Map storage map, bytes32 key) private returns (bool) { delete map._values[key]; return map._keys.remove(key); } function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._keys.contains(key); } function _length(Map storage map) private view returns (uint256) { return map._keys.length(); } function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { bytes32 key = map._keys.at(index); return (key, map._values[key]); } function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { bytes32 value = map._values[key]; if (value == bytes32(0)) { return (_contains(map, key), bytes32(0)); return (true, value); } } function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { bytes32 value = map._values[key]; if (value == bytes32(0)) { return (_contains(map, key), bytes32(0)); return (true, value); } } } else { function _get(Map storage map, bytes32 key) private view returns (bytes32) { bytes32 value = map._values[key]; require(value != 0 || _contains(map, key), "EnumerableMap: nonexistent key"); return value; } function _get( Map storage map, bytes32 key, string memory errorMessage ) private view returns (bytes32) { bytes32 value = map._values[key]; require(value != 0 || _contains(map, key), errorMessage); return value; } struct UintToAddressMap { Map _inner; } function set( UintToAddressMap storage map, uint256 key, address value ) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } function get( UintToAddressMap storage map, uint256 key, string memory errorMessage ) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } }
268,912
[ 1, 9313, 364, 30632, 392, 14873, 5437, 434, 348, 7953, 560, 1807, 618, 18, 19837, 1240, 326, 3751, 1790, 30, 300, 19411, 854, 3096, 16, 3723, 16, 471, 5950, 364, 15782, 316, 5381, 813, 261, 51, 12, 21, 13, 2934, 300, 19411, 854, 3557, 690, 316, 531, 12, 82, 2934, 2631, 28790, 854, 7165, 603, 326, 9543, 18, 31621, 6835, 5090, 288, 377, 1450, 6057, 25121, 863, 364, 6057, 25121, 863, 18, 5487, 774, 1887, 863, 31, 377, 6057, 25121, 863, 18, 5487, 774, 1887, 863, 3238, 3399, 863, 31, 289, 31621, 2970, 434, 331, 23, 18, 20, 18, 20, 16, 1338, 7565, 434, 618, 1375, 11890, 5034, 317, 1758, 68, 21863, 5487, 774, 1887, 863, 24065, 854, 3260, 18, 19, 2974, 2348, 333, 5313, 364, 3229, 1953, 598, 487, 12720, 981, 31239, 487, 3323, 16, 732, 1045, 518, 316, 6548, 434, 279, 5210, 1635, 618, 598, 1731, 1578, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 12083, 6057, 25121, 863, 10784, 429, 288, 203, 565, 1450, 6057, 25121, 694, 10784, 429, 364, 6057, 25121, 694, 10784, 429, 18, 2160, 1578, 694, 31, 203, 203, 203, 203, 565, 1958, 1635, 288, 203, 3639, 6057, 25121, 694, 10784, 429, 18, 2160, 1578, 694, 389, 2452, 31, 203, 3639, 2874, 12, 3890, 1578, 516, 1731, 1578, 13, 389, 2372, 31, 203, 565, 289, 203, 203, 565, 445, 389, 542, 12, 203, 3639, 1635, 2502, 852, 16, 203, 3639, 1731, 1578, 498, 16, 203, 3639, 1731, 1578, 460, 203, 565, 262, 3238, 1135, 261, 6430, 13, 288, 203, 3639, 852, 6315, 2372, 63, 856, 65, 273, 460, 31, 203, 3639, 327, 852, 6315, 2452, 18, 1289, 12, 856, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 4479, 12, 863, 2502, 852, 16, 1731, 1578, 498, 13, 3238, 1135, 261, 6430, 13, 288, 203, 3639, 1430, 852, 6315, 2372, 63, 856, 15533, 203, 3639, 327, 852, 6315, 2452, 18, 4479, 12, 856, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 12298, 12, 863, 2502, 852, 16, 1731, 1578, 498, 13, 3238, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 852, 6315, 2452, 18, 12298, 12, 856, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 2469, 12, 863, 2502, 852, 13, 3238, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 852, 6315, 2452, 18, 2469, 5621, 203, 565, 289, 203, 203, 565, 445, 389, 270, 12, 863, 2502, 852, 16, 2254, 5034, 770, 13, 3238, 1476, 1135, 261, 3890, 1578, 2 ]
./partial_match/1/0xe3Ff511d558d5476Eb535A23c92F307A4F98C3Fe/sources/FRNCoinCrowdsale.sol
* 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/
) Ownable() { require(_endTime > 0); require(_rate > 0); require(_wallet != 0x0); require(_tokenHolder != 0x0); token = StandardToken(tokenAddress); endTime = _endTime; rate = _rate; wallet = _wallet; tokenPoolAddress = _tokenHolder; }
3,642,987
[ 1, 2575, 364, 1147, 23701, 2907, 225, 5405, 343, 14558, 10354, 30591, 364, 326, 2430, 225, 27641, 74, 14463, 814, 10354, 2363, 326, 2430, 225, 460, 732, 291, 30591, 364, 23701, 225, 3844, 3844, 434, 2430, 5405, 343, 8905, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 262, 14223, 6914, 1435, 288, 203, 565, 2583, 24899, 409, 950, 405, 374, 1769, 203, 565, 2583, 24899, 5141, 405, 374, 1769, 203, 565, 2583, 24899, 19177, 480, 374, 92, 20, 1769, 203, 565, 2583, 24899, 2316, 6064, 480, 374, 92, 20, 1769, 203, 203, 565, 1147, 273, 8263, 1345, 12, 2316, 1887, 1769, 203, 565, 13859, 273, 389, 409, 950, 31, 203, 565, 4993, 273, 389, 5141, 31, 203, 565, 9230, 273, 389, 19177, 31, 203, 565, 1147, 2864, 1887, 273, 389, 2316, 6064, 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 ]
pragma solidity ^0.4.19; contract IGold { function balanceOf(address _owner) public constant returns (uint256); function issueTokens(address _who, uint _tokens) public; function burnTokens(address _who, uint _tokens) public; } // StdToken inheritance is commented, because no &#39;totalSupply&#39; needed contract IMNTP { /*is StdToken */ function balanceOf(address _owner) public constant returns (uint256); // Additional methods that MNTP contract provides function lockTransfer(bool _lock) public; function issueTokens(address _who, uint _tokens) public; function burnTokens(address _who, uint _tokens) public; } contract SafeMath { function safeAdd(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } function safeSub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function safeMul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } function safeDiv(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; } } contract CreatorEnabled { address public creator = 0x0; modifier onlyCreator() { require(msg.sender == creator); _; } function changeCreator(address _to) public onlyCreator { creator = _to; } } contract StringMover { function stringToBytes32(string s) public constant returns(bytes32){ bytes32 out; assembly { out := mload(add(s, 32)) } return out; } function stringToBytes64(string s) public constant returns(bytes32,bytes32){ bytes32 out; bytes32 out2; assembly { out := mload(add(s, 32)) out2 := mload(add(s, 64)) } return (out,out2); } function bytes32ToString(bytes32 x) public constant returns (string) { bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint j = 0; j < 32; j++) { byte char = byte(bytes32(uint(x) * 2 ** (8 * j))); if (char != 0) { bytesString[charCount] = char; charCount++; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (j = 0; j < charCount; j++) { bytesStringTrimmed[j] = bytesString[j]; } return string(bytesStringTrimmed); } function bytes64ToString(bytes32 x, bytes32 y) public constant returns (string) { bytes memory bytesString = new bytes(64); uint charCount = 0; for (uint j = 0; j < 32; j++) { byte char = byte(bytes32(uint(x) * 2 ** (8 * j))); if (char != 0) { bytesString[charCount] = char; charCount++; } } for (j = 0; j < 32; j++) { char = byte(bytes32(uint(y) * 2 ** (8 * j))); if (char != 0) { bytesString[charCount] = char; charCount++; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (j = 0; j < charCount; j++) { bytesStringTrimmed[j] = bytesString[j]; } return string(bytesStringTrimmed); } } contract Storage is SafeMath, StringMover { function Storage() public { controllerAddress = msg.sender; } address public controllerAddress = 0x0; modifier onlyController() { require(msg.sender==controllerAddress); _; } function setControllerAddress(address _newController) public onlyController { controllerAddress = _newController; } address public hotWalletAddress = 0x0; function setHotWalletAddress(address _address) public onlyController { hotWalletAddress = _address; } // Fields - 1 mapping(uint => string) docs; uint public docCount = 0; // Fields - 2 mapping(string => mapping(uint => int)) fiatTxs; mapping(string => uint) fiatBalancesCents; mapping(string => uint) fiatTxCounts; uint fiatTxTotal = 0; // Fields - 3 mapping(string => mapping(uint => int)) goldTxs; mapping(string => uint) goldHotBalances; mapping(string => uint) goldTxCounts; uint goldTxTotal = 0; // Fields - 4 struct Request { address sender; string userId; uint reference; bool buyRequest; // otherwise - sell uint inputAmount; // 0 - init // 1 - processed // 2 - cancelled uint8 state; uint outputAmount; } mapping (uint=>Request) requests; uint public requestsCount = 0; /////// function addDoc(string _ipfsDocLink) public onlyController returns(uint) { docs[docCount] = _ipfsDocLink; uint out = docCount; docCount++; return out; } function getDocCount() public constant returns (uint) { return docCount; } function getDocAsBytes64(uint _index) public constant returns (bytes32,bytes32) { require(_index < docCount); return stringToBytes64(docs[_index]); } function addFiatTransaction(string _userId, int _amountCents) public onlyController returns(uint) { require(0 != _amountCents); uint c = fiatTxCounts[_userId]; fiatTxs[_userId][c] = _amountCents; if (_amountCents > 0) { fiatBalancesCents[_userId] = safeAdd(fiatBalancesCents[_userId], uint(_amountCents)); } else { fiatBalancesCents[_userId] = safeSub(fiatBalancesCents[_userId], uint(-_amountCents)); } fiatTxCounts[_userId] = safeAdd(fiatTxCounts[_userId], 1); fiatTxTotal++; return c; } function getFiatTransactionsCount(string _userId) public constant returns (uint) { return fiatTxCounts[_userId]; } function getAllFiatTransactionsCount() public constant returns (uint) { return fiatTxTotal; } function getFiatTransaction(string _userId, uint _index) public constant returns(int) { require(_index < fiatTxCounts[_userId]); return fiatTxs[_userId][_index]; } function getUserFiatBalance(string _userId) public constant returns(uint) { return fiatBalancesCents[_userId]; } function addGoldTransaction(string _userId, int _amount) public onlyController returns(uint) { require(0 != _amount); uint c = goldTxCounts[_userId]; goldTxs[_userId][c] = _amount; if (_amount > 0) { goldHotBalances[_userId] = safeAdd(goldHotBalances[_userId], uint(_amount)); } else { goldHotBalances[_userId] = safeSub(goldHotBalances[_userId], uint(-_amount)); } goldTxCounts[_userId] = safeAdd(goldTxCounts[_userId], 1); goldTxTotal++; return c; } function getGoldTransactionsCount(string _userId) public constant returns (uint) { return goldTxCounts[_userId]; } function getAllGoldTransactionsCount() public constant returns (uint) { return goldTxTotal; } function getGoldTransaction(string _userId, uint _index) public constant returns(int) { require(_index < goldTxCounts[_userId]); return goldTxs[_userId][_index]; } function getUserHotGoldBalance(string _userId) public constant returns(uint) { return goldHotBalances[_userId]; } function addBuyTokensRequest(address _who, string _userId, uint _reference, uint _amount) public onlyController returns(uint) { Request memory r; r.sender = _who; r.userId = _userId; r.reference = _reference; r.buyRequest = true; r.inputAmount = _amount; r.state = 0; requests[requestsCount] = r; uint out = requestsCount; requestsCount++; return out; } function addSellTokensRequest(address _who, string _userId, uint _reference, uint _amount) public onlyController returns(uint) { Request memory r; r.sender = _who; r.userId = _userId; r.reference = _reference; r.buyRequest = false; r.inputAmount = _amount; r.state = 0; requests[requestsCount] = r; uint out = requestsCount; requestsCount++; return out; } function getRequestsCount() public constant returns(uint) { return requestsCount; } function getRequest(uint _index) public constant returns(address, bytes32, uint, bool, uint8, uint) { require(_index < requestsCount); Request memory r = requests[_index]; bytes32 userBytes = stringToBytes32(r.userId); return (r.sender, userBytes, r.reference, r.buyRequest, r.state, r.inputAmount); } function getRequestBaseInfo(uint _index) public constant returns(address, uint8, uint, uint) { require(_index < requestsCount); Request memory r = requests[_index]; return (r.sender, r.state, r.inputAmount, r.outputAmount); } function cancelRequest(uint _index) onlyController public { require(_index < requestsCount); require(0==requests[_index].state); requests[_index].state = 2; } function setRequestFailed(uint _index) onlyController public { require(_index < requestsCount); require(0==requests[_index].state); requests[_index].state = 3; } function setRequestProcessed(uint _index, uint _outputAmount) onlyController public { require(_index < requestsCount); require(0==requests[_index].state); requests[_index].state = 1; requests[_index].outputAmount = _outputAmount; } } contract GoldIssueBurnFee is CreatorEnabled, StringMover { string gmUserId = ""; // Functions: function GoldIssueBurnFee(string _gmUserId) public { creator = msg.sender; gmUserId = _gmUserId; } function getGoldmintFeeAccount() public constant returns(bytes32) { bytes32 userBytes = stringToBytes32(gmUserId); return userBytes; } function setGoldmintFeeAccount(string _gmUserId) public onlyCreator { gmUserId = _gmUserId; } function calculateIssueGoldFee(uint _mntpBalance, uint _value, bool _forFiat) public constant returns(uint) { return 0; } function calculateBurnGoldFee(uint _mntpBalance, uint _value, bool _forFiat) public constant returns(uint) { // if burn is for crypocurrencies, then fee is 0.1% if (!_forFiat) return (1 * _value / 1000); // If the sender holds 0 MNTP, then the fee is 3%, // If the sender holds at least 10 MNTP, then the fee is 2%, // If the sender holds at least 1000 MNTP, then the fee is 1.5%, // If the sender holds at least 10000 MNTP, then the fee is 1%, if (_mntpBalance >= (10000 * 1 ether)) { return (75 * _value / 10000); } if (_mntpBalance >= (1000 * 1 ether)) { return (15 * _value / 1000); } if (_mntpBalance >= (10 * 1 ether)) { return (25 * _value / 1000); } // 3% return (3 * _value / 100); } } contract IGoldIssueBurnFee { function getGoldmintFeeAccount()public constant returns(bytes32); function calculateIssueGoldFee(uint _mntpBalance, uint _goldValue, bool _forFiat) public constant returns(uint); function calculateBurnGoldFee(uint _mntpBalance, uint _goldValue, bool _forFiat) public constant returns(uint); } contract StorageController is SafeMath, CreatorEnabled, StringMover { Storage public stor; IMNTP public mntpToken; IGold public goldToken; IGoldIssueBurnFee public goldIssueBurnFee; address public managerAddress = 0x0; event TokenBuyRequest(address _from, string _userId, uint _reference, uint _amount, uint indexed _index); event TokenSellRequest(address _from, string _userId, uint _reference, uint _amount, uint indexed _index); event RequestCancelled(uint indexed _index); event RequestProcessed(uint indexed _index); event RequestFailed(uint indexed _index); modifier onlyManagerOrCreator() { require(msg.sender == managerAddress || msg.sender == creator); _; } function StorageController(address _mntpContractAddress, address _goldContractAddress, address _storageAddress, address _goldIssueBurnFeeContract) public { creator = msg.sender; if (0 != _storageAddress) { // use existing storage stor = Storage(_storageAddress); } else { stor = new Storage(); } require(0x0!=_mntpContractAddress); require(0x0!=_goldContractAddress); require(0x0!=_goldIssueBurnFeeContract); mntpToken = IMNTP(_mntpContractAddress); goldToken = IGold(_goldContractAddress); goldIssueBurnFee = IGoldIssueBurnFee(_goldIssueBurnFeeContract); } function setManagerAddress(address _address) public onlyCreator { managerAddress = _address; } // Only old controller can call setControllerAddress function changeController(address _newController) public onlyCreator { stor.setControllerAddress(_newController); } function setHotWalletAddress(address _hotWalletAddress) public onlyCreator { stor.setHotWalletAddress(_hotWalletAddress); } function getHotWalletAddress() public constant returns (address) { return stor.hotWalletAddress(); } function changeGoldIssueBurnFeeContract(address _goldIssueBurnFeeAddress) public onlyCreator { goldIssueBurnFee = IGoldIssueBurnFee(_goldIssueBurnFeeAddress); } function addDoc(string _ipfsDocLink) public onlyManagerOrCreator returns(uint) { return stor.addDoc(_ipfsDocLink); } function getDocCount() public constant returns (uint) { return stor.getDocCount(); } function getDoc(uint _index) public constant returns (string) { bytes32 x; bytes32 y; (x, y) = stor.getDocAsBytes64(_index); return bytes64ToString(x,y); } function addGoldTransaction(string _userId, int _amount) public onlyManagerOrCreator returns(uint) { return stor.addGoldTransaction(_userId, _amount); } function getGoldTransactionsCount(string _userId) public constant returns (uint) { return stor.getGoldTransactionsCount(_userId); } function getAllGoldTransactionsCount() public constant returns (uint) { return stor.getAllGoldTransactionsCount(); } function getGoldTransaction(string _userId, uint _index) public constant returns(int) { require(keccak256(_userId) != keccak256("")); return stor.getGoldTransaction(_userId, _index); } function getUserHotGoldBalance(string _userId) public constant returns(uint) { require(keccak256(_userId) != keccak256("")); return stor.getUserHotGoldBalance(_userId); } function addBuyTokensRequest(string _userId, uint _reference) public payable returns(uint) { require(keccak256(_userId) != keccak256("")); require(msg.value > 0); uint reqIndex = stor.addBuyTokensRequest(msg.sender, _userId, _reference, msg.value); TokenBuyRequest(msg.sender, _userId, _reference, msg.value, reqIndex); return reqIndex; } function addSellTokensRequest(string _userId, uint _reference, uint _amount) public returns(uint) { require(keccak256(_userId) != keccak256("")); require(_amount > 0); uint tokenBalance = goldToken.balanceOf(msg.sender); require(tokenBalance >= _amount); burnGoldTokens(msg.sender, _amount); uint reqIndex = stor.addSellTokensRequest(msg.sender, _userId, _reference, _amount); TokenSellRequest(msg.sender, _userId, _reference, _amount, reqIndex); return reqIndex; } function getRequestsCount() public constant returns(uint) { return stor.getRequestsCount(); } function getRequest(uint _index) public constant returns(address, string, uint, bool, uint8, uint) { address sender; bytes32 userIdBytes; uint reference; bool buy; uint8 state; uint inputAmount; (sender, userIdBytes, reference, buy, state, inputAmount) = stor.getRequest(_index); string memory userId = bytes32ToString(userIdBytes); return (sender, userId, reference, buy, state, inputAmount); } function getRequestBaseInfo(uint _index) public constant returns(address, uint8, uint, uint) { return stor.getRequestBaseInfo(_index); } function cancelRequest(uint _index) onlyManagerOrCreator public { address sender; string memory userId; uint reference; bool isBuy; uint state; uint inputAmount; (sender, userId, reference, isBuy, state, inputAmount) = getRequest(_index); require(0 == state); if (isBuy) { sender.transfer(inputAmount); } else { goldToken.issueTokens(sender, inputAmount); } stor.cancelRequest(_index); RequestCancelled(_index); } function processRequest(uint _index, uint _weiPerGold) onlyManagerOrCreator public returns(bool) { require(_index < getRequestsCount()); address sender; string memory userId; uint reference; bool isBuy; uint state; uint inputAmount; (sender, userId, reference, isBuy, state, inputAmount) = getRequest(_index); require(0 == state); bool processResult = false; uint outputAmount = 0; if (isBuy) { (processResult, outputAmount) = processBuyRequest(userId, sender, inputAmount, _weiPerGold, false); } else { (processResult, outputAmount) = processSellRequest(userId, sender, inputAmount, _weiPerGold, false); } if (processResult) { stor.setRequestProcessed(_index, outputAmount); RequestProcessed(_index); } else { stor.setRequestFailed(_index); RequestFailed(_index); } return processResult; } function processBuyRequestFiat(string _userId, uint _reference, address _userAddress, uint _amountCents, uint _centsPerGold) onlyManagerOrCreator public returns(bool) { uint reqIndex = stor.addBuyTokensRequest(_userAddress, _userId, _reference, _amountCents); bool processResult = false; uint outputAmount = 0; (processResult, outputAmount) = processBuyRequest(_userId, _userAddress, _amountCents * 1 ether, _centsPerGold * 1 ether, true); if (processResult) { stor.setRequestProcessed(reqIndex, outputAmount); RequestProcessed(reqIndex); } else { stor.setRequestFailed(reqIndex); RequestFailed(reqIndex); } return processResult; } function processSellRequestFiat(uint _index, uint _centsPerGold) onlyManagerOrCreator public returns(bool) { require(_index < getRequestsCount()); address sender; string memory userId; uint reference; bool isBuy; uint state; uint inputAmount; (sender, userId, reference, isBuy, state, inputAmount) = getRequest(_index); require(0 == state); // fee uint userMntpBalance = mntpToken.balanceOf(sender); uint fee = goldIssueBurnFee.calculateBurnGoldFee(userMntpBalance, inputAmount, true); require(inputAmount > fee); if (fee > 0) { inputAmount = safeSub(inputAmount, fee); } require(inputAmount > 0); uint resultAmount = inputAmount * _centsPerGold / 1 ether; stor.setRequestProcessed(_index, resultAmount); RequestProcessed(_index); return true; } function processBuyRequest(string _userId, address _userAddress, uint _amountWei, uint _weiPerGold, bool _isFiat) internal returns(bool, uint) { require(keccak256(_userId) != keccak256("")); uint userMntpBalance = mntpToken.balanceOf(_userAddress); uint fee = goldIssueBurnFee.calculateIssueGoldFee(userMntpBalance, _amountWei, _isFiat); require(_amountWei > fee); // issue tokens minus fee uint amountWeiMinusFee = _amountWei; if (fee > 0) { amountWeiMinusFee = safeSub(_amountWei, fee); } require(amountWeiMinusFee > 0); uint tokensWei = safeDiv(uint(amountWeiMinusFee) * 1 ether, _weiPerGold); issueGoldTokens(_userAddress, tokensWei); // request from hot wallet if (isHotWallet(_userAddress)) { addGoldTransaction(_userId, int(tokensWei)); } return (true, tokensWei); } function processSellRequest(string _userId, address _userAddress, uint _amountWei, uint _weiPerGold, bool _isFiat) internal returns(bool, uint) { require(keccak256(_userId) != keccak256("")); uint amountWei = safeMul(_amountWei, _weiPerGold) / 1 ether; require(amountWei > 0); // request from hot wallet if (isHotWallet(_userAddress)) { // TODO: overflow addGoldTransaction(_userId, - int(_amountWei)); } // fee uint userMntpBalance = mntpToken.balanceOf(_userAddress); uint fee = goldIssueBurnFee.calculateBurnGoldFee(userMntpBalance, amountWei, _isFiat); require(amountWei > fee); uint amountWeiMinusFee = amountWei; if (fee > 0) { amountWeiMinusFee = safeSub(amountWei, fee); } require(amountWeiMinusFee > 0); if (amountWeiMinusFee > this.balance) { issueGoldTokens(_userAddress, _amountWei); return (false, 0); } _userAddress.transfer(amountWeiMinusFee); return (true, amountWeiMinusFee); } //////// INTERNAL REQUESTS FROM HOT WALLET function processInternalRequest(string _userId, bool _isBuy, uint _amountCents, uint _centsPerGold) onlyManagerOrCreator public { if (_isBuy) { processBuyRequest(_userId, getHotWalletAddress(), _amountCents, _centsPerGold, true); } else { processSellRequest(_userId, getHotWalletAddress(), _amountCents, _centsPerGold, true); } } function transferGoldFromHotWallet(address _to, uint _value, string _userId) onlyManagerOrCreator public { require(keccak256(_userId) != keccak256("")); uint balance = getUserHotGoldBalance(_userId); require(balance >= _value); goldToken.burnTokens(getHotWalletAddress(), _value); goldToken.issueTokens(_to, _value); addGoldTransaction(_userId, -int(_value)); } function withdrawEth(address _userAddress, uint _value) onlyManagerOrCreator public { require(_value >= 0.1 * 1 ether); if (this.balance < _value) _value = this.balance; _userAddress.transfer(_value); } function withdrawTokens(address _userAddress, uint _value) onlyManagerOrCreator public { burnGoldTokens(address(this), _value); issueGoldTokens(_userAddress, _value); } //////// function issueGoldTokens(address _userAddress, uint _tokenAmount) internal { require(0!=_tokenAmount); goldToken.issueTokens(_userAddress, _tokenAmount); } function burnGoldTokens(address _userAddress, uint _tokenAmount) internal { require(0!=_tokenAmount); goldToken.burnTokens(_userAddress, _tokenAmount); } function isHotWallet(address _address) internal returns(bool) { return _address == getHotWalletAddress(); } }
if burn is for crypocurrencies, then fee is 0.1% If the sender holds 0 MNTP, then the fee is 3%, If the sender holds at least 10 MNTP, then the fee is 2%, If the sender holds at least 1000 MNTP, then the fee is 1.5%, If the sender holds at least 10000 MNTP, then the fee is 1%,
function calculateBurnGoldFee(uint _mntpBalance, uint _value, bool _forFiat) public constant returns(uint) { if (!_forFiat) return (1 * _value / 1000); if (_mntpBalance >= (10000 * 1 ether)) { return (75 * _value / 10000); } if (_mntpBalance >= (1000 * 1 ether)) { return (15 * _value / 1000); } if (_mntpBalance >= (10 * 1 ether)) { return (25 * _value / 1000); } }
6,782,992
[ 1, 430, 18305, 353, 364, 4422, 879, 504, 295, 14695, 16, 1508, 14036, 353, 374, 18, 21, 9, 971, 326, 5793, 14798, 374, 490, 1784, 52, 16, 1508, 326, 14036, 353, 890, 9, 16, 971, 326, 5793, 14798, 622, 4520, 1728, 490, 1784, 52, 16, 1508, 326, 14036, 353, 576, 9, 16, 971, 326, 5793, 14798, 622, 4520, 4336, 490, 1784, 52, 16, 1508, 326, 14036, 353, 404, 18, 25, 9, 16, 971, 326, 5793, 14798, 622, 4520, 12619, 490, 1784, 52, 16, 1508, 326, 14036, 353, 404, 9, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4604, 38, 321, 43, 1673, 14667, 12, 11890, 389, 21818, 84, 13937, 16, 2254, 389, 1132, 16, 1426, 389, 1884, 42, 77, 270, 13, 1071, 5381, 1135, 12, 11890, 13, 288, 203, 203, 3639, 309, 16051, 67, 1884, 42, 77, 270, 13, 327, 261, 21, 380, 389, 1132, 342, 4336, 1769, 203, 203, 203, 3639, 309, 261, 67, 21818, 84, 13937, 1545, 261, 23899, 380, 404, 225, 2437, 3719, 288, 203, 2398, 327, 261, 5877, 380, 389, 1132, 342, 12619, 1769, 203, 3639, 289, 203, 203, 3639, 309, 261, 67, 21818, 84, 13937, 1545, 261, 18088, 380, 404, 225, 2437, 3719, 288, 203, 2398, 327, 261, 3600, 380, 389, 1132, 342, 4336, 1769, 203, 3639, 289, 203, 203, 3639, 309, 261, 67, 21818, 84, 13937, 1545, 261, 2163, 380, 404, 225, 2437, 3719, 288, 203, 2398, 327, 261, 2947, 380, 389, 1132, 342, 4336, 1769, 203, 3639, 289, 203, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^ 0.4.18; /** * @title Owned * @dev The Owned contract has an owner address, and provides basic authorization control */ contract Owned { address public owner; /*Set owner of the contract*/ function Owned() public { owner = msg.sender; } /*only owner can be modifier*/ modifier onlyOwner { require(msg.sender == owner); _; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Owned { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { paused = false; Unpause(); } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns(uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns(uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns(uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns(uint256) { uint256 c = a + b; assert(c >= a); return c; } } /*ERC20*/ contract TokenERC20 is Pausable { using SafeMath for uint256; // Public variables of the token string public name = "NRC"; string public symbol = "R"; uint8 public decimals = 0; // how many token units a buyer gets per wei uint256 public rate = 50000; // address where funds are collected address public wallet = 0xd3C8326064044c36B73043b009155a59e92477D0; // contributors address address public contributorsAddress = 0xa7db53CB73DBe640DbD480a928dD06f03E2aE7Bd; // company address address public companyAddress = 0x9c949b51f2CafC3A5efc427621295489B63D861D; // market Address address public marketAddress = 0x199EcdFaC25567eb4D21C995B817230050d458d9; // share of all token uint8 public constant ICO_SHARE = 20; uint8 public constant CONTRIBUTORS_SHARE = 30; uint8 public constant COMPANY_SHARE = 20; uint8 public constant MARKET_SHARE = 30; // unfronzen periods uint8 constant COMPANY_PERIODS = 10; uint8 constant CONTRIBUTORS_PERIODS = 3; // token totalsupply amount uint256 public constant TOTAL_SUPPLY = 80000000000; // ico token amount uint256 public icoTotalAmount = 16000000000; uint256 public companyPeriodsElapsed; uint256 public contributorsPeriodsElapsed; // token frozened amount uint256 public frozenSupply; uint256 public initDate; uint8 public contributorsCurrentPeriod; uint8 public companyCurrentPeriod; // This creates an array with all balances mapping(address => uint256) public balanceOf; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); event InitialToken(string desc, address indexed target, uint256 value); /** * Constrctor function * Initializes contract with initial supply tokens to the creator of the contract */ function TokenERC20( ) public { // contributors share 30% of totalSupply,but get all by 3 years uint256 tempContributors = TOTAL_SUPPLY.mul(CONTRIBUTORS_SHARE).div(100).div(CONTRIBUTORS_PERIODS); contributorsPeriodsElapsed = tempContributors; balanceOf[contributorsAddress] = tempContributors; InitialToken("contributors", contributorsAddress, tempContributors); // company shares 20% of totalSupply,but get all by 10 years uint256 tempCompany = TOTAL_SUPPLY.mul(COMPANY_SHARE).div(100).div(COMPANY_PERIODS); companyPeriodsElapsed = tempCompany; balanceOf[companyAddress] = tempCompany; InitialToken("company", companyAddress, tempCompany); // ico takes 20% of totalSupply uint256 tempIco = TOTAL_SUPPLY.mul(ICO_SHARE).div(100); icoTotalAmount = tempIco; // expand the market cost 30% of totalSupply uint256 tempMarket = TOTAL_SUPPLY.mul(MARKET_SHARE).div(100); balanceOf[marketAddress] = tempMarket; InitialToken("market", marketAddress, tempMarket); // frozenSupply waitting for being unfrozen uint256 tempFrozenSupply = TOTAL_SUPPLY.sub(tempContributors).sub(tempIco).sub(tempCompany).sub(tempMarket); frozenSupply = tempFrozenSupply; initDate = block.timestamp; contributorsCurrentPeriod = 1; companyCurrentPeriod = 1; paused = true; } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to].add(_value) > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from].add(balanceOf[_to]); // Subtract from the sender balanceOf[_from] = balanceOf[_from].sub(_value); // Add the same to the recipient balanceOf[_to] = balanceOf[_to].add(_value); Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } } /******************************************/ /* NRCToken STARTS HERE */ /******************************************/ contract NRCToken is Owned, TokenERC20 { uint256 private etherChangeRate = 10 ** 18; uint256 private minutesOneYear = 365*24*60 minutes; bool public tokenSaleActive = true; // token have been sold uint256 public totalSoldToken; // all frozenAccount addresses mapping(address => bool) public frozenAccount; /* This generates a public log event on the blockchain that will notify clients */ event LogFrozenAccount(address target, bool frozen); event LogUnfrozenTokens(string desc, address indexed targetaddress, uint256 unfrozenTokensAmount); event LogSetTokenPrice(uint256 tokenPrice); event TimePassBy(string desc, uint256 times ); /** * event for token purchase logging * @param purchaser who paid for the tokens * @param value ehter paid for purchase * @param amount amount of tokens purchased */ event LogTokenPurchase(address indexed purchaser, uint256 value, uint256 amount); // ICO finished Event event TokenSaleFinished(string desc, address indexed contributors, uint256 icoTotalAmount, uint256 totalSoldToken, uint256 leftAmount); /* Initializes contract with initial supply tokens to the creator of the contract */ function NRCToken() TokenERC20() public {} /* Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { require(_from != _to); require(_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead require(balanceOf[_from] >= _value); // Check if the sender has enough require(balanceOf[_to].add(_value) > balanceOf[_to]); // Check for overflows require(!frozenAccount[_from]); // Check if sender is frozen require(!frozenAccount[_to]); // Check if recipient is frozen balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient Transfer(_from, _to, _value); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens /// @param target Address to be frozen /// @param freeze either to freeze it or not function freezeAccount(address target, bool freeze) public onlyOwner whenNotPaused { require(target != 0x0); require(target != owner); require(frozenAccount[target] != freeze); frozenAccount[target] = freeze; LogFrozenAccount(target, freeze); } /// @notice Allow users to buy tokens for `newTokenRate` eth /// @param newTokenRate Price users can buy from the contract function setPrices(uint256 newTokenRate) public onlyOwner whenNotPaused { require(newTokenRate > 0); require(newTokenRate <= icoTotalAmount); require(tokenSaleActive); rate = newTokenRate; LogSetTokenPrice(newTokenRate); } /// @notice Buy tokens from contract by sending ether function buy() public payable whenNotPaused { // if ICO finished ,can not buy any more! require(!frozenAccount[msg.sender]); require(tokenSaleActive); require(validPurchase()); uint tokens = getTokenAmount(msg.value); // calculates the amount require(!validSoldOut(tokens)); LogTokenPurchase(msg.sender, msg.value, tokens); balanceOf[msg.sender] = balanceOf[msg.sender].add(tokens); calcTotalSoldToken(tokens); forwardFunds(); } // Override this method to have a way to add business logic to your crowdsale when buying function getTokenAmount(uint256 etherAmount) internal view returns(uint256) { uint256 temp = etherAmount.mul(rate); uint256 amount = temp.div(etherChangeRate); return amount; } // send ether to the funder wallet function forwardFunds() internal { wallet.transfer(msg.value); } // calc totalSoldToken function calcTotalSoldToken(uint256 soldAmount) internal { totalSoldToken = totalSoldToken.add(soldAmount); if (totalSoldToken >= icoTotalAmount) { tokenSaleActive = false; } } // @return true if the transaction can buy tokens function validPurchase() internal view returns(bool) { bool limitPurchase = msg.value >= 1 ether; bool isNotTheOwner = msg.sender != owner; bool isNotTheCompany = msg.sender != companyAddress; bool isNotWallet = msg.sender != wallet; bool isNotContributors = msg.sender != contributorsAddress; bool isNotMarket = msg.sender != marketAddress; return limitPurchase && isNotTheOwner && isNotTheCompany && isNotWallet && isNotContributors && isNotMarket; } // @return true if the ICO is in progress. function validSoldOut(uint256 soldAmount) internal view returns(bool) { return totalSoldToken.add(soldAmount) > icoTotalAmount; } // @return current timestamp function time() internal constant returns (uint) { return block.timestamp; } /// @dev send the rest of the tokens after the crowdsale end and /// send to contributors address function finaliseICO() public onlyOwner whenNotPaused { require(tokenSaleActive == true); uint256 tokensLeft = icoTotalAmount.sub(totalSoldToken); tokenSaleActive = false; require(tokensLeft > 0); balanceOf[contributorsAddress] = balanceOf[contributorsAddress].add(tokensLeft); TokenSaleFinished("finaliseICO", contributorsAddress, icoTotalAmount, totalSoldToken, tokensLeft); totalSoldToken = icoTotalAmount; } /// @notice freeze unfrozenAmount function unfrozenTokens() public onlyOwner whenNotPaused { require(frozenSupply >= 0); if (contributorsCurrentPeriod < CONTRIBUTORS_PERIODS) { unfrozenContributorsTokens(); unfrozenCompanyTokens(); } else { unfrozenCompanyTokens(); } } // unfrozen contributors token year by year function unfrozenContributorsTokens() internal { require(contributorsCurrentPeriod < CONTRIBUTORS_PERIODS); uint256 contributortimeShouldPassBy = contributorsCurrentPeriod * (minutesOneYear); TimePassBy("contributortimeShouldPassBy", contributortimeShouldPassBy); uint256 contributorsTimePassBy = time() - initDate; TimePassBy("contributortimePassBy", contributorsTimePassBy); contributorsCurrentPeriod = contributorsCurrentPeriod + 1; require(contributorsTimePassBy >= contributortimeShouldPassBy); frozenSupply = frozenSupply.sub(contributorsPeriodsElapsed); balanceOf[contributorsAddress] = balanceOf[contributorsAddress].add(contributorsPeriodsElapsed); LogUnfrozenTokens("contributors", contributorsAddress, contributorsPeriodsElapsed); } // unfrozen company token year by year function unfrozenCompanyTokens() internal { require(companyCurrentPeriod < COMPANY_PERIODS); uint256 companytimeShouldPassBy = companyCurrentPeriod * (minutesOneYear); TimePassBy("CompanytimeShouldPassBy", companytimeShouldPassBy); uint256 companytimePassBy = time() - initDate; TimePassBy("CompanytimePassBy", companytimePassBy); require(companytimePassBy >= companytimeShouldPassBy); companyCurrentPeriod = companyCurrentPeriod + 1; frozenSupply = frozenSupply.sub(companyPeriodsElapsed); balanceOf[companyAddress] = balanceOf[companyAddress].add(companyPeriodsElapsed); LogUnfrozenTokens("company", companyAddress, companyPeriodsElapsed); } // fallback function - do not allow any eth transfers to this contract function() external { revert(); } }
@dev send the rest of the tokens after the crowdsale end and send to contributors address
function finaliseICO() public onlyOwner whenNotPaused { require(tokenSaleActive == true); uint256 tokensLeft = icoTotalAmount.sub(totalSoldToken); tokenSaleActive = false; require(tokensLeft > 0); balanceOf[contributorsAddress] = balanceOf[contributorsAddress].add(tokensLeft); TokenSaleFinished("finaliseICO", contributorsAddress, icoTotalAmount, totalSoldToken, tokensLeft); totalSoldToken = icoTotalAmount; }
1,770,874
[ 1, 4661, 326, 3127, 434, 326, 2430, 1839, 326, 276, 492, 2377, 5349, 679, 471, 1366, 358, 13608, 13595, 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 ]
[ 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, 727, 784, 2871, 51, 1435, 1071, 1338, 5541, 1347, 1248, 28590, 288, 203, 3639, 2583, 12, 2316, 30746, 3896, 422, 638, 1769, 540, 203, 3639, 2254, 5034, 2430, 3910, 273, 277, 2894, 5269, 6275, 18, 1717, 12, 4963, 55, 1673, 1345, 1769, 203, 3639, 1147, 30746, 3896, 273, 629, 31, 203, 3639, 2583, 12, 7860, 3910, 405, 374, 1769, 203, 3639, 11013, 951, 63, 26930, 13595, 1887, 65, 273, 11013, 951, 63, 26930, 13595, 1887, 8009, 1289, 12, 7860, 3910, 1769, 203, 3639, 3155, 30746, 10577, 2932, 6385, 784, 2871, 51, 3113, 13608, 13595, 1887, 16, 277, 2894, 5269, 6275, 16, 2078, 55, 1673, 1345, 16, 2430, 3910, 1769, 203, 3639, 2078, 55, 1673, 1345, 273, 277, 2894, 5269, 6275, 31, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; contract DSAuthority { function canCall( address src, address dst, bytes4 sig ) public view returns (bool); } contract DSAuthEvents { event LogSetAuthority (address indexed authority); event LogSetOwner (address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; function DSAuth() public { owner = msg.sender; LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; LogSetAuthority(authority); } modifier auth { require(isAuthorized(msg.sender, msg.sig)); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, this, sig); } } } contract DSMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } } contract ERC20 { /// @return total amount of tokens function totalSupply() constant public returns (uint256 supply); /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant public returns (uint256 balance); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) public returns (bool success); /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); /// @notice `msg.sender` approves `_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) public returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant public returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract LemoSale is DSAuth, DSMath { ERC20 public token; // The LemoCoin token bool public funding = true; // funding state uint256 public startTime = 0; // crowdsale start time (in seconds) uint256 public endTime = 0; // crowdsale end time (in seconds) uint256 public finney2LemoRate = 0; // how many tokens one wei equals uint256 public tokenContributionCap = 0; // max amount raised during crowdsale uint256 public tokenContributionMin = 0; // min amount raised during crowdsale uint256 public soldAmount = 0; // total sold token amount uint256 public minPayment = 0; // min eth each time uint256 public contributionCount = 0; // triggered when contribute successful event Contribution(address indexed _contributor, uint256 _amount, uint256 _return); // triggered when refund successful event Refund(address indexed _from, uint256 _value); // triggered when crowdsale is over event Finalized(uint256 _time); modifier between(uint256 _startTime, uint256 _endTime) { require(block.timestamp >= _startTime && block.timestamp < _endTime); _; } function LemoSale(uint256 _tokenContributionMin, uint256 _tokenContributionCap, uint256 _finney2LemoRate) public { require(_finney2LemoRate > 0); require(_tokenContributionMin > 0); require(_tokenContributionCap > 0); require(_tokenContributionCap > _tokenContributionMin); finney2LemoRate = _finney2LemoRate; tokenContributionMin = _tokenContributionMin; tokenContributionCap = _tokenContributionCap; } function initialize(uint256 _startTime, uint256 _endTime, uint256 _minPaymentFinney) public auth { require(_startTime < _endTime); require(_minPaymentFinney > 0); startTime = _startTime; endTime = _endTime; // Ether is to big to pass in the function, So we use Finney. 1 Finney = 0.001 Ether minPayment = _minPaymentFinney * 1 finney; } function setTokenContract(ERC20 tokenInstance) public auth { assert(address(token) == address(0)); require(tokenInstance.balanceOf(owner) > tokenContributionMin); token = tokenInstance; } function() public payable { contribute(); } function contribute() public payable between(startTime, endTime) { uint256 max = tokenContributionCap; uint256 oldSoldAmount = soldAmount; require(oldSoldAmount < max); require(msg.value >= minPayment); uint256 reward = mul(msg.value, finney2LemoRate) / 1 finney; uint256 refundEth = 0; uint256 newSoldAmount = add(oldSoldAmount, reward); if (newSoldAmount > max) { uint over = newSoldAmount - max; refundEth = over / finney2LemoRate * 1 finney; reward = max - oldSoldAmount; soldAmount = max; } else { soldAmount = newSoldAmount; } token.transferFrom(owner, msg.sender, reward); Contribution(msg.sender, msg.value, reward); contributionCount++; if (refundEth > 0) { Refund(msg.sender, refundEth); msg.sender.transfer(refundEth); } } function finalize() public auth { require(funding); require(block.timestamp >= endTime); require(soldAmount >= tokenContributionMin); funding = false; Finalized(block.timestamp); owner.transfer(this.balance); } // Withdraw in 3 month after failed. So funds not locked in contract forever function withdraw() public auth { require(this.balance > 0); require(block.timestamp >= endTime + 3600 * 24 * 30 * 3); owner.transfer(this.balance); } function destroy() public auth { require(block.timestamp >= endTime + 3600 * 24 * 30 * 3); selfdestruct(owner); } function refund() public { require(funding); require(block.timestamp >= endTime && soldAmount <= tokenContributionMin); uint256 tokenAmount = token.balanceOf(msg.sender); require(tokenAmount > 0); // need user approve first token.transferFrom(msg.sender, owner, tokenAmount); soldAmount = sub(soldAmount, tokenAmount); uint256 refundEth = tokenAmount / finney2LemoRate * 1 finney; Refund(msg.sender, refundEth); msg.sender.transfer(refundEth); } }
crowdsale end time (in seconds)
uint256 public endTime = 0;
2,543,765
[ 1, 71, 492, 2377, 5349, 679, 813, 261, 267, 3974, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 13859, 273, 374, 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 ]
// hevm: flattened sources of src/Orchestrator.sol pragma solidity >0.4.13 >=0.4.23 >=0.5.0 <0.6.0 >=0.5.7 <0.6.0; ////// lib/abdk-libraries-solidity/src/ABDKMath64x64.sol /* * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected]> */ /* pragma solidity ^0.5.7; */ /** * Smart contract library of mathematical functions operating with signed * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is * basically a simple fraction whose numerator is signed 128-bit integer and * denominator is 2^64. As long as denominator is always the same, there is no * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are * represented by int128 type holding only the numerator. */ library ABDKMath64x64 { /** * Minimum value signed 64.64-bit fixed point number may have. */ int128 private constant MIN_64x64 = -0x80000000000000000000000000000000; /** * Maximum value signed 64.64-bit fixed point number may have. */ int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Convert signed 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromInt (int256 x) internal pure returns (int128) { require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } /** * Convert signed 64.64 fixed point number into signed 64-bit integer number * rounding down. * * @param x signed 64.64-bit fixed point number * @return signed 64-bit integer number */ function toInt (int128 x) internal pure returns (int64) { return int64 (x >> 64); } /** * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromUInt (uint256 x) internal pure returns (int128) { require (x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } /** * Convert signed 64.64 fixed point number into unsigned 64-bit integer * number rounding down. Revert on underflow. * * @param x signed 64.64-bit fixed point number * @return unsigned 64-bit integer number */ function toUInt (int128 x) internal pure returns (uint64) { require (x >= 0); return uint64 (x >> 64); } /** * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point * number rounding down. Revert on overflow. * * @param x signed 128.128-bin fixed point number * @return signed 64.64-bit fixed point number */ function from128x128 (int256 x) internal pure returns (int128) { int256 result = x >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Convert signed 64.64 fixed point number into signed 128.128 fixed point * number. * * @param x signed 64.64-bit fixed point number * @return signed 128.128 fixed point number */ function to128x128 (int128 x) internal pure returns (int256) { return int256 (x) << 64; } /** * Calculate x + y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function add (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) + y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x - y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sub (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) - y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x * y rounding down. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function mul (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) * y >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point * number and y is signed 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y signed 256-bit integer number * @return signed 256-bit integer number */ function muli (int128 x, int256 y) internal pure returns (int256) { if (x == MIN_64x64) { require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF && y <= 0x1000000000000000000000000000000000000000000000000); return -y << 63; } else { bool negativeResult = false; if (x < 0) { x = -x; negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint256 absoluteResult = mulu (x, uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x8000000000000000000000000000000000000000000000000000000000000000); return -int256 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int256 (absoluteResult); } } } /** * Calculate x * y rounding down, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y unsigned 256-bit integer number * @return unsigned 256-bit integer number */ function mulu (int128 x, uint256 y) internal pure returns (uint256) { if (y == 0) return 0; require (x >= 0); uint256 lo = (uint256 (x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64; uint256 hi = uint256 (x) * (y >> 128); require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); hi <<= 64; require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo); return hi + lo; } /** * Calculate x / y rounding towards zero. Revert on overflow or when y is * zero. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function div (int128 x, int128 y) internal pure returns (int128) { require (y != 0); int256 result = (int256 (x) << 64) / y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x / y rounding towards zero, where x and y are signed 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x signed 256-bit integer number * @param y signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function divi (int256 x, int256 y) internal pure returns (int128) { require (y != 0); bool negativeResult = false; if (x < 0) { x = -x; // We rely on overflow behavior here negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint128 absoluteResult = divuu (uint256 (x), uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x80000000000000000000000000000000); return -int128 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128 (absoluteResult); // We rely on overflow behavior here } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function divu (uint256 x, uint256 y) internal pure returns (int128) { require (y != 0); uint128 result = divuu (x, y); require (result <= uint128 (MAX_64x64)); return int128 (result); } /** * Calculate -x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function neg (int128 x) internal pure returns (int128) { require (x != MIN_64x64); return -x; } /** * Calculate |x|. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function abs (int128 x) internal pure returns (int128) { require (x != MIN_64x64); return x < 0 ? -x : x; } /** * Calculate 1 / x rounding towards zero. Revert on overflow or when x is * zero. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function inv (int128 x) internal pure returns (int128) { require (x != 0); int256 result = int256 (0x100000000000000000000000000000000) / x; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function avg (int128 x, int128 y) internal pure returns (int128) { return int128 ((int256 (x) + int256 (y)) >> 1); } /** * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down. * Revert on overflow or in case x * y is negative. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function gavg (int128 x, int128 y) internal pure returns (int128) { int256 m = int256 (x) * int256 (y); require (m >= 0); require (m < 0x4000000000000000000000000000000000000000000000000000000000000000); return int128 (sqrtu (uint256 (m), uint256 (x) + uint256 (y) >> 1)); } /** * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y uint256 value * @return signed 64.64-bit fixed point number */ function pow (int128 x, uint256 y) internal pure returns (int128) { uint256 absoluteResult; bool negativeResult = false; if (x >= 0) { absoluteResult = powu (uint256 (x) << 63, y); } else { // We rely on overflow behavior here absoluteResult = powu (uint256 (uint128 (-x)) << 63, y); negativeResult = y & 1 > 0; } absoluteResult >>= 63; if (negativeResult) { require (absoluteResult <= 0x80000000000000000000000000000000); return -int128 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128 (absoluteResult); // We rely on overflow behavior here } } /** * Calculate sqrt (x) rounding down. Revert if x < 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sqrt (int128 x) internal pure returns (int128) { require (x >= 0); return int128 (sqrtu (uint256 (x) << 64, 0x10000000000000000)); } /** * Calculate binary logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function log_2 (int128 x) internal pure returns (int128) { require (x > 0); int256 msb = 0; int256 xc = x; if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 result = msb - 64 << 64; uint256 ux = uint256 (x) << 127 - msb; for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) { ux *= ux; uint256 b = ux >> 255; ux >>= 127 + b; result += bit * int256 (b); } return int128 (result); } /** * Calculate natural logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function ln (int128 x) internal pure returns (int128) { require (x > 0); return int128 ( uint256 (log_2 (x)) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128); } /** * Calculate binary exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp_2 (int128 x) internal pure returns (int128) { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow uint256 result = 0x80000000000000000000000000000000; if (x & 0x8000000000000000 > 0) result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128; if (x & 0x4000000000000000 > 0) result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128; if (x & 0x2000000000000000 > 0) result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128; if (x & 0x1000000000000000 > 0) result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128; if (x & 0x800000000000000 > 0) result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128; if (x & 0x400000000000000 > 0) result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128; if (x & 0x200000000000000 > 0) result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128; if (x & 0x100000000000000 > 0) result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128; if (x & 0x80000000000000 > 0) result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128; if (x & 0x40000000000000 > 0) result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128; if (x & 0x20000000000000 > 0) result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128; if (x & 0x10000000000000 > 0) result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128; if (x & 0x8000000000000 > 0) result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128; if (x & 0x4000000000000 > 0) result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128; if (x & 0x2000000000000 > 0) result = result * 0x1000162E525EE054754457D5995292026 >> 128; if (x & 0x1000000000000 > 0) result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128; if (x & 0x800000000000 > 0) result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128; if (x & 0x400000000000 > 0) result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128; if (x & 0x200000000000 > 0) result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128; if (x & 0x100000000000 > 0) result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128; if (x & 0x80000000000 > 0) result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128; if (x & 0x40000000000 > 0) result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128; if (x & 0x20000000000 > 0) result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128; if (x & 0x10000000000 > 0) result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128; if (x & 0x8000000000 > 0) result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128; if (x & 0x4000000000 > 0) result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128; if (x & 0x2000000000 > 0) result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128; if (x & 0x1000000000 > 0) result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128; if (x & 0x800000000 > 0) result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128; if (x & 0x400000000 > 0) result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128; if (x & 0x200000000 > 0) result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128; if (x & 0x100000000 > 0) result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128; if (x & 0x80000000 > 0) result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128; if (x & 0x40000000 > 0) result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128; if (x & 0x20000000 > 0) result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128; if (x & 0x10000000 > 0) result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128; if (x & 0x8000000 > 0) result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128; if (x & 0x4000000 > 0) result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128; if (x & 0x2000000 > 0) result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128; if (x & 0x1000000 > 0) result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128; if (x & 0x800000 > 0) result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128; if (x & 0x400000 > 0) result = result * 0x100000000002C5C85FDF477B662B26945 >> 128; if (x & 0x200000 > 0) result = result * 0x10000000000162E42FEFA3AE53369388C >> 128; if (x & 0x100000 > 0) result = result * 0x100000000000B17217F7D1D351A389D40 >> 128; if (x & 0x80000 > 0) result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128; if (x & 0x40000 > 0) result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128; if (x & 0x20000 > 0) result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128; if (x & 0x10000 > 0) result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128; if (x & 0x8000 > 0) result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128; if (x & 0x4000 > 0) result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128; if (x & 0x2000 > 0) result = result * 0x1000000000000162E42FEFA39F02B772C >> 128; if (x & 0x1000 > 0) result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128; if (x & 0x800 > 0) result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128; if (x & 0x400 > 0) result = result * 0x100000000000002C5C85FDF473DEA871F >> 128; if (x & 0x200 > 0) result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128; if (x & 0x100 > 0) result = result * 0x100000000000000B17217F7D1CF79E949 >> 128; if (x & 0x80 > 0) result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128; if (x & 0x40 > 0) result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128; if (x & 0x20 > 0) result = result * 0x100000000000000162E42FEFA39EF366F >> 128; if (x & 0x10 > 0) result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128; if (x & 0x8 > 0) result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128; if (x & 0x4 > 0) result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128; if (x & 0x2 > 0) result = result * 0x1000000000000000162E42FEFA39EF358 >> 128; if (x & 0x1 > 0) result = result * 0x10000000000000000B17217F7D1CF79AB >> 128; result >>= 63 - (x >> 64); require (result <= uint256 (MAX_64x64)); return int128 (result); } /** * Calculate natural exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp (int128 x) internal pure returns (int128) { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow return exp_2 ( int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128)); } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return unsigned 64.64-bit fixed point number */ function divuu (uint256 x, uint256 y) private pure returns (uint128) { require (y != 0); uint256 result; if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y; else { uint256 msb = 192; uint256 xc = x >> 192; if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1); require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 hi = result * (y >> 128); uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 xh = x >> 192; uint256 xl = x << 64; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here lo = hi << 128; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here assert (xh == hi >> 128); result += xl / y; } require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return uint128 (result); } /** * Calculate x^y assuming 0^0 is 1, where x is unsigned 129.127 fixed point * number and y is unsigned 256-bit integer number. Revert on overflow. * * @param x unsigned 129.127-bit fixed point number * @param y uint256 value * @return unsigned 129.127-bit fixed point number */ function powu (uint256 x, uint256 y) private pure returns (uint256) { if (y == 0) return 0x80000000000000000000000000000000; else if (x == 0) return 0; else { int256 msb = 0; uint256 xc = x; if (xc >= 0x100000000000000000000000000000000) { xc >>= 128; msb += 128; } if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 xe = msb - 127; if (xe > 0) x >>= xe; else x <<= -xe; uint256 result = 0x80000000000000000000000000000000; int256 re = 0; while (y > 0) { if (y & 1 > 0) { result = result * x; y -= 1; re += xe; if (result >= 0x8000000000000000000000000000000000000000000000000000000000000000) { result >>= 128; re += 1; } else result >>= 127; if (re < -127) return 0; // Underflow require (re < 128); // Overflow } else { x = x * x; y >>= 1; xe <<= 1; if (x >= 0x8000000000000000000000000000000000000000000000000000000000000000) { x >>= 128; xe += 1; } else x >>= 127; if (xe < -127) return 0; // Underflow require (xe < 128); // Overflow } } if (re > 0) result <<= re; else if (re < 0) result >>= -re; return result; } } /** * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer * number. * * @param x unsigned 256-bit integer number * @return unsigned 128-bit integer number */ function sqrtu (uint256 x, uint256 r) private pure returns (uint128) { if (x == 0) return 0; else { require (r > 0); while (true) { uint256 rr = x / r; if (r == rr || r + 1 == rr) return uint128 (r); else if (r == rr + 1) return uint128 (rr); r = r + rr + 1 >> 1; } } } } ////// src/interfaces/IAssimilator.sol // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /* pragma solidity ^0.5.0; */ interface IAssimilator { function intakeRaw (uint256 amount) external returns (int128); function intakeRawAndGetBalance (uint256 amount) external returns (int128, int128); function intakeNumeraire (int128 amount) external returns (uint256); function outputRaw (address dst, uint256 amount) external returns (int128); function outputRawAndGetBalance (address dst, uint256 amount) external returns (int128, int128); function outputNumeraire (address dst, int128 amount) external returns (uint256); function viewRawAmount (int128) external view returns (uint256); function viewNumeraireAmount (uint256) external view returns (int128); function viewNumeraireBalance (address) external view returns (int128); function viewNumeraireAmountAndBalance (address, uint256) external view returns (int128, int128); } ////// src/Assimilators.sol // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /* pragma solidity ^0.5.0; */ /* import "./interfaces/IAssimilator.sol"; */ /* import "abdk-libraries-solidity/ABDKMath64x64.sol"; */ library Assimilators { using ABDKMath64x64 for int128; IAssimilator constant iAsmltr = IAssimilator(address(0)); function delegate(address _callee, bytes memory _data) internal returns (bytes memory) { (bool _success, bytes memory returnData_) = _callee.delegatecall(_data); assembly { if eq(_success, 0) { revert(add(returnData_, 0x20), returndatasize()) } } return returnData_; } function viewRawAmount (address _assim, int128 _amt) internal view returns (uint256 amount_) { amount_ = IAssimilator(_assim).viewRawAmount(_amt); } function viewNumeraireAmount (address _assim, uint256 _amt) internal view returns (int128 amt_) { amt_ = IAssimilator(_assim).viewNumeraireAmount(_amt); } function viewNumeraireAmountAndBalance (address _assim, uint256 _amt) internal view returns (int128 amt_, int128 bal_) { ( amt_, bal_ ) = IAssimilator(_assim).viewNumeraireAmountAndBalance(address(this), _amt); } function viewNumeraireBalance (address _assim) internal view returns (int128 bal_) { bal_ = IAssimilator(_assim).viewNumeraireBalance(address(this)); } function intakeRaw (address _assim, uint256 _amount) internal returns (int128 amt_) { bytes memory data = abi.encodeWithSelector(iAsmltr.intakeRaw.selector, _amount); amt_ = abi.decode(delegate(_assim, data), (int128)); } function intakeRawAndGetBalance (address _assim, uint256 _amount) internal returns (int128 amt_, int128 bal_) { bytes memory data = abi.encodeWithSelector(iAsmltr.intakeRawAndGetBalance.selector, _amount); ( amt_, bal_ ) = abi.decode(delegate(_assim, data), (int128,int128)); } function intakeNumeraire (address _assim, int128 _amt) internal returns (uint256 rawAmt_) { bytes memory data = abi.encodeWithSelector(iAsmltr.intakeNumeraire.selector, _amt); rawAmt_ = abi.decode(delegate(_assim, data), (uint256)); } function outputRaw (address _assim, address _dst, uint256 _amount) internal returns (int128 amt_ ) { bytes memory data = abi.encodeWithSelector(iAsmltr.outputRaw.selector, _dst, _amount); amt_ = abi.decode(delegate(_assim, data), (int128)); amt_ = amt_.neg(); } function outputRawAndGetBalance (address _assim, address _dst, uint256 _amount) internal returns (int128 amt_, int128 bal_) { bytes memory data = abi.encodeWithSelector(iAsmltr.outputRawAndGetBalance.selector, _dst, _amount); ( amt_, bal_ ) = abi.decode(delegate(_assim, data), (int128,int128)); amt_ = amt_.neg(); } function outputNumeraire (address _assim, address _dst, int128 _amt) internal returns (uint256 rawAmt_) { bytes memory data = abi.encodeWithSelector(iAsmltr.outputNumeraire.selector, _dst, _amt.abs()); rawAmt_ = abi.decode(delegate(_assim, data), (uint256)); } } ////// src/UnsafeMath64x64.sol /* pragma solidity ^0.5.0; */ library UnsafeMath64x64 { /** * Calculate x * y rounding down. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function us_mul (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) * y >> 64; return int128 (result); } /** * Calculate x / y rounding towards zero. Revert on overflow or when y is * zero. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function us_div (int128 x, int128 y) internal pure returns (int128) { int256 result = (int256 (x) << 64) / y; return int128 (result); } } ////// src/ShellMath.sol // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /* pragma solidity ^0.5.0; */ /* import "./Assimilators.sol"; */ /* import "./UnsafeMath64x64.sol"; */ /* import "./LoihiStorage.sol"; */ /* import "abdk-libraries-solidity/ABDKMath64x64.sol"; */ library ShellMath { int128 constant ONE = 0x10000000000000000; int128 constant MAX = 0x4000000000000000; // .25 in laments terms int128 constant ONE_WEI = 0x12; using ABDKMath64x64 for int128; using UnsafeMath64x64 for int128; using ABDKMath64x64 for uint256; function calculateFee ( int128 _gLiq, int128[] memory _bals, int128 _beta, int128 _delta, int128[] memory _weights ) internal pure returns (int128 psi_) { for (uint i = 0; i < _weights.length; i++) { int128 _ideal = _gLiq.us_mul(_weights[i]); psi_ += calculateMicroFee(_bals[i], _ideal, _beta, _delta); } } function calculateMicroFee ( int128 _bal, int128 _ideal, int128 _beta, int128 _delta ) private pure returns (int128 fee_) { if (_bal < _ideal) { int128 _threshold = _ideal.us_mul(ONE - _beta); if (_bal < _threshold) { int128 _feeSection = _threshold - _bal; fee_ = _feeSection.us_div(_ideal); fee_ = fee_.us_mul(_delta); if (fee_ > MAX) fee_ = MAX; fee_ = fee_.us_mul(_feeSection); } else fee_ = 0; } else { int128 _threshold = _ideal.us_mul(ONE + _beta); if (_bal > _threshold) { int128 _feeSection = _bal - _threshold; fee_ = _feeSection.us_div(_ideal); fee_ = fee_.us_mul(_delta); if (fee_ > MAX) fee_ = MAX; fee_ = fee_.us_mul(_feeSection); } else fee_ = 0; } } function calculateTrade ( LoihiStorage.Shell storage shell, int128 _oGLiq, int128 _nGLiq, int128[] memory _oBals, int128[] memory _nBals, int128 _inputAmt, uint _outputIndex ) internal view returns (int128 outputAmt_ , int128 psi_) { outputAmt_ = - _inputAmt; int128 _lambda = shell.lambda; int128 _omega = shell.omega; int128 _beta = shell.beta; int128 _delta = shell.delta; int128[] memory _weights = shell.weights; for (uint i = 0; i < 32; i++) { psi_ = calculateFee(_nGLiq, _nBals, _beta, _delta, _weights); if (( outputAmt_ = _omega < psi_ ? - ( _inputAmt + _omega - psi_ ) : - ( _inputAmt + _lambda.us_mul(_omega - psi_)) ) / 1e13 == outputAmt_ / 1e13 ) { _nGLiq = _oGLiq + _inputAmt + outputAmt_; _nBals[_outputIndex] = _oBals[_outputIndex] + outputAmt_; enforceHalts(shell, _oGLiq, _nGLiq, _oBals, _nBals, _weights); require(ABDKMath64x64.sub(_oGLiq, _omega) <= ABDKMath64x64.sub(_nGLiq, psi_), "Shell/swap-invariant-violation"); return ( outputAmt_, psi_ ); } else { _nGLiq = _oGLiq + _inputAmt + outputAmt_; _nBals[_outputIndex] = _oBals[_outputIndex].add(outputAmt_); } } revert("Shell/swap-convergence-failed"); } function calculateLiquidityMembrane ( LoihiStorage.Shell storage shell, int128 _oGLiq, int128 _nGLiq, int128[] memory _oBals, int128[] memory _nBals ) internal view returns (int128 shells_, int128 psi_) { enforceHalts(shell, _oGLiq, _nGLiq, _oBals, _nBals, shell.weights); psi_ = calculateFee(_nGLiq, _nBals, shell.beta, shell.delta, shell.weights); int128 _omega = shell.omega; int128 _feeDiff = psi_.sub(_omega); int128 _liqDiff = _nGLiq.sub(_oGLiq); int128 _oUtil = _oGLiq.sub(_omega); uint _totalSupply = shell.totalSupply; if (_totalSupply == 0) { shells_ = _nGLiq.sub(psi_); } else if (_feeDiff >= 0) { shells_ = _liqDiff.sub(_feeDiff).div(_oUtil); } else { shells_ = _liqDiff.sub(shell.lambda.mul(_feeDiff)); shells_ = shells_.div(_oUtil); } int128 _shellsPrev = _totalSupply.divu(1e18); if (_totalSupply != 0) { shells_ = shells_.mul(_shellsPrev); int128 _prevUtilPerShell = _oGLiq.sub(_omega); _prevUtilPerShell = _prevUtilPerShell.div(_shellsPrev); int128 _nextUtilPerShell = _nGLiq.sub(psi_); _nextUtilPerShell = _nextUtilPerShell.div(_shellsPrev.add(shells_)); _nextUtilPerShell += ONE_WEI; require(_prevUtilPerShell <= _nextUtilPerShell, "Shell/invariant-violation"); } } function enforceHalts ( LoihiStorage.Shell storage shell, int128 _oGLiq, int128 _nGLiq, int128[] memory _oBals, int128[] memory _nBals, int128[] memory _weights ) private view { uint256 _length = _nBals.length; int128 _alpha = shell.alpha; for (uint i = 0; i < _length; i++) { int128 _nIdeal = _nGLiq.us_mul(_weights[i]); if (_nBals[i] > _nIdeal) { int128 _upperAlpha = ONE + _alpha; int128 _nHalt = _nIdeal.us_mul(_upperAlpha); if (_nBals[i] > _nHalt){ int128 _oHalt = _oGLiq.us_mul(_weights[i]).us_mul(_upperAlpha); if (_oBals[i] < _oHalt) revert("Shell/upper-halt"); if (_nBals[i] - _nHalt > _oBals[i] - _oHalt) revert("Shell/upper-halt"); } } else { int128 _lowerAlpha = ONE - _alpha; int128 _nHalt = _nIdeal.us_mul(_lowerAlpha); if (_nBals[i] < _nHalt){ int128 _oHalt = _oGLiq.us_mul(_weights[i]).us_mul(_lowerAlpha); if (_oBals[i] > _oHalt) revert("Shell/lower-halt"); if (_nHalt - _nBals[i] > _oHalt - _oBals[i]) revert("Shel/lower-halt"); } } } } } ////// src/Orchestrator.sol // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /* pragma solidity ^0.5.0; */ /* import "./Assimilators.sol"; */ /* import "./ShellMath.sol"; */ /* import "./LoihiStorage.sol"; */ /* import "abdk-libraries-solidity/ABDKMath64x64.sol"; */ library Orchestrator { using ABDKMath64x64 for int128; using ABDKMath64x64 for uint256; int128 constant ONE_WEI = 0x12; event ParametersSet(uint256 alpha, uint256 beta, uint256 delta, uint256 epsilon, uint256 lambda, uint256 omega); event AssetIncluded(address indexed numeraire, address indexed reserve, uint weight); event AssimilatorIncluded(address indexed derivative, address indexed numeraire, address indexed reserve, address assimilator); function setParams ( LoihiStorage.Shell storage shell, uint256 _alpha, uint256 _beta, uint256 _feeAtHalt, uint256 _epsilon, uint256 _lambda ) external { require(_alpha < 1e18 && _alpha > 0, "Shell/parameter-invalid-alpha"); require(_beta <= _alpha && _beta >= 0, "Shell/parameter-invalid-beta"); require(_feeAtHalt <= .5e18, "Shell/parameter-invalid-max"); require(_epsilon < 1e16 && _epsilon >= 0, "Shell/parameter-invalid-epsilon"); require(_lambda <= 1e18 && _lambda >= 0, "Shell/parameter-invalid-lambda"); shell.alpha = (_alpha + 1).divu(1e18); shell.beta = (_beta + 1).divu(1e18); shell.delta = ( _feeAtHalt ).divu(1e18).div(uint(2).fromUInt().mul(shell.alpha.sub(shell.beta))) + ONE_WEI; shell.epsilon = (_epsilon + 1).divu(1e18); shell.lambda = (_lambda + 1).divu(1e18); shell.omega = getNewOmega(shell); emit ParametersSet(_alpha, _beta, shell.delta.mulu(1e18), _epsilon, _lambda, shell.omega.mulu(1e18)); } function getNewOmega ( LoihiStorage.Shell storage shell ) private view returns ( int128 omega_ ) { int128 _gLiq; int128[] memory _bals = new int128[](shell.assets.length); for (uint i = 0; i < _bals.length; i++) { int128 _bal = Assimilators.viewNumeraireBalance(shell.assets[i].addr); _bals[i] = _bal; _gLiq += _bal; } omega_ = ShellMath.calculateFee(_gLiq, _bals, shell.beta, shell.delta, shell.weights); } function initialize ( LoihiStorage.Shell storage shell, address[] storage numeraires, address[] storage reserves, address[] storage derivatives, address[] calldata _assets, uint[] calldata _assetWeights, address[] calldata _derivativeAssimilators ) external { for (uint i = 0; i < _assetWeights.length; i++) { uint ix = i*5; numeraires.push(_assets[ix]); derivatives.push(_assets[ix]); reserves.push(_assets[2+ix]); if (_assets[ix] != _assets[2+ix]) derivatives.push(_assets[2+ix]); includeAsset( shell, _assets[ix], // numeraire _assets[1+ix], // numeraire assimilator _assets[2+ix], // reserve _assets[3+ix], // reserve assimilator _assets[4+ix], // reserve approve to _assetWeights[i] ); } for (uint i = 0; i < _derivativeAssimilators.length / 5; i++) { uint ix = i * 5; derivatives.push(_derivativeAssimilators[ix]); includeAssimilator( shell, _derivativeAssimilators[ix], // derivative _derivativeAssimilators[1+ix], // numeraire _derivativeAssimilators[2+ix], // reserve _derivativeAssimilators[3+ix], // assimilator _derivativeAssimilators[4+ix] // derivative approve to ); } } function includeAsset ( LoihiStorage.Shell storage shell, address _numeraire, address _numeraireAssim, address _reserve, address _reserveAssim, address _reserveApproveTo, uint256 _weight ) private { require(_numeraire != address(0), "Shell/numeraire-cannot-be-zeroth-adress"); require(_numeraireAssim != address(0), "Shell/numeraire-assimilator-cannot-be-zeroth-adress"); require(_reserve != address(0), "Shell/reserve-cannot-be-zeroth-adress"); require(_reserveAssim != address(0), "Shell/reserve-assimilator-cannot-be-zeroth-adress"); require(_weight < 1e18, "Shell/weight-must-be-less-than-one"); if (_numeraire != _reserve) safeApprove(_numeraire, _reserveApproveTo, uint(-1)); LoihiStorage.Assimilator storage _numeraireAssimilator = shell.assimilators[_numeraire]; _numeraireAssimilator.addr = _numeraireAssim; _numeraireAssimilator.ix = uint8(shell.assets.length); LoihiStorage.Assimilator storage _reserveAssimilator = shell.assimilators[_reserve]; _reserveAssimilator.addr = _reserveAssim; _reserveAssimilator.ix = uint8(shell.assets.length); int128 __weight = _weight.divu(1e18).add(uint256(1).divu(1e18)); shell.weights.push(__weight); shell.assets.push(_numeraireAssimilator); emit AssetIncluded(_numeraire, _reserve, _weight); emit AssimilatorIncluded(_numeraire, _numeraire, _numeraire, _numeraireAssim); if (_numeraireAssim != _reserveAssim) { emit AssimilatorIncluded(_numeraire, _numeraire, _reserve, _reserveAssim); } } function includeAssimilator ( LoihiStorage.Shell storage shell, address _derivative, address _numeraire, address _reserve, address _assimilator, address _derivativeApproveTo ) private { require(_derivative != address(0), "Shell/derivative-cannot-be-zeroth-address"); require(_numeraire != address(0), "Shell/numeraire-cannot-be-zeroth-address"); require(_reserve != address(0), "Shell/numeraire-cannot-be-zeroth-address"); require(_assimilator != address(0), "Shell/assimilator-cannot-be-zeroth-address"); safeApprove(_numeraire, _derivativeApproveTo, uint(-1)); LoihiStorage.Assimilator storage _numeraireAssim = shell.assimilators[_numeraire]; shell.assimilators[_derivative] = LoihiStorage.Assimilator(_assimilator, _numeraireAssim.ix); emit AssimilatorIncluded(_derivative, _numeraire, _reserve, _assimilator); } function safeApprove ( address _token, address _spender, uint256 _value ) private { ( bool success, bytes memory returndata ) = _token.call(abi.encodeWithSignature("approve(address,uint256)", _spender, _value)); require(success, "SafeERC20: low-level call failed"); } function prime (LoihiStorage.Shell storage shell) external { uint _length = shell.assets.length; int128[] memory _oBals = new int128[](_length); int128 _oGLiq; for (uint i = 0; i < _length; i++) { int128 _bal = Assimilators.viewNumeraireBalance(shell.assets[i].addr); _oGLiq += _bal; _oBals[i] = _bal; } shell.omega = ShellMath.calculateFee(_oGLiq, _oBals, shell.beta, shell.delta, shell.weights); } function viewShell ( LoihiStorage.Shell storage shell ) external view returns ( uint alpha_, uint beta_, uint delta_, uint epsilon_, uint lambda_, uint omega_ ) { alpha_ = shell.alpha.mulu(1e18); beta_ = shell.beta.mulu(1e18); delta_ = shell.delta.mulu(1e18); epsilon_ = shell.epsilon.mulu(1e18); lambda_ = shell.lambda.mulu(1e18); omega_ = shell.omega.mulu(1e18); } } ////// src/PartitionedLiquidity.sol /* pragma solidity ^0.5.0; */ /* import "./Assimilators.sol"; */ /* import "./LoihiStorage.sol"; */ /* import "./UnsafeMath64x64.sol"; */ library PartitionedLiquidity { using ABDKMath64x64 for uint; using ABDKMath64x64 for int128; using UnsafeMath64x64 for int128; event PoolPartitioned(bool); event PartitionRedeemed(address indexed token, address indexed redeemer, uint value); int128 constant ONE = 0x10000000000000000; function partition ( LoihiStorage.Shell storage shell, mapping (address => LoihiStorage.PartitionTicket) storage partitionTickets ) external { uint _length = shell.assets.length; LoihiStorage.PartitionTicket storage totalSupplyTicket = partitionTickets[address(this)]; totalSupplyTicket.initialized = true; for (uint i = 0; i < _length; i++) totalSupplyTicket.claims.push(shell.totalSupply); emit PoolPartitioned(true); } function viewPartitionClaims ( LoihiStorage.Shell storage shell, mapping (address => LoihiStorage.PartitionTicket) storage partitionTickets, address _addr ) external view returns ( uint[] memory claims_ ) { LoihiStorage.PartitionTicket storage ticket = partitionTickets[_addr]; if (ticket.initialized) return ticket.claims; uint _length = shell.assets.length; uint[] memory claims_ = new uint[](_length); uint _balance = shell.balances[msg.sender]; for (uint i = 0; i < _length; i++) claims_[i] = _balance; return claims_; } function partitionedWithdraw ( LoihiStorage.Shell storage shell, mapping (address => LoihiStorage.PartitionTicket) storage partitionTickets, address[] calldata _derivatives, uint[] calldata _withdrawals ) external returns ( uint[] memory ) { uint _length = shell.assets.length; uint _balance = shell.balances[msg.sender]; LoihiStorage.PartitionTicket storage totalSuppliesTicket = partitionTickets[address(this)]; LoihiStorage.PartitionTicket storage ticket = partitionTickets[msg.sender]; if (!ticket.initialized) { for (uint i = 0; i < _length; i++) ticket.claims.push(_balance); ticket.initialized = true; } _length = _derivatives.length; uint[] memory withdrawals_ = new uint[](_length); for (uint i = 0; i < _length; i++) { LoihiStorage.Assimilator memory _assim = shell.assimilators[_derivatives[i]]; require(totalSuppliesTicket.claims[_assim.ix] >= _withdrawals[i], "Shell/burn-exceeds-total-supply"); require(ticket.claims[_assim.ix] >= _withdrawals[i], "Shell/insufficient-balance"); require(_assim.addr != address(0), "Shell/unsupported-asset"); int128 _reserveBalance = Assimilators.viewNumeraireBalance(_assim.addr); int128 _multiplier = _withdrawals[i].divu(1e18) .div(totalSuppliesTicket.claims[_assim.ix].divu(1e18)); totalSuppliesTicket.claims[_assim.ix] = totalSuppliesTicket.claims[_assim.ix] - _withdrawals[i]; ticket.claims[_assim.ix] = ticket.claims[_assim.ix] - _withdrawals[i]; uint _withdrawal = Assimilators.outputNumeraire( _assim.addr, msg.sender, _reserveBalance.mul(_multiplier) ); withdrawals_[i] = _withdrawal; emit PartitionRedeemed(_derivatives[i], msg.sender, withdrawals_[i]); } return withdrawals_; } } ////// src/ProportionalLiquidity.sol /* pragma solidity ^0.5.0; */ /* import "./Assimilators.sol"; */ /* import "./LoihiStorage.sol"; */ /* import "./UnsafeMath64x64.sol"; */ library ProportionalLiquidity { using ABDKMath64x64 for uint; using ABDKMath64x64 for int128; using UnsafeMath64x64 for int128; event Transfer(address indexed from, address indexed to, uint256 value); int128 constant ONE = 0x10000000000000000; function proportionalDeposit ( LoihiStorage.Shell storage shell, uint256 _deposit ) external returns ( uint256 shells_, uint[] memory ) { int128 _shells = _deposit.divu(1e18); int128 _oGLiq; uint _length = shell.assets.length; int128[] memory _oBals = new int128[](_length); uint[] memory deposits_ = new uint[](_length); for (uint i = 0; i < _length; i++) { int128 _bal = Assimilators.viewNumeraireBalance(shell.assets[i].addr); _oBals[i] = _bal; _oGLiq += _bal; } if (_oGLiq == 0) { for (uint8 i = 0; i < _length; i++) { deposits_[i] = Assimilators.intakeNumeraire(shell.assets[i].addr, _shells.mul(shell.weights[i])); } } else { int128 _multiplier = _shells.div(_oGLiq); for (uint8 i = 0; i < _length; i++) { deposits_[i] = Assimilators.intakeNumeraire(shell.assets[i].addr, _oBals[i].mul(_multiplier)); } shell.omega = shell.omega.mul(ONE.add(_multiplier)); } if (shell.totalSupply > 0) _shells = _shells.div(_oGLiq).mul(shell.totalSupply.divu(1e18)); mint(shell, msg.sender, shells_ = _shells.mulu(1e18)); return (shells_, deposits_); } function viewProportionalDeposit ( LoihiStorage.Shell storage shell, uint256 _deposit ) external view returns ( uint shells_, uint[] memory ) { int128 _shells = _deposit.divu(1e18); int128 _oGLiq; uint _length = shell.assets.length; int128[] memory _oBals = new int128[](_length); uint[] memory deposits_ = new uint[](_length); for (uint i = 0; i < _length; i++) { int128 _bal = Assimilators.viewNumeraireBalance(shell.assets[i].addr); _oBals[i] = _bal; _oGLiq += _bal; } if (_oGLiq == 0) { for (uint8 i = 0; i < _length; i++) { deposits_[i] = Assimilators.viewRawAmount(shell.assets[i].addr, _shells.mul(shell.weights[i])); } } else { int128 _multiplier = _shells.div(_oGLiq); for (uint8 i = 0; i < _length; i++) { deposits_[i] = Assimilators.viewRawAmount(shell.assets[i].addr, _oBals[i].mul(_multiplier)); } } shells_ = _shells.mulu(1e18); return ( shells_, deposits_ ); } function proportionalWithdraw ( LoihiStorage.Shell storage shell, uint256 _withdrawal ) external returns ( uint[] memory ) { uint _length = shell.assets.length; int128 _oGLiq; int128[] memory _oBals = new int128[](_length); uint[] memory withdrawals_ = new uint[](_length); for (uint i = 0; i < _length; i++) { int128 _bal = Assimilators.viewNumeraireBalance(shell.assets[i].addr); _oGLiq += _bal; _oBals[i] = _bal; } int128 _multiplier = _withdrawal.divu(1e18) .mul(ONE.sub(shell.epsilon)) .div(shell.totalSupply.divu(1e18)); for (uint8 i = 0; i < _length; i++) { withdrawals_[i] = Assimilators.outputNumeraire(shell.assets[i].addr, msg.sender, _oBals[i].mul(_multiplier)); } shell.omega = shell.omega.mul(ONE.sub(_multiplier)); burn(shell, msg.sender, _withdrawal); return withdrawals_; } function viewProportionalWithdraw ( LoihiStorage.Shell storage shell, uint256 _withdrawal ) external view returns ( uint[] memory ) { uint _length = shell.assets.length; int128 _oGLiq; int128[] memory _oBals = new int128[](_length); uint[] memory withdrawals_ = new uint[](_length); for (uint i = 0; i < _length; i++) { int128 _bal = Assimilators.viewNumeraireBalance(shell.assets[i].addr); _oGLiq += _bal; _oBals[i] = _bal; } int128 _multiplier = _withdrawal.divu(1e18) .mul(ONE.sub(shell.epsilon)) .div(shell.totalSupply.divu(1e18)); for (uint8 i = 0; i < _length; i++) { withdrawals_[i] = Assimilators.viewRawAmount(shell.assets[i].addr, _oBals[i].mul(_multiplier)); } return withdrawals_; } function burn (LoihiStorage.Shell storage shell, address account, uint256 amount) private { shell.balances[account] = burn_sub(shell.balances[account], amount); shell.totalSupply = burn_sub(shell.totalSupply, amount); emit Transfer(msg.sender, address(0), amount); } function mint (LoihiStorage.Shell storage shell, address account, uint256 amount) private { shell.totalSupply = mint_add(shell.totalSupply, amount); shell.balances[account] = mint_add(shell.balances[account], amount); emit Transfer(address(0), msg.sender, amount); } function mint_add(uint x, uint y) private pure returns (uint z) { require((z = x + y) >= x, "Shell/mint-overflow"); } function burn_sub(uint x, uint y) private pure returns (uint z) { require((z = x - y) <= x, "Shell/burn-underflow"); } } ////// src/SelectiveLiquidity.sol /* pragma solidity ^0.5.0; */ /* import "./Assimilators.sol"; */ /* import "./LoihiStorage.sol"; */ /* import "./ShellMath.sol"; */ /* import "./UnsafeMath64x64.sol"; */ /* import "abdk-libraries-solidity/ABDKMath64x64.sol"; */ library SelectiveLiquidity { using ABDKMath64x64 for int128; using UnsafeMath64x64 for int128; event Transfer(address indexed from, address indexed to, uint256 value); int128 constant ONE = 0x10000000000000000; function selectiveDeposit ( LoihiStorage.Shell storage shell, address[] calldata _derivatives, uint[] calldata _amounts, uint _minShells ) external returns ( uint shells_ ) { ( int128 _oGLiq, int128 _nGLiq, int128[] memory _oBals, int128[] memory _nBals ) = getLiquidityDepositData(shell, _derivatives, _amounts); int128 _shells; ( _shells, shell.omega ) = ShellMath.calculateLiquidityMembrane(shell, _oGLiq, _nGLiq, _oBals, _nBals); shells_ = _shells.mulu(1e18); require(_minShells < shells_, "Shell/under-minimum-shells"); mint(shell, msg.sender, shells_); } function viewSelectiveDeposit ( LoihiStorage.Shell storage shell, address[] calldata _derivatives, uint[] calldata _amounts ) external view returns ( uint shells_ ) { ( int128 _oGLiq, int128 _nGLiq, int128[] memory _oBals, int128[] memory _nBals ) = viewLiquidityDepositData(shell, _derivatives, _amounts); ( int128 _shells, ) = ShellMath.calculateLiquidityMembrane(shell, _oGLiq, _nGLiq, _oBals, _nBals); shells_ = _shells.mulu(1e18); } function selectiveWithdraw ( LoihiStorage.Shell storage shell, address[] calldata _derivatives, uint[] calldata _amounts, uint _maxShells ) external returns ( uint256 shells_ ) { ( int128 _oGLiq, int128 _nGLiq, int128[] memory _oBals, int128[] memory _nBals ) = getLiquidityWithdrawData(shell, _derivatives, msg.sender, _amounts); int128 _shells; ( _shells, shell.omega ) = ShellMath.calculateLiquidityMembrane(shell, _oGLiq, _nGLiq, _oBals, _nBals); _shells = _shells.abs().us_mul(ONE + shell.epsilon); shells_ = _shells.mulu(1e18); require(shells_ < _maxShells, "Shell/above-maximum-shells"); burn(shell, msg.sender, shells_); } function viewSelectiveWithdraw ( LoihiStorage.Shell storage shell, address[] calldata _derivatives, uint[] calldata _amounts ) external view returns ( uint shells_ ) { ( int128 _oGLiq, int128 _nGLiq, int128[] memory _oBals, int128[] memory _nBals ) = viewLiquidityWithdrawData(shell, _derivatives, _amounts); ( int128 _shells, ) = ShellMath.calculateLiquidityMembrane(shell, _oGLiq, _nGLiq, _oBals, _nBals); _shells = _shells.abs().us_mul(ONE + shell.epsilon); shells_ = _shells.mulu(1e18); } function getLiquidityDepositData ( LoihiStorage.Shell storage shell, address[] memory _derivatives, uint[] memory _amounts ) private returns ( int128 oGLiq_, int128 nGLiq_, int128[] memory, int128[] memory ) { uint _length = shell.weights.length; int128[] memory oBals_ = new int128[](_length); int128[] memory nBals_ = new int128[](_length); for (uint i = 0; i < _derivatives.length; i++) { LoihiStorage.Assimilator memory _assim = shell.assimilators[_derivatives[i]]; require(_assim.addr != address(0), "Shell/unsupported-derivative"); if ( nBals_[_assim.ix] == 0 && oBals_[_assim.ix] == 0 ) { ( int128 _amount, int128 _balance ) = Assimilators.intakeRawAndGetBalance(_assim.addr, _amounts[i]); nBals_[_assim.ix] = _balance; oBals_[_assim.ix] = _balance.sub(_amount); } else { int128 _amount = Assimilators.intakeRaw(_assim.addr, _amounts[i]); nBals_[_assim.ix] = nBals_[_assim.ix].sub(_amount); } } return completeLiquidityData(shell, oBals_, nBals_); } function getLiquidityWithdrawData ( LoihiStorage.Shell storage shell, address[] memory _derivatives, address _rcpnt, uint[] memory _amounts ) private returns ( int128 oGLiq_, int128 nGLiq_, int128[] memory, int128[] memory ) { uint _length = shell.weights.length; int128[] memory oBals_ = new int128[](_length); int128[] memory nBals_ = new int128[](_length); for (uint i = 0; i < _derivatives.length; i++) { LoihiStorage.Assimilator memory _assim = shell.assimilators[_derivatives[i]]; require(_assim.addr != address(0), "Shell/unsupported-derivative"); if ( nBals_[_assim.ix] == 0 && oBals_[_assim.ix] == 0 ) { ( int128 _amount, int128 _balance ) = Assimilators.outputRawAndGetBalance(_assim.addr, _rcpnt, _amounts[i]); nBals_[_assim.ix] = _balance; oBals_[_assim.ix] = _balance.sub(_amount); } else { int128 _amount = Assimilators.outputRaw(_assim.addr, _rcpnt, _amounts[i]); nBals_[_assim.ix] = nBals_[_assim.ix].sub(_amount); } } return completeLiquidityData(shell, oBals_, nBals_); } function viewLiquidityDepositData ( LoihiStorage.Shell storage shell, address[] memory _derivatives, uint[] memory _amounts ) private view returns ( int128 oGLiq_, int128 nGLiq_, int128[] memory, int128[] memory ) { uint _length = shell.assets.length; int128[] memory oBals_ = new int128[](_length); int128[] memory nBals_ = new int128[](_length); for (uint i = 0; i < _derivatives.length; i++) { LoihiStorage.Assimilator memory _assim = shell.assimilators[_derivatives[i]]; require(_assim.addr != address(0), "Shell/unsupported-derivative"); if ( nBals_[_assim.ix] == 0 && oBals_[_assim.ix] == 0 ) { ( int128 _amount, int128 _balance ) = Assimilators.viewNumeraireAmountAndBalance(_assim.addr, _amounts[i]); nBals_[_assim.ix] = _balance.add(_amount); oBals_[_assim.ix] = _balance; } else { int128 _amount = Assimilators.viewNumeraireAmount(_assim.addr, _amounts[i]); nBals_[_assim.ix] = nBals_[_assim.ix].sub(_amount); } } return completeLiquidityData(shell, oBals_, nBals_); } function viewLiquidityWithdrawData ( LoihiStorage.Shell storage shell, address[] memory _derivatives, uint[] memory _amounts ) private view returns ( int128 oGLiq_, int128 nGLiq_, int128[] memory, int128[] memory ) { uint _length = shell.assets.length; int128[] memory oBals_ = new int128[](_length); int128[] memory nBals_ = new int128[](_length); for (uint i = 0; i < _derivatives.length; i++) { LoihiStorage.Assimilator memory _assim = shell.assimilators[_derivatives[i]]; require(_assim.addr != address(0), "Shell/unsupported-derivative"); if ( nBals_[_assim.ix] == 0 && oBals_[_assim.ix] == 0 ) { ( int128 _amount, int128 _balance ) = Assimilators.viewNumeraireAmountAndBalance(_assim.addr, _amounts[i]); nBals_[_assim.ix] = _balance.add(_amount.neg()); oBals_[_assim.ix] = _balance; } else { int128 _amount = Assimilators.viewNumeraireAmount(_assim.addr, _amounts[i]); nBals_[_assim.ix] = nBals_[_assim.ix].sub(_amount.neg()); } } return completeLiquidityData(shell, oBals_, nBals_); } function completeLiquidityData ( LoihiStorage.Shell storage shell, int128[] memory oBals_, int128[] memory nBals_ ) private view returns ( int128 oGLiq_, int128 nGLiq_, int128[] memory, int128[] memory ) { uint _length = oBals_.length; for (uint i = 0; i < _length; i++) { if (oBals_[i] == 0 && nBals_[i] == 0) nBals_[i] = oBals_[i] = Assimilators.viewNumeraireBalance(shell.assets[i].addr); oGLiq_ += oBals_[i]; nGLiq_ += nBals_[i]; } return ( oGLiq_, nGLiq_, oBals_, nBals_ ); } function burn (LoihiStorage.Shell storage shell, address account, uint256 amount) private { shell.balances[account] = burn_sub(shell.balances[account], amount); shell.totalSupply = burn_sub(shell.totalSupply, amount); emit Transfer(msg.sender, address(0), amount); } function mint (LoihiStorage.Shell storage shell, address account, uint256 amount) private { shell.totalSupply = mint_add(shell.totalSupply, amount); shell.balances[account] = mint_add(shell.balances[account], amount); emit Transfer(address(0), msg.sender, amount); } function mint_add(uint x, uint y) private pure returns (uint z) { require((z = x + y) >= x, "Shell/mint-overflow"); } function burn_sub(uint x, uint y) private pure returns (uint z) { require((z = x - y) <= x, "Shell/burn-underflow"); } } ////// src/Shells.sol // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /* pragma solidity ^0.5.0; */ /* import "./LoihiStorage.sol"; */ /* import "./Assimilators.sol"; */ /* import "abdk-libraries-solidity/ABDKMath64x64.sol"; */ library Shells { using ABDKMath64x64 for int128; event Approval(address indexed _owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); function add(uint x, uint y, string memory errorMessage) private pure returns (uint z) { require((z = x + y) >= x, errorMessage); } function sub(uint x, uint y, string memory errorMessage) private pure returns (uint z) { require((z = x - y) <= x, errorMessage); } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(LoihiStorage.Shell storage shell, address recipient, uint256 amount) external returns (bool) { _transfer(shell, msg.sender, recipient, amount); return true; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(LoihiStorage.Shell storage shell, address spender, uint256 amount) external returns (bool) { _approve(shell, 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(LoihiStorage.Shell storage shell, address sender, address recipient, uint256 amount) external returns (bool) { _transfer(shell, msg.sender, recipient, amount); _approve(shell, sender, msg.sender, sub(shell.allowances[sender][msg.sender], amount, "Shell/insufficient-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(LoihiStorage.Shell storage shell, address spender, uint256 addedValue) external returns (bool) { _approve(shell, msg.sender, spender, add(shell.allowances[msg.sender][spender], addedValue, "Shell/approval-overflow")); 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(LoihiStorage.Shell storage shell, address spender, uint256 subtractedValue) external returns (bool) { _approve(shell, msg.sender, spender, sub(shell.allowances[msg.sender][spender], subtractedValue, "Shell/allowance-decrease-underflow")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is public 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(LoihiStorage.Shell storage shell, address sender, address recipient, uint256 amount) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); shell.balances[sender] = sub(shell.balances[sender], amount, "Shell/insufficient-balance"); shell.balances[recipient] = add(shell.balances[recipient], amount, "Shell/transfer-overflow"); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `_owner`s tokens. * * This is public 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(LoihiStorage.Shell storage shell, 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"); shell.allowances[_owner][spender] = amount; emit Approval(_owner, spender, amount); } } ////// src/Swaps.sol /* pragma solidity ^0.5.0; */ /* import "./Assimilators.sol"; */ /* import "./LoihiStorage.sol"; */ /* import "./ShellMath.sol"; */ /* import "./UnsafeMath64x64.sol"; */ /* import "abdk-libraries-solidity/ABDKMath64x64.sol"; */ library Swaps { using ABDKMath64x64 for int128; using UnsafeMath64x64 for int128; event Trade(address indexed trader, address indexed origin, address indexed target, uint256 originAmount, uint256 targetAmount); int128 constant ONE = 0x10000000000000000; function getOriginAndTarget ( LoihiStorage.Shell storage shell, address _o, address _t ) private view returns ( LoihiStorage.Assimilator memory, LoihiStorage.Assimilator memory ) { LoihiStorage.Assimilator memory o_ = shell.assimilators[_o]; LoihiStorage.Assimilator memory t_ = shell.assimilators[_t]; require(o_.addr != address(0), "Shell/origin-not-supported"); require(t_.addr != address(0), "Shell/target-not-supported"); return ( o_, t_ ); } function originSwap ( LoihiStorage.Shell storage shell, address _origin, address _target, uint256 _originAmount, address _recipient ) external returns ( uint256 tAmt_ ) { ( LoihiStorage.Assimilator memory _o, LoihiStorage.Assimilator memory _t ) = getOriginAndTarget(shell, _origin, _target); if (_o.ix == _t.ix) return Assimilators.outputNumeraire(_t.addr, _recipient, Assimilators.intakeRaw(_o.addr, _originAmount)); ( int128 _amt, int128 _oGLiq, int128 _nGLiq, int128[] memory _oBals, int128[] memory _nBals ) = getOriginSwapData(shell, _o.ix, _t.ix, _o.addr, _originAmount); ( _amt, shell.omega ) = ShellMath.calculateTrade(shell, _oGLiq, _nGLiq, _oBals, _nBals, _amt, _t.ix); _amt = _amt.us_mul(ONE - shell.epsilon); tAmt_ = Assimilators.outputNumeraire(_t.addr, _recipient, _amt); emit Trade(msg.sender, _origin, _target, _originAmount, tAmt_); } function viewOriginSwap ( LoihiStorage.Shell storage shell, address _origin, address _target, uint256 _originAmount ) external view returns ( uint256 tAmt_ ) { ( LoihiStorage.Assimilator memory _o, LoihiStorage.Assimilator memory _t ) = getOriginAndTarget(shell, _origin, _target); if (_o.ix == _t.ix) return Assimilators.viewRawAmount(_t.addr, Assimilators.viewNumeraireAmount(_o.addr, _originAmount)); ( int128 _amt, int128 _oGLiq, int128 _nGLiq, int128[] memory _nBals, int128[] memory _oBals ) = viewOriginSwapData(shell, _o.ix, _t.ix, _originAmount, _o.addr); ( _amt, ) = ShellMath.calculateTrade(shell, _oGLiq, _nGLiq, _oBals, _nBals, _amt, _t.ix); _amt = _amt.us_mul(ONE - shell.epsilon); tAmt_ = Assimilators.viewRawAmount(_t.addr, _amt.abs()); } function targetSwap ( LoihiStorage.Shell storage shell, address _origin, address _target, uint256 _targetAmount, address _recipient ) external returns ( uint256 oAmt_ ) { ( LoihiStorage.Assimilator memory _o, LoihiStorage.Assimilator memory _t ) = getOriginAndTarget(shell, _origin, _target); if (_o.ix == _t.ix) return Assimilators.intakeNumeraire(_o.addr, Assimilators.outputRaw(_t.addr, _recipient, _targetAmount)); ( int128 _amt, int128 _oGLiq, int128 _nGLiq, int128[] memory _oBals, int128[] memory _nBals) = getTargetSwapData(shell, _t.ix, _o.ix, _t.addr, _recipient, _targetAmount); ( _amt, shell.omega ) = ShellMath.calculateTrade(shell, _oGLiq, _nGLiq, _oBals, _nBals, _amt, _o.ix); _amt = _amt.us_mul(ONE + shell.epsilon); oAmt_ = Assimilators.intakeNumeraire(_o.addr, _amt); emit Trade(msg.sender, _origin, _target, oAmt_, _targetAmount); } function viewTargetSwap ( LoihiStorage.Shell storage shell, address _origin, address _target, uint256 _targetAmount ) external view returns ( uint256 oAmt_ ) { ( LoihiStorage.Assimilator memory _o, LoihiStorage.Assimilator memory _t ) = getOriginAndTarget(shell, _origin, _target); if (_o.ix == _t.ix) return Assimilators.viewRawAmount(_o.addr, Assimilators.viewNumeraireAmount(_t.addr, _targetAmount)); ( int128 _amt, int128 _oGLiq, int128 _nGLiq, int128[] memory _nBals, int128[] memory _oBals ) = viewTargetSwapData(shell, _t.ix, _o.ix, _targetAmount, _t.addr); ( _amt, ) = ShellMath.calculateTrade(shell, _oGLiq, _nGLiq, _oBals, _nBals, _amt, _o.ix); _amt = _amt.us_mul(ONE + shell.epsilon); oAmt_ = Assimilators.viewRawAmount(_o.addr, _amt); } function getOriginSwapData ( LoihiStorage.Shell storage shell, uint _inputIx, uint _outputIndex, address _assim, uint _amt ) private returns ( int128 amt_, int128 oGLiq_, int128 nGLiq_, int128[] memory, int128[] memory ) { uint _length = shell.assets.length; int128[] memory oBals_ = new int128[](_length); int128[] memory nBals_ = new int128[](_length); LoihiStorage.Assimilator[] memory _reserves = shell.assets; for (uint i = 0; i < _length; i++) { if (i != _inputIx) nBals_[i] = oBals_[i] = Assimilators.viewNumeraireBalance(_reserves[i].addr); else { int128 _bal; ( amt_, _bal ) = Assimilators.intakeRawAndGetBalance(_assim, _amt); oBals_[i] = _bal - amt_; nBals_[i] = _bal; } oGLiq_ += oBals_[i]; nGLiq_ += nBals_[i]; } nGLiq_ = nGLiq_.sub(amt_); nBals_[_outputIndex] = ABDKMath64x64.sub(nBals_[_outputIndex], amt_); return ( amt_, oGLiq_, nGLiq_, oBals_, nBals_ ); } function getTargetSwapData ( LoihiStorage.Shell storage shell, uint _inputIx, uint _outputIndex, address _assim, address _recipient, uint _amt ) private returns ( int128 amt_, int128 oGLiq_, int128 nGLiq_, int128[] memory, int128[] memory ) { uint _length = shell.assets.length; int128[] memory oBals_ = new int128[](_length); int128[] memory nBals_ = new int128[](_length); LoihiStorage.Assimilator[] memory _reserves = shell.assets; for (uint i = 0; i < _length; i++) { if (i != _inputIx) nBals_[i] = oBals_[i] = Assimilators.viewNumeraireBalance(_reserves[i].addr); else { int128 _bal; ( amt_, _bal ) = Assimilators.outputRawAndGetBalance(_assim, _recipient, _amt); oBals_[i] = _bal - amt_; nBals_[i] = _bal; } oGLiq_ += oBals_[i]; nGLiq_ += nBals_[i]; } nGLiq_ = nGLiq_.sub(amt_); nBals_[_outputIndex] = ABDKMath64x64.sub(nBals_[_outputIndex], amt_); return ( amt_, oGLiq_, nGLiq_, oBals_, nBals_ ); } function viewOriginSwapData ( LoihiStorage.Shell storage shell, uint _inputIx, uint _outputIndex, uint _amt, address _assim ) private view returns ( int128 amt_, int128 oGLiq_, int128 nGLiq_, int128[] memory, int128[] memory ) { uint _length = shell.assets.length; int128[] memory nBals_ = new int128[](_length); int128[] memory oBals_ = new int128[](_length); for (uint i = 0; i < _length; i++) { if (i != _inputIx) nBals_[i] = oBals_[i] = Assimilators.viewNumeraireBalance(shell.assets[i].addr); else { int128 _bal; ( amt_, _bal ) = Assimilators.viewNumeraireAmountAndBalance(_assim, _amt); oBals_[i] = _bal; nBals_[i] = _bal.add(amt_); } oGLiq_ += oBals_[i]; nGLiq_ += nBals_[i]; } nGLiq_ = nGLiq_.sub(amt_); nBals_[_outputIndex] = ABDKMath64x64.sub(nBals_[_outputIndex], amt_); return ( amt_, oGLiq_, nGLiq_, nBals_, oBals_ ); } function viewTargetSwapData ( LoihiStorage.Shell storage shell, uint _inputIx, uint _outputIndex, uint _amt, address _assim ) private view returns ( int128 amt_, int128 oGLiq_, int128 nGLiq_, int128[] memory, int128[] memory ) { uint _length = shell.assets.length; int128[] memory nBals_ = new int128[](_length); int128[] memory oBals_ = new int128[](_length); for (uint i = 0; i < _length; i++) { if (i != _inputIx) nBals_[i] = oBals_[i] = Assimilators.viewNumeraireBalance(shell.assets[i].addr); else { int128 _bal; ( amt_, _bal ) = Assimilators.viewNumeraireAmountAndBalance(_assim, _amt); amt_ = amt_.neg(); oBals_[i] = _bal; nBals_[i] = _bal.add(amt_); } oGLiq_ += oBals_[i]; nGLiq_ += nBals_[i]; } nGLiq_ = nGLiq_.sub(amt_); nBals_[_outputIndex] = ABDKMath64x64.sub(nBals_[_outputIndex], amt_); return ( amt_, oGLiq_, nGLiq_, nBals_, oBals_ ); } } ////// src/ViewLiquidity.sol // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /* pragma solidity ^0.5.0; */ /* import "./LoihiStorage.sol"; */ /* import "./Assimilators.sol"; */ /* import "abdk-libraries-solidity/ABDKMath64x64.sol"; */ library ViewLiquidity { using ABDKMath64x64 for int128; function viewLiquidity ( LoihiStorage.Shell storage shell ) external view returns ( uint total_, uint[] memory individual_ ) { uint _length = shell.assets.length; uint[] memory individual_ = new uint[](_length); uint total_; for (uint i = 0; i < _length; i++) { uint _liquidity = Assimilators.viewNumeraireBalance(shell.assets[i].addr).mulu(1e18); total_ += _liquidity; individual_[i] = _liquidity; } return (total_, individual_); } } ////// src/interfaces/IAToken.sol /* pragma solidity ^0.5.0; */ interface IAToken { function transfer(address recipient, uint256 amount) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function redirectInterestStream(address _to) external; function redirectInterestStreamOf(address _from, address _to) external; function allowInterestRedirectionTo(address _to) external; function redeem(uint256 _amount) external; function balanceOf(address _user) external view returns(uint256); function principalBalanceOf(address _user) external view returns(uint256); function totalSupply() external view returns(uint256); function isTransferAllowed(address _user, uint256 _amount) external view returns (bool); function getUserIndex(address _user) external view returns(uint256); function getInterestRedirectionAddress(address _user) external view returns(address); function getRedirectedBalance(address _user) external view returns(uint256); function decimals () external view returns (uint256); function deposit(uint256 _amount) external; } ////// src/interfaces/ICToken.sol /* pragma solidity ^0.5.0; */ interface ICToken { function mint(uint mintAmount) external returns (uint); function redeem(uint redeemTokens) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); function repayBorrow(uint repayAmount) external returns (uint); function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint); function getCash() external view returns (uint); function exchangeRateCurrent() external returns (uint); function exchangeRateStored() external view returns (uint); function transfer(address recipient, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function balanceOfUnderlying(address account) external returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } ////// src/interfaces/IChai.sol /* pragma solidity ^0.5.0; */ interface IChai { function draw(address src, uint wad) external; function exit(address src, uint wad) external; function join(address dst, uint wad) external; function dai(address usr) external returns (uint wad); function permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external; function approve(address usr, uint wad) external returns (bool); function move(address src, address dst, uint wad) external returns (bool); function transfer(address dst, uint wad) external returns (bool); function transferFrom(address src, address dst, uint wad) external; function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); } ////// src/interfaces/IERC20.sol /* pragma solidity ^0.5.0; */ /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } ////// src/interfaces/IERC20NoBool.sol /* pragma solidity ^0.5.0; */ /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20NoBool { /** * @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; /** * @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; /** * @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; /** * @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); } ////// src/interfaces/IPot.sol /* pragma solidity ^0.5.0; */ interface IPot { function rho () external returns (uint256); function drip () external returns (uint256); function chi () external view returns (uint256); } ////// src/LoihiStorage.sol // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /* pragma solidity ^0.5.0; */ /* import "abdk-libraries-solidity/ABDKMath64x64.sol"; */ /* import "./Orchestrator.sol"; */ /* import "./PartitionedLiquidity.sol"; */ /* import "./ProportionalLiquidity.sol"; */ /* import "./SelectiveLiquidity.sol"; */ /* import "./Shells.sol"; */ /* import "./Swaps.sol"; */ /* import "./ViewLiquidity.sol"; */ /* import "./interfaces/IERC20.sol"; */ /* import "./interfaces/IERC20NoBool.sol"; */ /* import "./interfaces/IAToken.sol"; */ /* import "./interfaces/ICToken.sol"; */ /* import "./interfaces/IChai.sol"; */ /* import "./interfaces/IPot.sol"; */ contract LoihiStorage { string public constant name = "Shells"; string public constant symbol = "SHL"; uint8 public constant decimals = 18; struct Shell { int128 alpha; int128 beta; int128 delta; int128 epsilon; int128 lambda; int128 omega; int128[] weights; uint totalSupply; mapping (address => uint) balances; mapping (address => mapping (address => uint)) allowances; Assimilator[] assets; mapping (address => Assimilator) assimilators; } struct Assimilator { address addr; uint8 ix; } Shell public shell; struct PartitionTicket { uint[] claims; bool initialized; } mapping (address => PartitionTicket) public partitionTickets; address[] public derivatives; address[] public numeraires; address[] public reserves; bool public partitioned = false; bool public frozen = false; address public owner; bool internal notEntered = true; // uint public maxFee; }
* @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(LoihiStorage.Shell storage shell, address spender, uint256 subtractedValue) external returns (bool) { _approve(shell, msg.sender, spender, sub(shell.allowances[msg.sender][spender], subtractedValue, "Shell/allowance-decrease-underflow")); return true; }
125,027
[ 1, 3641, 6478, 23850, 3304, 326, 1699, 1359, 17578, 358, 1375, 87, 1302, 264, 68, 635, 326, 4894, 18, 1220, 353, 392, 10355, 358, 288, 12908, 537, 97, 716, 848, 506, 1399, 487, 279, 20310, 360, 367, 364, 9688, 11893, 316, 288, 45, 654, 39, 3462, 17, 12908, 537, 5496, 7377, 1282, 392, 288, 23461, 97, 871, 11193, 326, 3526, 1699, 1359, 18, 29076, 30, 300, 1375, 87, 1302, 264, 68, 2780, 506, 326, 3634, 1758, 18, 300, 1375, 87, 1302, 264, 68, 1297, 1240, 1699, 1359, 364, 326, 4894, 434, 622, 4520, 1375, 1717, 1575, 329, 620, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 20467, 7009, 1359, 12, 1504, 7392, 77, 3245, 18, 13220, 2502, 5972, 16, 1758, 17571, 264, 16, 2254, 5034, 10418, 329, 620, 13, 3903, 1135, 261, 6430, 13, 288, 203, 3639, 389, 12908, 537, 12, 10304, 16, 1234, 18, 15330, 16, 17571, 264, 16, 720, 12, 10304, 18, 5965, 6872, 63, 3576, 18, 15330, 6362, 87, 1302, 264, 6487, 10418, 329, 620, 16, 315, 13220, 19, 5965, 1359, 17, 323, 11908, 17, 9341, 2426, 7923, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./Timer.sol"; /// This contract represents abstract auction. contract Auction { enum Outcome { NOT_FINISHED, NOT_SUCCESSFUL, SUCCESSFUL } /// Address of timer. Timer private timer; /// Address of a judge. address private judgeAddress; /// Address of seller. address private sellerAddress; /// Address of the highest bidder. /// This should be set when the auction is over. address internal highestBidderAddress; /// Indicates auction outcome. Outcome internal outcome; constructor( address _sellerAddress, address _judgeAddress, Timer _timer ) { timer = _timer; judgeAddress = _judgeAddress; sellerAddress = _sellerAddress; if (sellerAddress == address(0)) { sellerAddress = msg.sender; } outcome = Outcome.NOT_FINISHED; } /// Internal function used to finish an auction. /// Auction can finish in three different scenarios: /// 1.) Somebody have won the auction and seller has the rights to get the /// founds on this contract. /// 2.) Auction finished with highest bidder, but for some reason the /// highest bidder does not have rights to claim the auction item /// (e.g. minimal item price is not reached). /// 3.) Not one bid has been placed for an item. /// /// The values that should be used with this function invocation for each of /// the cases are: /// 1.) In the case of the first outcome, contract should call this method with /// _highestBidderAddress != address(0) and _outcome should be equal to /// Auction.Outcome.SUCCESSFUL. /// 2.) In the case of the second outcome, contract should call this method /// with _outcome == AuctionOutcome.NOT_SUCCESSFUL and arbitrary value /// for the _highestBidderAddress parameter. /// 3.) In the third case when not a single bid was placed, then this function /// should be called with _outcome == NOT_SUCCESSFUL and /// _highestBidderAddress should be equal to address(0). /// /// @param _outcome Outcome of the auction. /// @param _highestBidder Address of the highest bidder or address(0) if auction did not finish successfully. function finishAuction(Outcome _outcome, address _highestBidder) internal { require(_outcome != Outcome.NOT_FINISHED); // This should not happen. outcome = _outcome; highestBidderAddress = _highestBidder; } /// Finalizes the auction and sends the money to the auction seller. /// This function can only be called when the auction has finished successfully. /// If no judge is specified for an auction then anybody can request /// the transfer of fonds to the seller. If the judge is specified, /// then only the judge or highest bidder can transfer the funds to the seller. function finalize() public { require(outcome == Outcome.SUCCESSFUL, "Auction isn't successful!"); require( judgeAddress == address(0) || msg.sender == judgeAddress || msg.sender == highestBidderAddress, "Sender can't call finalize()!"); payUp(payable(sellerAddress), address(this).balance); } // If a judge is specified, this can ONLY be called by seller or the judge. // Otherwise, anybody can request refund to the highest bidder. // Money can only be refunded to the highest bidder. function refund() public { require(outcome == Outcome.NOT_SUCCESSFUL, "Auction should be unsuccessful!"); require( judgeAddress == address(0) || msg.sender == sellerAddress || msg.sender == judgeAddress, "Sender can't call refund()!"); require(highestBidderAddress != address(0), "Not one bid has been placed for an item!"); payUp(payable(highestBidderAddress), address(this).balance); } function payUp(address payable _to, uint _amount) internal { (bool success,) = _to.call{value : _amount}(""); require(success, "Transfer failed!"); } // This is provided for testing // You should use this instead of block.number directly // You should not modify this function. function time() public view returns (uint) { return timer.getTime(); } /// Function that returns highest bidder address or address(0) if /// auction is not yet over. function getHighestBidder() public virtual returns (address) { return highestBidderAddress; } }
Address of a judge.
address private judgeAddress;
1,812,905
[ 1, 1887, 434, 279, 525, 27110, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1758, 3238, 525, 27110, 1887, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.16; pragma experimental ABIEncoderV2; import "@0x/contracts-asset-proxy/contracts/src/interfaces/IAssetData.sol"; import "@0x/contracts-exchange/contracts/src/interfaces/IExchange.sol"; import "@0x/contracts-utils/contracts/src/DeploymentConstants.sol"; // solhint-disable no-empty-blocks contract Addresses is DeploymentConstants { address public exchangeAddress; address public erc20ProxyAddress; address public erc721ProxyAddress; address public erc1155ProxyAddress; address public staticCallProxyAddress; address public chaiBridgeAddress; address public dydxBridgeAddress; constructor ( address exchange_, address chaiBridge_, address dydxBridge_ ) public { exchangeAddress = exchange_; chaiBridgeAddress = chaiBridge_; dydxBridgeAddress = dydxBridge_; erc20ProxyAddress = IExchange(exchange_).getAssetProxy(IAssetData(address(0)).ERC20Token.selector); erc721ProxyAddress = IExchange(exchange_).getAssetProxy(IAssetData(address(0)).ERC721Token.selector); erc1155ProxyAddress = IExchange(exchange_).getAssetProxy(IAssetData(address(0)).ERC1155Assets.selector); staticCallProxyAddress = IExchange(exchange_).getAssetProxy(IAssetData(address(0)).StaticCall.selector); } } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.16; pragma experimental ABIEncoderV2; import "@0x/contracts-utils/contracts/src/LibBytes.sol"; import "@0x/contracts-asset-proxy/contracts/src/interfaces/IAssetData.sol"; import "@0x/contracts-asset-proxy/contracts/src/interfaces/IAssetProxy.sol"; import "@0x/contracts-erc20/contracts/src/LibERC20Token.sol"; import "@0x/contracts-erc721/contracts/src/interfaces/IERC721Token.sol"; import "@0x/contracts-erc1155/contracts/src/interfaces/IERC1155.sol"; import "@0x/contracts-asset-proxy/contracts/src/interfaces/IChai.sol"; import "@0x/contracts-exchange-libs/contracts/src/LibMath.sol"; import "./Addresses.sol"; import "./LibDydxBalance.sol"; contract AssetBalance is Addresses { // 2^256 - 1 uint256 constant internal _MAX_UINT256 = uint256(-1); using LibBytes for bytes; /// @dev Returns the owner's balance of the assets(s) specified in /// assetData. When the asset data contains multiple assets (eg in /// ERC1155 or Multi-Asset), the return value indicates how many /// complete "baskets" of those assets are owned by owner. /// @param ownerAddress Owner of the assets specified by assetData. /// @param assetData Details of asset, encoded per the AssetProxy contract specification. /// @return Number of assets (or asset baskets) held by owner. function getBalance(address ownerAddress, bytes memory assetData) public returns (uint256 balance) { // Get id of AssetProxy contract bytes4 assetProxyId = assetData.readBytes4(0); if (assetProxyId == IAssetData(address(0)).ERC20Token.selector) { // Get ERC20 token address address tokenAddress = assetData.readAddress(16); balance = LibERC20Token.balanceOf(tokenAddress, ownerAddress); } else if (assetProxyId == IAssetData(address(0)).ERC721Token.selector) { // Get ERC721 token address and id (, address tokenAddress, uint256 tokenId) = LibAssetData.decodeERC721AssetData(assetData); // Check if id is owned by ownerAddress bytes memory ownerOfCalldata = abi.encodeWithSelector( IERC721Token(address(0)).ownerOf.selector, tokenId ); (bool success, bytes memory returnData) = tokenAddress.staticcall(ownerOfCalldata); address currentOwnerAddress = (success && returnData.length == 32) ? returnData.readAddress(12) : address(0); balance = currentOwnerAddress == ownerAddress ? 1 : 0; } else if (assetProxyId == IAssetData(address(0)).ERC1155Assets.selector) { // Get ERC1155 token address, array of ids, and array of values (, address tokenAddress, uint256[] memory tokenIds, uint256[] memory tokenValues,) = LibAssetData.decodeERC1155AssetData(assetData); uint256 length = tokenIds.length; for (uint256 i = 0; i != length; i++) { // Skip over the token if the corresponding value is 0. if (tokenValues[i] == 0) { continue; } // Encode data for `balanceOf(ownerAddress, tokenIds[i]) bytes memory balanceOfData = abi.encodeWithSelector( IERC1155(address(0)).balanceOf.selector, ownerAddress, tokenIds[i] ); // Query balance (bool success, bytes memory returnData) = tokenAddress.staticcall(balanceOfData); uint256 totalBalance = success && returnData.length == 32 ? returnData.readUint256(0) : 0; // Scale total balance down by corresponding value in assetData uint256 scaledBalance = totalBalance / tokenValues[i]; if (scaledBalance == 0) { return 0; } if (scaledBalance < balance || balance == 0) { balance = scaledBalance; } } } else if (assetProxyId == IAssetData(address(0)).StaticCall.selector) { // Encode data for `staticCallProxy.transferFrom(assetData,...)` bytes memory transferFromData = abi.encodeWithSelector( IAssetProxy(address(0)).transferFrom.selector, assetData, address(0), // `from` address is not used address(0), // `to` address is not used 0 // `amount` is not used ); // Check if staticcall would be successful (bool success,) = staticCallProxyAddress.staticcall(transferFromData); // Success means that the staticcall can be made an unlimited amount of times balance = success ? _MAX_UINT256 : 0; } else if (assetProxyId == IAssetData(address(0)).ERC20Bridge.selector) { // Get address of ERC20 token and bridge contract (, address tokenAddress, address bridgeAddress, ) = LibAssetData.decodeERC20BridgeAssetData(assetData); if (tokenAddress == _getDaiAddress() && bridgeAddress == chaiBridgeAddress) { uint256 chaiBalance = LibERC20Token.balanceOf(_getChaiAddress(), ownerAddress); // Calculate Dai balance balance = _convertChaiToDaiAmount(chaiBalance); } // Balance will be 0 if bridge is not supported } else if (assetProxyId == IAssetData(address(0)).MultiAsset.selector) { // Get array of values and array of assetDatas (, uint256[] memory assetAmounts, bytes[] memory nestedAssetData) = LibAssetData.decodeMultiAssetData(assetData); uint256 length = nestedAssetData.length; for (uint256 i = 0; i != length; i++) { // Skip over the asset if the corresponding amount is 0. if (assetAmounts[i] == 0) { continue; } // Query balance of individual assetData uint256 totalBalance = getBalance(ownerAddress, nestedAssetData[i]); // Scale total balance down by corresponding value in assetData uint256 scaledBalance = totalBalance / assetAmounts[i]; if (scaledBalance == 0) { return 0; } if (scaledBalance < balance || balance == 0) { balance = scaledBalance; } } } // Balance will be 0 if assetProxyId is unknown return balance; } /// @dev Calls getBalance() for each element of assetData. /// @param ownerAddress Owner of the assets specified by assetData. /// @param assetData Array of asset details, each encoded per the AssetProxy contract specification. /// @return Array of asset balances from getBalance(), with each element /// corresponding to the same-indexed element in the assetData input. function getBatchBalances(address ownerAddress, bytes[] memory assetData) public returns (uint256[] memory balances) { uint256 length = assetData.length; balances = new uint256[](length); for (uint256 i = 0; i != length; i++) { balances[i] = getBalance(ownerAddress, assetData[i]); } return balances; } /// @dev Returns the number of asset(s) (described by assetData) that /// the corresponding AssetProxy contract is authorized to spend. When the asset data contains /// multiple assets (eg for Multi-Asset), the return value indicates /// how many complete "baskets" of those assets may be spent by all of the corresponding /// AssetProxy contracts. /// @param ownerAddress Owner of the assets specified by assetData. /// @param assetData Details of asset, encoded per the AssetProxy contract specification. /// @return Number of assets (or asset baskets) that the corresponding AssetProxy is authorized to spend. function getAssetProxyAllowance(address ownerAddress, bytes memory assetData) public returns (uint256 allowance) { // Get id of AssetProxy contract bytes4 assetProxyId = assetData.readBytes4(0); if (assetProxyId == IAssetData(address(0)).MultiAsset.selector) { // Get array of values and array of assetDatas (, uint256[] memory amounts, bytes[] memory nestedAssetData) = LibAssetData.decodeMultiAssetData(assetData); uint256 length = nestedAssetData.length; for (uint256 i = 0; i != length; i++) { // Skip over the asset if the corresponding amount is 0. if (amounts[i] == 0) { continue; } // Query allowance of individual assetData uint256 totalAllowance = getAssetProxyAllowance(ownerAddress, nestedAssetData[i]); // Scale total allowance down by corresponding value in assetData uint256 scaledAllowance = totalAllowance / amounts[i]; if (scaledAllowance == 0) { return 0; } if (scaledAllowance < allowance || allowance == 0) { allowance = scaledAllowance; } } return allowance; } if (assetProxyId == IAssetData(address(0)).ERC20Token.selector) { // Get ERC20 token address address tokenAddress = assetData.readAddress(16); allowance = LibERC20Token.allowance(tokenAddress, ownerAddress, erc20ProxyAddress); } else if (assetProxyId == IAssetData(address(0)).ERC721Token.selector) { // Get ERC721 token address and id (, address tokenAddress, uint256 tokenId) = LibAssetData.decodeERC721AssetData(assetData); // Encode data for `isApprovedForAll(ownerAddress, erc721ProxyAddress)` bytes memory isApprovedForAllData = abi.encodeWithSelector( IERC721Token(address(0)).isApprovedForAll.selector, ownerAddress, erc721ProxyAddress ); (bool success, bytes memory returnData) = tokenAddress.staticcall(isApprovedForAllData); // If not approved for all, call `getApproved(tokenId)` if (!success || returnData.length != 32 || returnData.readUint256(0) != 1) { // Encode data for `getApproved(tokenId)` bytes memory getApprovedData = abi.encodeWithSelector(IERC721Token(address(0)).getApproved.selector, tokenId); (success, returnData) = tokenAddress.staticcall(getApprovedData); // Allowance is 1 if successful and the approved address is the ERC721Proxy allowance = success && returnData.length == 32 && returnData.readAddress(12) == erc721ProxyAddress ? 1 : 0; } else { // Allowance is 2^256 - 1 if `isApprovedForAll` returned true allowance = _MAX_UINT256; } } else if (assetProxyId == IAssetData(address(0)).ERC1155Assets.selector) { // Get ERC1155 token address (, address tokenAddress, , , ) = LibAssetData.decodeERC1155AssetData(assetData); // Encode data for `isApprovedForAll(ownerAddress, erc1155ProxyAddress)` bytes memory isApprovedForAllData = abi.encodeWithSelector( IERC1155(address(0)).isApprovedForAll.selector, ownerAddress, erc1155ProxyAddress ); // Query allowance (bool success, bytes memory returnData) = tokenAddress.staticcall(isApprovedForAllData); allowance = success && returnData.length == 32 && returnData.readUint256(0) == 1 ? _MAX_UINT256 : 0; } else if (assetProxyId == IAssetData(address(0)).StaticCall.selector) { // The StaticCallProxy does not require any approvals allowance = _MAX_UINT256; } else if (assetProxyId == IAssetData(address(0)).ERC20Bridge.selector) { // Get address of ERC20 token and bridge contract (, address tokenAddress, address bridgeAddress,) = LibAssetData.decodeERC20BridgeAssetData(assetData); if (tokenAddress == _getDaiAddress() && bridgeAddress == chaiBridgeAddress) { uint256 chaiAllowance = LibERC20Token.allowance(_getChaiAddress(), ownerAddress, chaiBridgeAddress); // Dai allowance is unlimited if Chai allowance is unlimited allowance = chaiAllowance == _MAX_UINT256 ? _MAX_UINT256 : _convertChaiToDaiAmount(chaiAllowance); } else if (bridgeAddress == dydxBridgeAddress) { allowance = LibDydxBalance.getDydxMakerAllowance(ownerAddress, bridgeAddress, _getDydxAddress()); } // Allowance will be 0 if bridge is not supported } // Allowance will be 0 if the assetProxyId is unknown return allowance; } /// @dev Calls getAssetProxyAllowance() for each element of assetData. /// @param ownerAddress Owner of the assets specified by assetData. /// @param assetData Array of asset details, each encoded per the AssetProxy contract specification. /// @return An array of asset allowances from getAllowance(), with each /// element corresponding to the same-indexed element in the assetData input. function getBatchAssetProxyAllowances(address ownerAddress, bytes[] memory assetData) public returns (uint256[] memory allowances) { uint256 length = assetData.length; allowances = new uint256[](length); for (uint256 i = 0; i != length; i++) { allowances[i] = getAssetProxyAllowance(ownerAddress, assetData[i]); } return allowances; } /// @dev Calls getBalance() and getAllowance() for assetData. /// @param ownerAddress Owner of the assets specified by assetData. /// @param assetData Details of asset, encoded per the AssetProxy contract specification. /// @return Number of assets (or asset baskets) held by owner, and number /// of assets (or asset baskets) that the corresponding AssetProxy is authorized to spend. function getBalanceAndAssetProxyAllowance( address ownerAddress, bytes memory assetData ) public returns (uint256 balance, uint256 allowance) { balance = getBalance(ownerAddress, assetData); allowance = getAssetProxyAllowance(ownerAddress, assetData); return (balance, allowance); } /// @dev Calls getBatchBalances() and getBatchAllowances() for each element of assetData. /// @param ownerAddress Owner of the assets specified by assetData. /// @param assetData Array of asset details, each encoded per the AssetProxy contract specification. /// @return An array of asset balances from getBalance(), and an array of /// asset allowances from getAllowance(), with each element /// corresponding to the same-indexed element in the assetData input. function getBatchBalancesAndAssetProxyAllowances( address ownerAddress, bytes[] memory assetData ) public returns (uint256[] memory balances, uint256[] memory allowances) { balances = getBatchBalances(ownerAddress, assetData); allowances = getBatchAssetProxyAllowances(ownerAddress, assetData); return (balances, allowances); } /// @dev Converts an amount of Chai into its equivalent Dai amount. /// Also accumulates Dai from DSR if called after the last time it was collected. /// @param chaiAmount Amount of Chai to converts. function _convertChaiToDaiAmount(uint256 chaiAmount) internal returns (uint256 daiAmount) { PotLike pot = IChai(_getChaiAddress()).pot(); // Accumulate savings if called after last time savings were collected // solhint-disable-next-line not-rely-on-time uint256 chiMultiplier = (now > pot.rho()) ? pot.drip() : pot.chi(); daiAmount = LibMath.getPartialAmountFloor(chiMultiplier, 10**27, chaiAmount); return daiAmount; } /// @dev Returns an order MAKER's balance of the assets(s) specified in /// makerAssetData. Unlike `getBalanceAndAssetProxyAllowance()`, this /// can handle maker asset types that depend on taker tokens being /// transferred to the maker first. /// @param order The order. /// @return balance Quantity of assets transferrable from maker to taker. function _getConvertibleMakerBalanceAndAssetProxyAllowance( LibOrder.Order memory order ) internal returns (uint256 balance, uint256 allowance) { if (order.makerAssetData.length < 4) { return (0, 0); } bytes4 assetProxyId = order.makerAssetData.readBytes4(0); // Handle dydx bridge assets. if (assetProxyId == IAssetData(address(0)).ERC20Bridge.selector) { (, , address bridgeAddress, ) = LibAssetData.decodeERC20BridgeAssetData(order.makerAssetData); if (bridgeAddress == dydxBridgeAddress) { return ( LibDydxBalance.getDydxMakerBalance(order, _getDydxAddress()), getAssetProxyAllowance(order.makerAddress, order.makerAssetData) ); } } return ( getBalance(order.makerAddress, order.makerAssetData), getAssetProxyAllowance(order.makerAddress, order.makerAssetData) ); } } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.16; pragma experimental ABIEncoderV2; import "@0x/contracts-exchange-libs/contracts/src/LibEIP712ExchangeDomain.sol"; import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol"; import "@0x/contracts-exchange-libs/contracts/src/LibZeroExTransaction.sol"; import "@0x/contracts-utils/contracts/src/LibEIP712.sol"; import "@0x/contracts-utils/contracts/src/LibBytes.sol"; import "./Addresses.sol"; import "./OrderValidationUtils.sol"; import "./EthBalanceChecker.sol"; import "./ExternalFunctions.sol"; // solhint-disable no-empty-blocks contract DevUtils is Addresses, OrderValidationUtils, LibEIP712ExchangeDomain, EthBalanceChecker, ExternalFunctions { constructor ( address exchange_, address chaiBridge_, address dydxBridge_ ) public Addresses( exchange_, chaiBridge_, dydxBridge_ ) LibEIP712ExchangeDomain(uint256(0), address(0)) // null args because because we only use constants {} function getOrderHash( LibOrder.Order memory order, uint256 chainId, address exchange ) public pure returns (bytes32 orderHash) { return LibOrder.getTypedDataHash( order, LibEIP712.hashEIP712Domain(_EIP712_EXCHANGE_DOMAIN_NAME, _EIP712_EXCHANGE_DOMAIN_VERSION, chainId, exchange) ); } function getTransactionHash( LibZeroExTransaction.ZeroExTransaction memory transaction, uint256 chainId, address exchange ) public pure returns (bytes32 transactionHash) { return LibZeroExTransaction.getTypedDataHash( transaction, LibEIP712.hashEIP712Domain(_EIP712_EXCHANGE_DOMAIN_NAME, _EIP712_EXCHANGE_DOMAIN_VERSION, chainId, exchange) ); } } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.16; contract EthBalanceChecker { /// @dev Batch fetches ETH balances /// @param addresses Array of addresses. /// @return Array of ETH balances. function getEthBalances(address[] memory addresses) public view returns (uint256[] memory) { uint256[] memory balances = new uint256[](addresses.length); for (uint256 i = 0; i != addresses.length; i++) { balances[i] = addresses[i].balance; } return balances; } } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.16; pragma experimental ABIEncoderV2; import "./Addresses.sol"; import "./LibAssetData.sol"; import "./LibTransactionDecoder.sol"; import "./LibOrderTransferSimulation.sol"; contract ExternalFunctions is Addresses { /// @dev Decodes the call data for an Exchange contract method call. /// @param transactionData ABI-encoded calldata for an Exchange /// contract method call. /// @return The name of the function called, and the parameters it was /// given. For single-order fills and cancels, the arrays will have /// just one element. function decodeZeroExTransactionData(bytes memory transactionData) public pure returns( string memory functionName, LibOrder.Order[] memory orders, uint256[] memory takerAssetFillAmounts, bytes[] memory signatures ) { return LibTransactionDecoder.decodeZeroExTransactionData(transactionData); } /// @dev Decode AssetProxy identifier /// @param assetData AssetProxy-compliant asset data describing an ERC-20, ERC-721, ERC1155, or MultiAsset asset. /// @return The AssetProxy identifier function decodeAssetProxyId(bytes memory assetData) public pure returns ( bytes4 assetProxyId ) { return LibAssetData.decodeAssetProxyId(assetData); } /// @dev Encode ERC-20 asset data into the format described in the AssetProxy contract specification. /// @param tokenAddress The address of the ERC-20 contract hosting the asset to be traded. /// @return AssetProxy-compliant data describing the asset. function encodeERC20AssetData(address tokenAddress) public pure returns (bytes memory assetData) { return LibAssetData.encodeERC20AssetData(tokenAddress); } /// @dev Decode ERC-20 asset data from the format described in the AssetProxy contract specification. /// @param assetData AssetProxy-compliant asset data describing an ERC-20 asset. /// @return The AssetProxy identifier, and the address of the ERC-20 /// contract hosting this asset. function decodeERC20AssetData(bytes memory assetData) public pure returns ( bytes4 assetProxyId, address tokenAddress ) { return LibAssetData.decodeERC20AssetData(assetData); } /// @dev Encode ERC-721 asset data into the format described in the AssetProxy specification. /// @param tokenAddress The address of the ERC-721 contract hosting the asset to be traded. /// @param tokenId The identifier of the specific asset to be traded. /// @return AssetProxy-compliant asset data describing the asset. function encodeERC721AssetData(address tokenAddress, uint256 tokenId) public pure returns (bytes memory assetData) { return LibAssetData.encodeERC721AssetData(tokenAddress, tokenId); } /// @dev Decode ERC-721 asset data from the format described in the AssetProxy contract specification. /// @param assetData AssetProxy-compliant asset data describing an ERC-721 asset. /// @return The ERC-721 AssetProxy identifier, the address of the ERC-721 /// contract hosting this asset, and the identifier of the specific /// asset to be traded. function decodeERC721AssetData(bytes memory assetData) public pure returns ( bytes4 assetProxyId, address tokenAddress, uint256 tokenId ) { return LibAssetData.decodeERC721AssetData(assetData); } /// @dev Encode ERC-1155 asset data into the format described in the AssetProxy contract specification. /// @param tokenAddress The address of the ERC-1155 contract hosting the asset(s) to be traded. /// @param tokenIds The identifiers of the specific assets to be traded. /// @param tokenValues The amounts of each asset to be traded. /// @param callbackData Data to be passed to receiving contracts when a transfer is performed. /// @return AssetProxy-compliant asset data describing the set of assets. function encodeERC1155AssetData( address tokenAddress, uint256[] memory tokenIds, uint256[] memory tokenValues, bytes memory callbackData ) public pure returns (bytes memory assetData) { return LibAssetData.encodeERC1155AssetData( tokenAddress, tokenIds, tokenValues, callbackData ); } /// @dev Decode ERC-1155 asset data from the format described in the AssetProxy contract specification. /// @param assetData AssetProxy-compliant asset data describing an ERC-1155 set of assets. /// @return The ERC-1155 AssetProxy identifier, the address of the ERC-1155 /// contract hosting the assets, an array of the identifiers of the /// assets to be traded, an array of asset amounts to be traded, and /// callback data. Each element of the arrays corresponds to the /// same-indexed element of the other array. Return values specified as /// `memory` are returned as pointers to locations within the memory of /// the input parameter `assetData`. function decodeERC1155AssetData(bytes memory assetData) public pure returns ( bytes4 assetProxyId, address tokenAddress, uint256[] memory tokenIds, uint256[] memory tokenValues, bytes memory callbackData ) { return LibAssetData.decodeERC1155AssetData(assetData); } /// @dev Encode data for multiple assets, per the AssetProxy contract specification. /// @param amounts The amounts of each asset to be traded. /// @param nestedAssetData AssetProxy-compliant data describing each asset to be traded. /// @return AssetProxy-compliant data describing the set of assets. function encodeMultiAssetData(uint256[] memory amounts, bytes[] memory nestedAssetData) public pure returns (bytes memory assetData) { return LibAssetData.encodeMultiAssetData(amounts, nestedAssetData); } /// @dev Decode multi-asset data from the format described in the AssetProxy contract specification. /// @param assetData AssetProxy-compliant data describing a multi-asset basket. /// @return The Multi-Asset AssetProxy identifier, an array of the amounts /// of the assets to be traded, and an array of the /// AssetProxy-compliant data describing each asset to be traded. Each /// element of the arrays corresponds to the same-indexed element of the other array. function decodeMultiAssetData(bytes memory assetData) public pure returns ( bytes4 assetProxyId, uint256[] memory amounts, bytes[] memory nestedAssetData ) { return LibAssetData.decodeMultiAssetData(assetData); } /// @dev Encode StaticCall asset data into the format described in the AssetProxy contract specification. /// @param staticCallTargetAddress Target address of StaticCall. /// @param staticCallData Data that will be passed to staticCallTargetAddress in the StaticCall. /// @param expectedReturnDataHash Expected Keccak-256 hash of the StaticCall return data. /// @return AssetProxy-compliant asset data describing the set of assets. function encodeStaticCallAssetData( address staticCallTargetAddress, bytes memory staticCallData, bytes32 expectedReturnDataHash ) public pure returns (bytes memory assetData) { return LibAssetData.encodeStaticCallAssetData( staticCallTargetAddress, staticCallData, expectedReturnDataHash ); } /// @dev Decode StaticCall asset data from the format described in the AssetProxy contract specification. /// @param assetData AssetProxy-compliant asset data describing a StaticCall asset /// @return The StaticCall AssetProxy identifier, the target address of the StaticCAll, the data to be /// passed to the target address, and the expected Keccak-256 hash of the static call return data. function decodeStaticCallAssetData(bytes memory assetData) public pure returns ( bytes4 assetProxyId, address staticCallTargetAddress, bytes memory staticCallData, bytes32 expectedReturnDataHash ) { return LibAssetData.decodeStaticCallAssetData(assetData); } /// @dev Decode ERC20Bridge asset data from the format described in the AssetProxy contract specification. /// @param assetData AssetProxy-compliant asset data describing an ERC20Bridge asset /// @return The ERC20BridgeProxy identifier, the address of the ERC20 token to transfer, the address /// of the bridge contract, and extra data to be passed to the bridge contract. function decodeERC20BridgeAssetData(bytes memory assetData) public pure returns ( bytes4 assetProxyId, address tokenAddress, address bridgeAddress, bytes memory bridgeData ) { return LibAssetData.decodeERC20BridgeAssetData(assetData); } /// @dev Reverts if assetData is not of a valid format for its given proxy id. /// @param assetData AssetProxy compliant asset data. function revertIfInvalidAssetData(bytes memory assetData) public pure { return LibAssetData.revertIfInvalidAssetData(assetData); } /// @dev Simulates the maker transfers within an order and returns the index of the first failed transfer. /// @param order The order to simulate transfers for. /// @param takerAddress The address of the taker that will fill the order. /// @param takerAssetFillAmount The amount of takerAsset that the taker wished to fill. /// @return The index of the first failed transfer (or 4 if all transfers are successful). function getSimulatedOrderMakerTransferResults( LibOrder.Order memory order, address takerAddress, uint256 takerAssetFillAmount ) public returns (LibOrderTransferSimulation.OrderTransferResults orderTransferResults) { return LibOrderTransferSimulation.getSimulatedOrderMakerTransferResults( exchangeAddress, order, takerAddress, takerAssetFillAmount ); } /// @dev Simulates all of the transfers within an order and returns the index of the first failed transfer. /// @param order The order to simulate transfers for. /// @param takerAddress The address of the taker that will fill the order. /// @param takerAssetFillAmount The amount of takerAsset that the taker wished to fill. /// @return The index of the first failed transfer (or 4 if all transfers are successful). function getSimulatedOrderTransferResults( LibOrder.Order memory order, address takerAddress, uint256 takerAssetFillAmount ) public returns (LibOrderTransferSimulation.OrderTransferResults orderTransferResults) { return LibOrderTransferSimulation.getSimulatedOrderTransferResults( exchangeAddress, order, takerAddress, takerAssetFillAmount ); } /// @dev Simulates all of the transfers for each given order and returns the indices of each first failed transfer. /// @param orders Array of orders to individually simulate transfers for. /// @param takerAddresses Array of addresses of takers that will fill each order. /// @param takerAssetFillAmounts Array of amounts of takerAsset that will be filled for each order. /// @return The indices of the first failed transfer (or 4 if all transfers are successful) for each order. function getSimulatedOrdersTransferResults( LibOrder.Order[] memory orders, address[] memory takerAddresses, uint256[] memory takerAssetFillAmounts ) public returns (LibOrderTransferSimulation.OrderTransferResults[] memory orderTransferResults) { return LibOrderTransferSimulation.getSimulatedOrdersTransferResults( exchangeAddress, orders, takerAddresses, takerAssetFillAmounts ); } } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.16; pragma experimental ABIEncoderV2; import "@0x/contracts-utils/contracts/src/LibBytes.sol"; import "@0x/contracts-asset-proxy/contracts/src/interfaces/IAssetData.sol"; library LibAssetData { using LibBytes for bytes; /// @dev Decode AssetProxy identifier /// @param assetData AssetProxy-compliant asset data describing an ERC-20, ERC-721, ERC1155, or MultiAsset asset. /// @return The AssetProxy identifier function decodeAssetProxyId(bytes memory assetData) public pure returns ( bytes4 assetProxyId ) { assetProxyId = assetData.readBytes4(0); require( assetProxyId == IAssetData(address(0)).ERC20Token.selector || assetProxyId == IAssetData(address(0)).ERC721Token.selector || assetProxyId == IAssetData(address(0)).ERC1155Assets.selector || assetProxyId == IAssetData(address(0)).MultiAsset.selector || assetProxyId == IAssetData(address(0)).StaticCall.selector, "WRONG_PROXY_ID" ); return assetProxyId; } /// @dev Encode ERC-20 asset data into the format described in the AssetProxy contract specification. /// @param tokenAddress The address of the ERC-20 contract hosting the asset to be traded. /// @return AssetProxy-compliant data describing the asset. function encodeERC20AssetData(address tokenAddress) public pure returns (bytes memory assetData) { assetData = abi.encodeWithSelector(IAssetData(address(0)).ERC20Token.selector, tokenAddress); return assetData; } /// @dev Decode ERC-20 asset data from the format described in the AssetProxy contract specification. /// @param assetData AssetProxy-compliant asset data describing an ERC-20 asset. /// @return The AssetProxy identifier, and the address of the ERC-20 /// contract hosting this asset. function decodeERC20AssetData(bytes memory assetData) public pure returns ( bytes4 assetProxyId, address tokenAddress ) { assetProxyId = assetData.readBytes4(0); require( assetProxyId == IAssetData(address(0)).ERC20Token.selector, "WRONG_PROXY_ID" ); tokenAddress = assetData.readAddress(16); return (assetProxyId, tokenAddress); } /// @dev Encode ERC-721 asset data into the format described in the AssetProxy specification. /// @param tokenAddress The address of the ERC-721 contract hosting the asset to be traded. /// @param tokenId The identifier of the specific asset to be traded. /// @return AssetProxy-compliant asset data describing the asset. function encodeERC721AssetData(address tokenAddress, uint256 tokenId) public pure returns (bytes memory assetData) { assetData = abi.encodeWithSelector( IAssetData(address(0)).ERC721Token.selector, tokenAddress, tokenId ); return assetData; } /// @dev Decode ERC-721 asset data from the format described in the AssetProxy contract specification. /// @param assetData AssetProxy-compliant asset data describing an ERC-721 asset. /// @return The ERC-721 AssetProxy identifier, the address of the ERC-721 /// contract hosting this asset, and the identifier of the specific /// asset to be traded. function decodeERC721AssetData(bytes memory assetData) public pure returns ( bytes4 assetProxyId, address tokenAddress, uint256 tokenId ) { assetProxyId = assetData.readBytes4(0); require( assetProxyId == IAssetData(address(0)).ERC721Token.selector, "WRONG_PROXY_ID" ); tokenAddress = assetData.readAddress(16); tokenId = assetData.readUint256(36); return (assetProxyId, tokenAddress, tokenId); } /// @dev Encode ERC-1155 asset data into the format described in the AssetProxy contract specification. /// @param tokenAddress The address of the ERC-1155 contract hosting the asset(s) to be traded. /// @param tokenIds The identifiers of the specific assets to be traded. /// @param tokenValues The amounts of each asset to be traded. /// @param callbackData Data to be passed to receiving contracts when a transfer is performed. /// @return AssetProxy-compliant asset data describing the set of assets. function encodeERC1155AssetData( address tokenAddress, uint256[] memory tokenIds, uint256[] memory tokenValues, bytes memory callbackData ) public pure returns (bytes memory assetData) { assetData = abi.encodeWithSelector( IAssetData(address(0)).ERC1155Assets.selector, tokenAddress, tokenIds, tokenValues, callbackData ); return assetData; } /// @dev Decode ERC-1155 asset data from the format described in the AssetProxy contract specification. /// @param assetData AssetProxy-compliant asset data describing an ERC-1155 set of assets. /// @return The ERC-1155 AssetProxy identifier, the address of the ERC-1155 /// contract hosting the assets, an array of the identifiers of the /// assets to be traded, an array of asset amounts to be traded, and /// callback data. Each element of the arrays corresponds to the /// same-indexed element of the other array. Return values specified as /// `memory` are returned as pointers to locations within the memory of /// the input parameter `assetData`. function decodeERC1155AssetData(bytes memory assetData) public pure returns ( bytes4 assetProxyId, address tokenAddress, uint256[] memory tokenIds, uint256[] memory tokenValues, bytes memory callbackData ) { assetProxyId = assetData.readBytes4(0); require( assetProxyId == IAssetData(address(0)).ERC1155Assets.selector, "WRONG_PROXY_ID" ); assembly { // Skip selector and length to get to the first parameter: assetData := add(assetData, 36) // Read the value of the first parameter: tokenAddress := mload(assetData) // Point to the next parameter's data: tokenIds := add(assetData, mload(add(assetData, 32))) // Point to the next parameter's data: tokenValues := add(assetData, mload(add(assetData, 64))) // Point to the next parameter's data: callbackData := add(assetData, mload(add(assetData, 96))) } return ( assetProxyId, tokenAddress, tokenIds, tokenValues, callbackData ); } /// @dev Encode data for multiple assets, per the AssetProxy contract specification. /// @param amounts The amounts of each asset to be traded. /// @param nestedAssetData AssetProxy-compliant data describing each asset to be traded. /// @return AssetProxy-compliant data describing the set of assets. function encodeMultiAssetData(uint256[] memory amounts, bytes[] memory nestedAssetData) public pure returns (bytes memory assetData) { assetData = abi.encodeWithSelector( IAssetData(address(0)).MultiAsset.selector, amounts, nestedAssetData ); return assetData; } /// @dev Decode multi-asset data from the format described in the AssetProxy contract specification. /// @param assetData AssetProxy-compliant data describing a multi-asset basket. /// @return The Multi-Asset AssetProxy identifier, an array of the amounts /// of the assets to be traded, and an array of the /// AssetProxy-compliant data describing each asset to be traded. Each /// element of the arrays corresponds to the same-indexed element of the other array. function decodeMultiAssetData(bytes memory assetData) public pure returns ( bytes4 assetProxyId, uint256[] memory amounts, bytes[] memory nestedAssetData ) { assetProxyId = assetData.readBytes4(0); require( assetProxyId == IAssetData(address(0)).MultiAsset.selector, "WRONG_PROXY_ID" ); // solhint-disable indent (amounts, nestedAssetData) = abi.decode( assetData.slice(4, assetData.length), (uint256[], bytes[]) ); // solhint-enable indent } /// @dev Encode StaticCall asset data into the format described in the AssetProxy contract specification. /// @param staticCallTargetAddress Target address of StaticCall. /// @param staticCallData Data that will be passed to staticCallTargetAddress in the StaticCall. /// @param expectedReturnDataHash Expected Keccak-256 hash of the StaticCall return data. /// @return AssetProxy-compliant asset data describing the set of assets. function encodeStaticCallAssetData( address staticCallTargetAddress, bytes memory staticCallData, bytes32 expectedReturnDataHash ) public pure returns (bytes memory assetData) { assetData = abi.encodeWithSelector( IAssetData(address(0)).StaticCall.selector, staticCallTargetAddress, staticCallData, expectedReturnDataHash ); return assetData; } /// @dev Decode StaticCall asset data from the format described in the AssetProxy contract specification. /// @param assetData AssetProxy-compliant asset data describing a StaticCall asset /// @return The StaticCall AssetProxy identifier, the target address of the StaticCAll, the data to be /// passed to the target address, and the expected Keccak-256 hash of the static call return data. function decodeStaticCallAssetData(bytes memory assetData) public pure returns ( bytes4 assetProxyId, address staticCallTargetAddress, bytes memory staticCallData, bytes32 expectedReturnDataHash ) { assetProxyId = assetData.readBytes4(0); require( assetProxyId == IAssetData(address(0)).StaticCall.selector, "WRONG_PROXY_ID" ); (staticCallTargetAddress, staticCallData, expectedReturnDataHash) = abi.decode( assetData.slice(4, assetData.length), (address, bytes, bytes32) ); } /// @dev Decode ERC20Bridge asset data from the format described in the AssetProxy contract specification. /// @param assetData AssetProxy-compliant asset data describing an ERC20Bridge asset /// @return The ERC20BridgeProxy identifier, the address of the ERC20 token to transfer, the address /// of the bridge contract, and extra data to be passed to the bridge contract. function decodeERC20BridgeAssetData(bytes memory assetData) public pure returns ( bytes4 assetProxyId, address tokenAddress, address bridgeAddress, bytes memory bridgeData ) { assetProxyId = assetData.readBytes4(0); require( assetProxyId == IAssetData(address(0)).ERC20Bridge.selector, "WRONG_PROXY_ID" ); (tokenAddress, bridgeAddress, bridgeData) = abi.decode( assetData.slice(4, assetData.length), (address, address, bytes) ); } /// @dev Reverts if assetData is not of a valid format for its given proxy id. /// @param assetData AssetProxy compliant asset data. function revertIfInvalidAssetData(bytes memory assetData) public pure { bytes4 assetProxyId = assetData.readBytes4(0); if (assetProxyId == IAssetData(address(0)).ERC20Token.selector) { decodeERC20AssetData(assetData); } else if (assetProxyId == IAssetData(address(0)).ERC721Token.selector) { decodeERC721AssetData(assetData); } else if (assetProxyId == IAssetData(address(0)).ERC1155Assets.selector) { decodeERC1155AssetData(assetData); } else if (assetProxyId == IAssetData(address(0)).MultiAsset.selector) { decodeMultiAssetData(assetData); } else if (assetProxyId == IAssetData(address(0)).StaticCall.selector) { decodeStaticCallAssetData(assetData); } else if (assetProxyId == IAssetData(address(0)).ERC20Bridge.selector) { decodeERC20BridgeAssetData(assetData); } else { revert("WRONG_PROXY_ID"); } } } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.16; pragma experimental ABIEncoderV2; import "@0x/contracts-asset-proxy/contracts/src/interfaces/IAssetData.sol"; import "@0x/contracts-asset-proxy/contracts/src/interfaces/IDydxBridge.sol"; import "@0x/contracts-asset-proxy/contracts/src/interfaces/IDydx.sol"; import "@0x/contracts-erc20/contracts/src/LibERC20Token.sol"; import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol"; import "@0x/contracts-utils/contracts/src/LibBytes.sol"; import "@0x/contracts-utils/contracts/src/LibSafeMath.sol"; import "@0x/contracts-utils/contracts/src/D18.sol"; import "./LibAssetData.sol"; library LibDydxBalance { using LibBytes for bytes; using LibSafeMath for uint256; /// @dev Padding % added to the minimum collateralization ratio to /// prevent withdrawing exactly the amount that would make an account /// insolvent. 1 bps. int256 private constant MARGIN_RATIO_PADDING = 0.0001e18; /// @dev Structure that holds all pertinent info needed to perform a balance /// check. struct BalanceCheckInfo { IDydx dydx; address bridgeAddress; address makerAddress; address makerTokenAddress; address takerTokenAddress; int256 orderMakerToTakerRate; uint256[] accounts; IDydxBridge.BridgeAction[] actions; } /// @dev Gets the maker asset allowance for a Dydx bridge order. /// @param makerAddress The maker of the order. /// @param bridgeAddress The address of the Dydx bridge. /// @param dydx The Dydx contract address. /// @return allowance The maker asset allowance. function getDydxMakerAllowance(address makerAddress, address bridgeAddress, address dydx) public view returns (uint256 allowance) { // Allowance is infinite if the dydx bridge is an operator for the maker. return IDydx(dydx).getIsLocalOperator(makerAddress, bridgeAddress) ? uint256(-1) : 0; } /// @dev Gets the maker allowance for a /// @dev Get the maker asset balance of an order with a `DydxBridge` maker asset. /// @param order An order with a dydx maker asset. /// @param dydx The address of the dydx contract. /// @return balance The maker asset balance. function getDydxMakerBalance(LibOrder.Order memory order, address dydx) public view returns (uint256 balance) { BalanceCheckInfo memory info = _getBalanceCheckInfo(order, dydx); // Actions must be well-formed. if (!_areActionsWellFormed(info)) { return 0; } // If the rate we withdraw maker tokens is less than one, the asset // proxy will throw because we will always transfer less maker tokens // than asked. if (_getMakerTokenWithdrawRate(info) < D18.one()) { return 0; } // The maker balance is the smaller of: return LibSafeMath.min256( // How many times we can execute all the deposit actions. _getDepositableMakerAmount(info), // How many times we can execute all the actions before the an // account becomes undercollateralized. _getSolventMakerAmount(info) ); } /// @dev Checks that: /// 1. Actions are arranged as [...deposits, withdraw]. /// 2. There is only one deposit for each market ID. /// 3. Every action has a valid account index. /// 4. There is exactly one withdraw at the end and it is for the /// maker token. /// @param info State from `_getBalanceCheckInfo()`. /// @return areWellFormed Whether the actions are well-formed. function _areActionsWellFormed(BalanceCheckInfo memory info) internal view returns (bool areWellFormed) { if (info.actions.length == 0) { return false; } uint256 depositCount = 0; // Count the number of deposits. for (; depositCount < info.actions.length; ++depositCount) { IDydxBridge.BridgeAction memory action = info.actions[depositCount]; if (action.actionType != IDydxBridge.BridgeActionType.Deposit) { break; } // Search all prior actions for the same market ID. uint256 marketId = action.marketId; for (uint256 j = 0; j < depositCount; ++j) { if (info.actions[j].marketId == marketId) { // Market ID is not unique. return false; } } // Check that the account index is within the valid range. if (action.accountIdx >= info.accounts.length) { return false; } } // There must be exactly one withdraw action at the end. if (depositCount + 1 != info.actions.length) { return false; } IDydxBridge.BridgeAction memory withdraw = info.actions[depositCount]; if (withdraw.actionType != IDydxBridge.BridgeActionType.Withdraw) { return false; } // And it must be for the maker token. if (info.dydx.getMarketTokenAddress(withdraw.marketId) != info.makerTokenAddress) { return false; } // Check the account index. return withdraw.accountIdx < info.accounts.length; } /// @dev Returns the rate at which we withdraw maker tokens. /// @param info State from `_getBalanceCheckInfo()`. /// @return makerTokenWithdrawRate Maker token withdraw rate. function _getMakerTokenWithdrawRate(BalanceCheckInfo memory info) internal pure returns (int256 makerTokenWithdrawRate) { // The last action is always a withdraw for the maker token. IDydxBridge.BridgeAction memory withdraw = info.actions[info.actions.length - 1]; return _getActionRate(withdraw); } /// @dev Get how much maker asset we can transfer before a deposit fails. /// @param info State from `_getBalanceCheckInfo()`. function _getDepositableMakerAmount(BalanceCheckInfo memory info) internal view returns (uint256 depositableMakerAmount) { depositableMakerAmount = uint256(-1); // Take the minimum maker amount from all deposits. for (uint256 i = 0; i < info.actions.length; ++i) { IDydxBridge.BridgeAction memory action = info.actions[i]; // Only looking at deposit actions. if (action.actionType != IDydxBridge.BridgeActionType.Deposit) { continue; } // `depositRate` is the rate at which we convert a maker token into // a taker token for deposit. int256 depositRate = _getActionRate(action); // Taker tokens will be transferred to the maker for every fill, so // we reduce the effective deposit rate if we're depositing the taker // token. address depositToken = info.dydx.getMarketTokenAddress(action.marketId); if (info.takerTokenAddress != address(0) && depositToken == info.takerTokenAddress) { depositRate = D18.sub(depositRate, info.orderMakerToTakerRate); } // If the deposit rate is > 0, we are limited by the transferrable // token balance of the maker. if (depositRate > 0) { uint256 supply = _getTransferabeTokenAmount( depositToken, info.makerAddress, address(info.dydx) ); depositableMakerAmount = LibSafeMath.min256( depositableMakerAmount, uint256(D18.div(supply, depositRate)) ); } } } /// @dev Get how much maker asset we can transfer before an account /// becomes insolvent. /// @param info State from `_getBalanceCheckInfo()`. function _getSolventMakerAmount(BalanceCheckInfo memory info) internal view returns (uint256 solventMakerAmount) { solventMakerAmount = uint256(-1); assert(info.actions.length >= 1); IDydxBridge.BridgeAction memory withdraw = info.actions[info.actions.length - 1]; assert(withdraw.actionType == IDydxBridge.BridgeActionType.Withdraw); int256 minCr = D18.add(_getMinimumCollateralizationRatio(info.dydx), MARGIN_RATIO_PADDING); // Loop through the accounts. for (uint256 accountIdx = 0; accountIdx < info.accounts.length; ++accountIdx) { (uint256 supplyValue, uint256 borrowValue) = _getAccountMarketValues(info, info.accounts[accountIdx]); // All accounts must currently be solvent. if (borrowValue != 0 && D18.div(supplyValue, borrowValue) < minCr) { return 0; } // If this is the same account used to in the withdraw/borrow action, // compute the maker amount at which it will become insolvent. if (accountIdx != withdraw.accountIdx) { continue; } // Compute the deposit/collateralization rate, which is the rate at // which (USD) value is added to the account across all markets. int256 dd = 0; for (uint256 i = 0; i < info.actions.length - 1; ++i) { IDydxBridge.BridgeAction memory deposit = info.actions[i]; assert(deposit.actionType == IDydxBridge.BridgeActionType.Deposit); if (deposit.accountIdx == accountIdx) { dd = D18.add( dd, _getActionRateValue( info, deposit ) ); } } // Compute the borrow/withdraw rate, which is the rate at which // (USD) value is deducted from the account. int256 db = _getActionRateValue( info, withdraw ); // If the deposit to withdraw ratio is >= the minimum collateralization // ratio, then we will never become insolvent at these prices. if (D18.div(dd, db) >= minCr) { continue; } // If the adjusted deposit rates are equal, the account will remain // at the same level of collateralization. if (D18.mul(minCr, db) == dd) { continue; } // The collateralization ratio for this account, parameterized by // `t` (maker amount), is given by: // `cr = (supplyValue + t * dd) / (borrowValue + t * db)` // Solving for `t` gives us: // `t = (supplyValue - cr * borrowValue) / (cr * db - dd)` int256 t = D18.div( D18.sub(supplyValue, D18.mul(minCr, borrowValue)), D18.sub(D18.mul(minCr, db), dd) ); solventMakerAmount = LibSafeMath.min256( solventMakerAmount, // `t` is in maker token units, so convert it to maker wei. _toWei(info.makerTokenAddress, uint256(D18.clip(t))) ); } } /// @dev Create a `BalanceCheckInfo` struct. /// @param order An order with a `DydxBridge` maker asset. /// @param dydx The address of the Dydx contract. /// @return info The `BalanceCheckInfo` struct. function _getBalanceCheckInfo(LibOrder.Order memory order, address dydx) private pure returns (BalanceCheckInfo memory info) { bytes memory rawBridgeData; (, info.makerTokenAddress, info.bridgeAddress, rawBridgeData) = LibAssetData.decodeERC20BridgeAssetData(order.makerAssetData); info.dydx = IDydx(dydx); info.makerAddress = order.makerAddress; if (order.takerAssetData.length == 36) { if (order.takerAssetData.readBytes4(0) == IAssetData(0).ERC20Token.selector) { (, info.takerTokenAddress) = LibAssetData.decodeERC20AssetData(order.takerAssetData); } } info.orderMakerToTakerRate = D18.div(order.takerAssetAmount, order.makerAssetAmount); (IDydxBridge.BridgeData memory bridgeData) = abi.decode(rawBridgeData, (IDydxBridge.BridgeData)); info.accounts = bridgeData.accountNumbers; info.actions = bridgeData.actions; } /// @dev Returns the conversion rate for an action. /// @param action A `BridgeAction`. function _getActionRate(IDydxBridge.BridgeAction memory action) private pure returns (int256 rate) { rate = action.conversionRateDenominator == 0 ? D18.one() : D18.div( action.conversionRateNumerator, action.conversionRateDenominator ); } /// @dev Returns the USD value of an action based on its conversion rate /// and market prices. /// @param info State from `_getBalanceCheckInfo()`. /// @param action A `BridgeAction`. function _getActionRateValue( BalanceCheckInfo memory info, IDydxBridge.BridgeAction memory action ) private view returns (int256 value) { address toToken = info.dydx.getMarketTokenAddress(action.marketId); uint256 fromTokenDecimals = LibERC20Token.decimals(info.makerTokenAddress); uint256 toTokenDecimals = LibERC20Token.decimals(toToken); // First express the rate as 18-decimal units. value = toTokenDecimals > fromTokenDecimals ? int256( uint256(_getActionRate(action)) .safeDiv(10 ** (toTokenDecimals - fromTokenDecimals)) ) : int256( uint256(_getActionRate(action)) .safeMul(10 ** (fromTokenDecimals - toTokenDecimals)) ); // Prices have 18 + (18 - TOKEN_DECIMALS) decimal places because // consistency is stupid. uint256 price = info.dydx.getMarketPrice(action.marketId).value; // Make prices have 18 decimals. if (toTokenDecimals > 18) { price = price.safeMul(10 ** (toTokenDecimals - 18)); } else { price = price.safeDiv(10 ** (18 - toTokenDecimals)); } // The action value is the action rate times the price. value = D18.mul(price, value); // Scale by the market premium. int256 marketPremium = D18.add( D18.one(), info.dydx.getMarketMarginPremium(action.marketId).value ); if (action.actionType == IDydxBridge.BridgeActionType.Deposit) { value = D18.div(value, marketPremium); } else { value = D18.mul(value, marketPremium); } } /// @dev Convert a `D18` fraction of 1 token to the equivalent integer wei. /// @param token Address the of the token. /// @param units Token units expressed with 18 digit precision. function _toWei(address token, uint256 units) private view returns (uint256 rate) { uint256 decimals = LibERC20Token.decimals(token); rate = decimals > 18 ? units.safeMul(10 ** (decimals - 18)) : units.safeDiv(10 ** (18 - decimals)); } /// @dev Get the global minimum collateralization ratio required for /// an account to be considered solvent. /// @param dydx The Dydx interface. function _getMinimumCollateralizationRatio(IDydx dydx) private view returns (int256 ratio) { IDydx.RiskParams memory riskParams = dydx.getRiskParams(); return D18.add(D18.one(), D18.toSigned(riskParams.marginRatio.value)); } /// @dev Get the total supply and borrow values for an account across all markets. /// @param info State from `_getBalanceCheckInfo()`. /// @param account The Dydx account identifier. function _getAccountMarketValues(BalanceCheckInfo memory info, uint256 account) private view returns (uint256 supplyValue, uint256 borrowValue) { (IDydx.Value memory supplyValue_, IDydx.Value memory borrowValue_) = info.dydx.getAdjustedAccountValues(IDydx.AccountInfo( info.makerAddress, account )); // Account values have 36 decimal places because dydx likes to make sure // you're paying attention. return (supplyValue_.value / 1e18, borrowValue_.value / 1e18); } /// @dev Get the amount of an ERC20 token held by `owner` that can be transferred /// by `spender`. /// @param tokenAddress The address of the ERC20 token. /// @param owner The address of the token holder. /// @param spender The address of the token spender. function _getTransferabeTokenAmount( address tokenAddress, address owner, address spender ) private view returns (uint256 transferableAmount) { return LibSafeMath.min256( LibERC20Token.allowance(tokenAddress, owner, spender), LibERC20Token.balanceOf(tokenAddress, owner) ); } } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.16; pragma experimental ABIEncoderV2; import "@0x/contracts-exchange/contracts/src/interfaces/IExchange.sol"; import "@0x/contracts-exchange/contracts/src/libs/LibExchangeRichErrorDecoder.sol"; import "@0x/contracts-exchange-libs/contracts/src/LibExchangeRichErrors.sol"; import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol"; import "@0x/contracts-exchange-libs/contracts/src/LibFillResults.sol"; import "@0x/contracts-utils/contracts/src/LibBytes.sol"; library LibOrderTransferSimulation { using LibBytes for bytes; enum OrderTransferResults { TakerAssetDataFailed, // Transfer of takerAsset failed MakerAssetDataFailed, // Transfer of makerAsset failed TakerFeeAssetDataFailed, // Transfer of takerFeeAsset failed MakerFeeAssetDataFailed, // Transfer of makerFeeAsset failed TransfersSuccessful // All transfers in the order were successful } // NOTE(jalextowle): This is a random address that we use to avoid issues that addresses like `address(1)` // may cause later. address constant internal UNUSED_ADDRESS = address(0x377f698C4c287018D09b516F415317aEC5919332); // keccak256(abi.encodeWithSignature("Error(string)", "TRANSFERS_SUCCESSFUL")); bytes32 constant internal _TRANSFERS_SUCCESSFUL_RESULT_HASH = 0xf43f26ea5a94b478394a975e856464913dc1a8a1ca70939d974aa7c238aa0ce0; /// @dev Simulates the maker transfers within an order and returns the index of the first failed transfer. /// @param order The order to simulate transfers for. /// @param takerAddress The address of the taker that will fill the order. /// @param takerAssetFillAmount The amount of takerAsset that the taker wished to fill. /// @return The index of the first failed transfer (or 4 if all transfers are successful). function getSimulatedOrderMakerTransferResults( address exchange, LibOrder.Order memory order, address takerAddress, uint256 takerAssetFillAmount ) public returns (OrderTransferResults orderTransferResults) { LibFillResults.FillResults memory fillResults = LibFillResults.calculateFillResults( order, takerAssetFillAmount, IExchange(exchange).protocolFeeMultiplier(), tx.gasprice ); bytes[] memory assetData = new bytes[](2); address[] memory fromAddresses = new address[](2); address[] memory toAddresses = new address[](2); uint256[] memory amounts = new uint256[](2); // Transfer `makerAsset` from maker to taker assetData[0] = order.makerAssetData; fromAddresses[0] = order.makerAddress; toAddresses[0] = takerAddress == address(0) ? UNUSED_ADDRESS : takerAddress; amounts[0] = fillResults.makerAssetFilledAmount; // Transfer `makerFeeAsset` from maker to feeRecipient assetData[1] = order.makerFeeAssetData; fromAddresses[1] = order.makerAddress; toAddresses[1] = order.feeRecipientAddress == address(0) ? UNUSED_ADDRESS : order.feeRecipientAddress; amounts[1] = fillResults.makerFeePaid; return _simulateTransferFromCalls( exchange, assetData, fromAddresses, toAddresses, amounts ); } /// @dev Simulates all of the transfers within an order and returns the index of the first failed transfer. /// @param order The order to simulate transfers for. /// @param takerAddress The address of the taker that will fill the order. /// @param takerAssetFillAmount The amount of takerAsset that the taker wished to fill. /// @return The index of the first failed transfer (or 4 if all transfers are successful). function getSimulatedOrderTransferResults( address exchange, LibOrder.Order memory order, address takerAddress, uint256 takerAssetFillAmount ) public returns (OrderTransferResults orderTransferResults) { LibFillResults.FillResults memory fillResults = LibFillResults.calculateFillResults( order, takerAssetFillAmount, IExchange(exchange).protocolFeeMultiplier(), tx.gasprice ); // Create input arrays bytes[] memory assetData = new bytes[](4); address[] memory fromAddresses = new address[](4); address[] memory toAddresses = new address[](4); uint256[] memory amounts = new uint256[](4); // Transfer `takerAsset` from taker to maker assetData[0] = order.takerAssetData; fromAddresses[0] = takerAddress; toAddresses[0] = order.makerAddress; amounts[0] = takerAssetFillAmount; // Transfer `makerAsset` from maker to taker assetData[1] = order.makerAssetData; fromAddresses[1] = order.makerAddress; toAddresses[1] = takerAddress == address(0) ? UNUSED_ADDRESS : takerAddress; amounts[1] = fillResults.makerAssetFilledAmount; // Transfer `takerFeeAsset` from taker to feeRecipient assetData[2] = order.takerFeeAssetData; fromAddresses[2] = takerAddress; toAddresses[2] = order.feeRecipientAddress == address(0) ? UNUSED_ADDRESS : order.feeRecipientAddress; amounts[2] = fillResults.takerFeePaid; // Transfer `makerFeeAsset` from maker to feeRecipient assetData[3] = order.makerFeeAssetData; fromAddresses[3] = order.makerAddress; toAddresses[3] = order.feeRecipientAddress == address(0) ? UNUSED_ADDRESS : order.feeRecipientAddress; amounts[3] = fillResults.makerFeePaid; return _simulateTransferFromCalls( exchange, assetData, fromAddresses, toAddresses, amounts ); } /// @dev Simulates all of the transfers for each given order and returns the indices of each first failed transfer. /// @param orders Array of orders to individually simulate transfers for. /// @param takerAddresses Array of addresses of takers that will fill each order. /// @param takerAssetFillAmounts Array of amounts of takerAsset that will be filled for each order. /// @return The indices of the first failed transfer (or 4 if all transfers are successful) for each order. function getSimulatedOrdersTransferResults( address exchange, LibOrder.Order[] memory orders, address[] memory takerAddresses, uint256[] memory takerAssetFillAmounts ) public returns (OrderTransferResults[] memory orderTransferResults) { uint256 length = orders.length; orderTransferResults = new OrderTransferResults[](length); for (uint256 i = 0; i != length; i++) { orderTransferResults[i] = getSimulatedOrderTransferResults( exchange, orders[i], takerAddresses[i], takerAssetFillAmounts[i] ); } return orderTransferResults; } /// @dev Makes the simulation call with information about the transfers and processes /// the returndata. /// @param assetData The assetdata to use to make transfers. /// @param fromAddresses The addresses to transfer funds. /// @param toAddresses The addresses that will receive funds /// @param amounts The amounts involved in the transfer. function _simulateTransferFromCalls( address exchange, bytes[] memory assetData, address[] memory fromAddresses, address[] memory toAddresses, uint256[] memory amounts ) private returns (OrderTransferResults orderTransferResults) { // Encode data for `simulateDispatchTransferFromCalls(assetData, fromAddresses, toAddresses, amounts)` bytes memory simulateDispatchTransferFromCallsData = abi.encodeWithSelector( IExchange(address(0)).simulateDispatchTransferFromCalls.selector, assetData, fromAddresses, toAddresses, amounts ); // Perform call and catch revert (, bytes memory returnData) = address(exchange).call(simulateDispatchTransferFromCallsData); bytes4 selector = returnData.readBytes4(0); if (selector == LibExchangeRichErrors.AssetProxyDispatchErrorSelector()) { // Decode AssetProxyDispatchError and return index of failed transfer (, bytes32 failedTransferIndex,) = LibExchangeRichErrorDecoder.decodeAssetProxyDispatchError(returnData); return OrderTransferResults(uint8(uint256(failedTransferIndex))); } else if (selector == LibExchangeRichErrors.AssetProxyTransferErrorSelector()) { // Decode AssetProxyTransferError and return index of failed transfer (bytes32 failedTransferIndex, ,) = LibExchangeRichErrorDecoder.decodeAssetProxyTransferError(returnData); return OrderTransferResults(uint8(uint256(failedTransferIndex))); } else if (keccak256(returnData) == _TRANSFERS_SUCCESSFUL_RESULT_HASH) { // All transfers were successful return OrderTransferResults.TransfersSuccessful; } else { revert("UNKNOWN_RETURN_DATA"); } } } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.16; pragma experimental ABIEncoderV2; import "@0x/contracts-exchange/contracts/src/interfaces/IExchange.sol"; import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol"; import "@0x/contracts-utils/contracts/src/LibBytes.sol"; library LibTransactionDecoder { using LibBytes for bytes; /// @dev Decodes the call data for an Exchange contract method call. /// @param transactionData ABI-encoded calldata for an Exchange /// contract method call. /// @return The name of the function called, and the parameters it was /// given. For single-order fills and cancels, the arrays will have /// just one element. function decodeZeroExTransactionData(bytes memory transactionData) public pure returns( string memory functionName, LibOrder.Order[] memory orders, uint256[] memory takerAssetFillAmounts, bytes[] memory signatures ) { bytes4 functionSelector = transactionData.readBytes4(0); if (functionSelector == IExchange(address(0)).batchCancelOrders.selector) { functionName = "batchCancelOrders"; } else if (functionSelector == IExchange(address(0)).batchFillOrders.selector) { functionName = "batchFillOrders"; } else if (functionSelector == IExchange(address(0)).batchFillOrdersNoThrow.selector) { functionName = "batchFillOrdersNoThrow"; } else if (functionSelector == IExchange(address(0)).batchFillOrKillOrders.selector) { functionName = "batchFillOrKillOrders"; } else if (functionSelector == IExchange(address(0)).cancelOrder.selector) { functionName = "cancelOrder"; } else if (functionSelector == IExchange(address(0)).fillOrder.selector) { functionName = "fillOrder"; } else if (functionSelector == IExchange(address(0)).fillOrKillOrder.selector) { functionName = "fillOrKillOrder"; } else if (functionSelector == IExchange(address(0)).marketBuyOrdersNoThrow.selector) { functionName = "marketBuyOrdersNoThrow"; } else if (functionSelector == IExchange(address(0)).marketSellOrdersNoThrow.selector) { functionName = "marketSellOrdersNoThrow"; } else if (functionSelector == IExchange(address(0)).marketBuyOrdersFillOrKill.selector) { functionName = "marketBuyOrdersFillOrKill"; } else if (functionSelector == IExchange(address(0)).marketSellOrdersFillOrKill.selector) { functionName = "marketSellOrdersFillOrKill"; } else if (functionSelector == IExchange(address(0)).matchOrders.selector) { functionName = "matchOrders"; } else if ( functionSelector == IExchange(address(0)).cancelOrdersUpTo.selector || functionSelector == IExchange(address(0)).executeTransaction.selector ) { revert("UNIMPLEMENTED"); } else { revert("UNKNOWN_FUNCTION_SELECTOR"); } if (functionSelector == IExchange(address(0)).batchCancelOrders.selector) { // solhint-disable-next-line indent orders = abi.decode(transactionData.slice(4, transactionData.length), (LibOrder.Order[])); takerAssetFillAmounts = new uint256[](0); signatures = new bytes[](0); } else if ( functionSelector == IExchange(address(0)).batchFillOrKillOrders.selector || functionSelector == IExchange(address(0)).batchFillOrders.selector || functionSelector == IExchange(address(0)).batchFillOrdersNoThrow.selector ) { (orders, takerAssetFillAmounts, signatures) = _makeReturnValuesForBatchFill(transactionData); } else if (functionSelector == IExchange(address(0)).cancelOrder.selector) { orders = new LibOrder.Order[](1); orders[0] = abi.decode(transactionData.slice(4, transactionData.length), (LibOrder.Order)); takerAssetFillAmounts = new uint256[](0); signatures = new bytes[](0); } else if ( functionSelector == IExchange(address(0)).fillOrKillOrder.selector || functionSelector == IExchange(address(0)).fillOrder.selector ) { (orders, takerAssetFillAmounts, signatures) = _makeReturnValuesForSingleOrderFill(transactionData); } else if ( functionSelector == IExchange(address(0)).marketBuyOrdersNoThrow.selector || functionSelector == IExchange(address(0)).marketSellOrdersNoThrow.selector || functionSelector == IExchange(address(0)).marketBuyOrdersFillOrKill.selector || functionSelector == IExchange(address(0)).marketSellOrdersFillOrKill.selector ) { (orders, takerAssetFillAmounts, signatures) = _makeReturnValuesForMarketFill(transactionData); } else if (functionSelector == IExchange(address(0)).matchOrders.selector) { ( LibOrder.Order memory leftOrder, LibOrder.Order memory rightOrder, bytes memory leftSignature, bytes memory rightSignature ) = abi.decode( transactionData.slice(4, transactionData.length), (LibOrder.Order, LibOrder.Order, bytes, bytes) ); orders = new LibOrder.Order[](2); orders[0] = leftOrder; orders[1] = rightOrder; takerAssetFillAmounts = new uint256[](2); takerAssetFillAmounts[0] = leftOrder.takerAssetAmount; takerAssetFillAmounts[1] = rightOrder.takerAssetAmount; signatures = new bytes[](2); signatures[0] = leftSignature; signatures[1] = rightSignature; } } function _makeReturnValuesForSingleOrderFill(bytes memory transactionData) private pure returns( LibOrder.Order[] memory orders, uint256[] memory takerAssetFillAmounts, bytes[] memory signatures ) { orders = new LibOrder.Order[](1); takerAssetFillAmounts = new uint256[](1); signatures = new bytes[](1); // solhint-disable-next-line indent (orders[0], takerAssetFillAmounts[0], signatures[0]) = abi.decode( transactionData.slice(4, transactionData.length), (LibOrder.Order, uint256, bytes) ); } function _makeReturnValuesForBatchFill(bytes memory transactionData) private pure returns( LibOrder.Order[] memory orders, uint256[] memory takerAssetFillAmounts, bytes[] memory signatures ) { // solhint-disable-next-line indent (orders, takerAssetFillAmounts, signatures) = abi.decode( transactionData.slice(4, transactionData.length), // solhint-disable-next-line indent (LibOrder.Order[], uint256[], bytes[]) ); } function _makeReturnValuesForMarketFill(bytes memory transactionData) private pure returns( LibOrder.Order[] memory orders, uint256[] memory takerAssetFillAmounts, bytes[] memory signatures ) { takerAssetFillAmounts = new uint256[](1); // solhint-disable-next-line indent (orders, takerAssetFillAmounts[0], signatures) = abi.decode( transactionData.slice(4, transactionData.length), // solhint-disable-next-line indent (LibOrder.Order[], uint256, bytes[]) ); } } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.16; pragma experimental ABIEncoderV2; import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol"; import "@0x/contracts-exchange-libs/contracts/src/LibMath.sol"; import "@0x/contracts-utils/contracts/src/LibBytes.sol"; import "@0x/contracts-utils/contracts/src/LibSafeMath.sol"; import "./Addresses.sol"; import "./AssetBalance.sol"; import "./LibAssetData.sol"; import "./LibOrderTransferSimulation.sol"; contract OrderValidationUtils is Addresses, AssetBalance { using LibBytes for bytes; using LibSafeMath for uint256; /// @dev Fetches all order-relevant information needed to validate if the supplied order is fillable. /// @param order The order structure. /// @param signature Signature provided by maker that proves the order's authenticity. /// `0x01` can always be provided if the signature does not need to be validated. /// @return The orderInfo (hash, status, and `takerAssetAmount` already filled for the given order), /// fillableTakerAssetAmount (amount of the order's `takerAssetAmount` that is fillable given all on-chain state), /// and isValidSignature (validity of the provided signature). /// NOTE: If the `takerAssetData` encodes data for multiple assets, `fillableTakerAssetAmount` will represent a "scaled" /// amount, meaning it must be multiplied by all the individual asset amounts within the `takerAssetData` to get the final /// amount of each asset that can be filled. function getOrderRelevantState(LibOrder.Order memory order, bytes memory signature) public returns ( LibOrder.OrderInfo memory orderInfo, uint256 fillableTakerAssetAmount, bool isValidSignature ) { // Get info specific to order orderInfo = IExchange(exchangeAddress).getOrderInfo(order); // Validate the maker's signature address makerAddress = order.makerAddress; isValidSignature = IExchange(exchangeAddress).isValidOrderSignature( order, signature ); // Get the transferable amount of the `makerAsset` uint256 transferableMakerAssetAmount = _getTransferableConvertedMakerAssetAmount( order ); // Get the amount of `takerAsset` that is transferable to maker given the // transferability of `makerAsset`, `makerFeeAsset`, // and the total amounts specified in the order uint256 transferableTakerAssetAmount; if (order.makerAssetData.equals(order.makerFeeAssetData)) { // If `makerAsset` equals `makerFeeAsset`, the % that can be filled is // transferableMakerAssetAmount / (makerAssetAmount + makerFee) transferableTakerAssetAmount = LibMath.getPartialAmountFloor( transferableMakerAssetAmount, order.makerAssetAmount.safeAdd(order.makerFee), order.takerAssetAmount ); } else { // If `makerFee` is 0, the % that can be filled is (transferableMakerAssetAmount / makerAssetAmount) if (order.makerFee == 0) { transferableTakerAssetAmount = LibMath.getPartialAmountFloor( transferableMakerAssetAmount, order.makerAssetAmount, order.takerAssetAmount ); // If `makerAsset` does not equal `makerFeeAsset`, the % that can be filled is the lower of // (transferableMakerAssetAmount / makerAssetAmount) and (transferableMakerAssetFeeAmount / makerFee) } else { // Get the transferable amount of the `makerFeeAsset` uint256 transferableMakerFeeAssetAmount = getTransferableAssetAmount( makerAddress, order.makerFeeAssetData ); uint256 transferableMakerToTakerAmount = LibMath.getPartialAmountFloor( transferableMakerAssetAmount, order.makerAssetAmount, order.takerAssetAmount ); uint256 transferableMakerFeeToTakerAmount = LibMath.getPartialAmountFloor( transferableMakerFeeAssetAmount, order.makerFee, order.takerAssetAmount ); transferableTakerAssetAmount = LibSafeMath.min256(transferableMakerToTakerAmount, transferableMakerFeeToTakerAmount); } } // `fillableTakerAssetAmount` is the lower of the order's remaining `takerAssetAmount` and the `transferableTakerAssetAmount` fillableTakerAssetAmount = LibSafeMath.min256( order.takerAssetAmount.safeSub(orderInfo.orderTakerAssetFilledAmount), transferableTakerAssetAmount ); // Ensure that all of the asset data is valid. Fee asset data only needs // to be valid if the fees are nonzero. if (!_areOrderAssetDatasValid(order)) { fillableTakerAssetAmount = 0; } // If the order is not fillable, then the fillable taker asset amount is // zero by definition. if (orderInfo.orderStatus != LibOrder.OrderStatus.FILLABLE) { fillableTakerAssetAmount = 0; } return (orderInfo, fillableTakerAssetAmount, isValidSignature); } /// @dev Fetches all order-relevant information needed to validate if the supplied orders are fillable. /// @param orders Array of order structures. /// @param signatures Array of signatures provided by makers that prove the authenticity of the orders. /// `0x01` can always be provided if a signature does not need to be validated. /// @return The ordersInfo (array of the hash, status, and `takerAssetAmount` already filled for each order), /// fillableTakerAssetAmounts (array of amounts for each order's `takerAssetAmount` that is fillable given all on-chain state), /// and isValidSignature (array containing the validity of each provided signature). /// NOTE: If the `takerAssetData` encodes data for multiple assets, each element of `fillableTakerAssetAmounts` /// will represent a "scaled" amount, meaning it must be multiplied by all the individual asset amounts within /// the `takerAssetData` to get the final amount of each asset that can be filled. function getOrderRelevantStates(LibOrder.Order[] memory orders, bytes[] memory signatures) public returns ( LibOrder.OrderInfo[] memory ordersInfo, uint256[] memory fillableTakerAssetAmounts, bool[] memory isValidSignature ) { uint256 length = orders.length; ordersInfo = new LibOrder.OrderInfo[](length); fillableTakerAssetAmounts = new uint256[](length); isValidSignature = new bool[](length); for (uint256 i = 0; i != length; i++) { (ordersInfo[i], fillableTakerAssetAmounts[i], isValidSignature[i]) = getOrderRelevantState( orders[i], signatures[i] ); } return (ordersInfo, fillableTakerAssetAmounts, isValidSignature); } /// @dev Gets the amount of an asset transferable by the maker of an order. /// @param ownerAddress Address of the owner of the asset. /// @param assetData Description of tokens, per the AssetProxy contract specification. /// @return The amount of the asset tranferable by the owner. /// NOTE: If the `assetData` encodes data for multiple assets, the `transferableAssetAmount` /// will represent the amount of times the entire `assetData` can be transferred. To calculate /// the total individual transferable amounts, this scaled `transferableAmount` must be multiplied by /// the individual asset amounts located within the `assetData`. function getTransferableAssetAmount(address ownerAddress, bytes memory assetData) public returns (uint256 transferableAssetAmount) { (uint256 balance, uint256 allowance) = getBalanceAndAssetProxyAllowance( ownerAddress, assetData ); transferableAssetAmount = LibSafeMath.min256(balance, allowance); return transferableAssetAmount; } /// @dev Gets the amount of an asset transferable by the maker of an order. /// Similar to `getTransferableAssetAmount()`, but can handle maker asset /// types that depend on taker assets being transferred first (e.g., Dydx bridge). /// @param order The order. /// @return transferableAssetAmount Amount of maker asset that can be transferred. function _getTransferableConvertedMakerAssetAmount( LibOrder.Order memory order ) internal returns (uint256 transferableAssetAmount) { (uint256 balance, uint256 allowance) = _getConvertibleMakerBalanceAndAssetProxyAllowance(order); transferableAssetAmount = LibSafeMath.min256(balance, allowance); return LibSafeMath.min256(transferableAssetAmount, order.makerAssetAmount); } /// @dev Checks that the asset data contained in a ZeroEx is valid and returns /// a boolean that indicates whether or not the asset data was found to be valid. /// @param order A ZeroEx order to validate. /// @return The validatity of the asset data. function _areOrderAssetDatasValid(LibOrder.Order memory order) internal pure returns (bool) { return _isAssetDataValid(order.makerAssetData) && (order.makerFee == 0 || _isAssetDataValid(order.makerFeeAssetData)) && _isAssetDataValid(order.takerAssetData) && (order.takerFee == 0 || _isAssetDataValid(order.takerFeeAssetData)); } /// @dev This function handles the edge cases around taker validation. This function /// currently attempts to find duplicate ERC721 token's in the taker /// multiAssetData. /// @param assetData The asset data that should be validated. /// @return Whether or not the order should be considered valid. function _isAssetDataValid(bytes memory assetData) internal pure returns (bool) { // Asset data must be composed of an asset proxy Id and a bytes segment with // a length divisible by 32. if (assetData.length % 32 != 4) { return false; } // Only process the taker asset data if it is multiAssetData. bytes4 assetProxyId = assetData.readBytes4(0); if (assetProxyId != IAssetData(address(0)).MultiAsset.selector) { return true; } // Get array of values and array of assetDatas (, , bytes[] memory nestedAssetData) = LibAssetData.decodeMultiAssetData(assetData); uint256 length = nestedAssetData.length; for (uint256 i = 0; i != length; i++) { // TODO(jalextowle): Implement similar validation for non-fungible ERC1155 asset data. bytes4 nestedAssetProxyId = nestedAssetData[i].readBytes4(0); if (nestedAssetProxyId == IAssetData(address(0)).ERC721Token.selector) { if (_isAssetDataDuplicated(nestedAssetData, i)) { return false; } } } return true; } /// Determines whether or not asset data is duplicated later in the nested asset data. /// @param nestedAssetData The asset data to scan for duplication. /// @param startIdx The index where the scan should begin. /// @return A boolean reflecting whether or not the starting asset data was duplicated. function _isAssetDataDuplicated( bytes[] memory nestedAssetData, uint256 startIdx ) internal pure returns (bool) { uint256 length = nestedAssetData.length; for (uint256 i = startIdx + 1; i < length; i++) { if (nestedAssetData[startIdx].equals(nestedAssetData[i])) { return true; } } } } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // solhint-disable pragma solidity ^0.5.9; pragma experimental ABIEncoderV2; // @dev Interface of the asset proxy's assetData. // The asset proxies take an ABI encoded `bytes assetData` as argument. // This argument is ABI encoded as one of the methods of this interface. interface IAssetData { /// @dev Function signature for encoding ERC20 assetData. /// @param tokenAddress Address of ERC20Token contract. function ERC20Token(address tokenAddress) external; /// @dev Function signature for encoding ERC721 assetData. /// @param tokenAddress Address of ERC721 token contract. /// @param tokenId Id of ERC721 token to be transferred. function ERC721Token( address tokenAddress, uint256 tokenId ) external; /// @dev Function signature for encoding ERC1155 assetData. /// @param tokenAddress Address of ERC1155 token contract. /// @param tokenIds Array of ids of tokens to be transferred. /// @param values Array of values that correspond to each token id to be transferred. /// Note that each value will be multiplied by the amount being filled in the order before transferring. /// @param callbackData Extra data to be passed to receiver's `onERC1155Received` callback function. function ERC1155Assets( address tokenAddress, uint256[] calldata tokenIds, uint256[] calldata values, bytes calldata callbackData ) external; /// @dev Function signature for encoding MultiAsset assetData. /// @param values Array of amounts that correspond to each asset to be transferred. /// Note that each value will be multiplied by the amount being filled in the order before transferring. /// @param nestedAssetData Array of assetData fields that will be be dispatched to their correspnding AssetProxy contract. function MultiAsset( uint256[] calldata values, bytes[] calldata nestedAssetData ) external; /// @dev Function signature for encoding StaticCall assetData. /// @param staticCallTargetAddress Address that will execute the staticcall. /// @param staticCallData Data that will be executed via staticcall on the staticCallTargetAddress. /// @param expectedReturnDataHash Keccak-256 hash of the expected staticcall return data. function StaticCall( address staticCallTargetAddress, bytes calldata staticCallData, bytes32 expectedReturnDataHash ) external; /// @dev Function signature for encoding ERC20Bridge assetData. /// @param tokenAddress Address of token to transfer. /// @param bridgeAddress Address of the bridge contract. /// @param bridgeData Arbitrary data to be passed to the bridge contract. function ERC20Bridge( address tokenAddress, address bridgeAddress, bytes calldata bridgeData ) external; } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.9; contract IAssetProxy { /// @dev Transfers assets. Either succeeds or throws. /// @param assetData Byte array encoded for the respective asset proxy. /// @param from Address to transfer asset from. /// @param to Address to transfer asset to. /// @param amount Amount of asset to transfer. function transferFrom( bytes calldata assetData, address from, address to, uint256 amount ) external; /// @dev Gets the proxy id associated with the proxy address. /// @return Proxy id. function getProxyId() external pure returns (bytes4); } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.9; import "@0x/contracts-erc20/contracts/src/interfaces/IERC20Token.sol"; contract PotLike { function chi() external returns (uint256); function rho() external returns (uint256); function drip() external returns (uint256); function join(uint256) external; function exit(uint256) external; } // The actual Chai contract can be found here: https://github.com/dapphub/chai contract IChai is IERC20Token { /// @dev Withdraws Dai owned by `src` /// @param src Address that owns Dai. /// @param wad Amount of Dai to withdraw. function draw( address src, uint256 wad ) external; /// @dev Queries Dai balance of Chai holder. /// @param usr Address of Chai holder. /// @return Dai balance. function dai(address usr) external returns (uint256); /// @dev Queries the Pot contract used by the Chai contract. function pot() external returns (PotLike); /// @dev Deposits Dai in exchange for Chai /// @param dst Address to receive Chai. /// @param wad Amount of Dai to deposit. function join( address dst, uint256 wad ) external; } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.9; pragma experimental ABIEncoderV2; interface IDydx { /// @dev Represents the unique key that specifies an account struct AccountInfo { address owner; // The address that owns the account uint256 number; // A nonce that allows a single address to control many accounts } enum ActionType { Deposit, // supply tokens Withdraw, // borrow tokens Transfer, // transfer balance between accounts Buy, // buy an amount of some token (externally) Sell, // sell an amount of some token (externally) Trade, // trade tokens against another account Liquidate, // liquidate an undercollateralized or expiring account Vaporize, // use excess tokens to zero-out a completely negative account Call // send arbitrary data to an address } /// @dev Arguments that are passed to Solo in an ordered list as part of a single operation. /// Each ActionArgs has an actionType which specifies which action struct that this data will be /// parsed into before being processed. struct ActionArgs { ActionType actionType; uint256 accountIdx; AssetAmount amount; uint256 primaryMarketId; uint256 secondaryMarketId; address otherAddress; uint256 otherAccountIdx; bytes data; } enum AssetDenomination { Wei, // the amount is denominated in wei Par // the amount is denominated in par } enum AssetReference { Delta, // the amount is given as a delta from the current value Target // the amount is given as an exact number to end up at } struct AssetAmount { bool sign; // true if positive AssetDenomination denomination; AssetReference ref; uint256 value; } struct D256 { uint256 value; } struct Value { uint256 value; } struct Price { uint256 value; } struct OperatorArg { address operator; bool trusted; } /// @dev The global risk parameters that govern the health and security of the system struct RiskParams { // Required ratio of over-collateralization D256 marginRatio; // Percentage penalty incurred by liquidated accounts D256 liquidationSpread; // Percentage of the borrower's interest fee that gets passed to the suppliers D256 earningsRate; // The minimum absolute borrow value of an account // There must be sufficient incentivize to liquidate undercollateralized accounts Value minBorrowedValue; } /// @dev The main entry-point to Solo that allows users and contracts to manage accounts. /// Take one or more actions on one or more accounts. The msg.sender must be the owner or /// operator of all accounts except for those being liquidated, vaporized, or traded with. /// One call to operate() is considered a singular "operation". Account collateralization is /// ensured only after the completion of the entire operation. /// @param accounts A list of all accounts that will be used in this operation. Cannot contain /// duplicates. In each action, the relevant account will be referred-to by its /// index in the list. /// @param actions An ordered list of all actions that will be taken in this operation. The /// actions will be processed in order. function operate( AccountInfo[] calldata accounts, ActionArgs[] calldata actions ) external; // @dev Approves/disapproves any number of operators. An operator is an external address that has the // same permissions to manipulate an account as the owner of the account. Operators are simply // addresses and therefore may either be externally-owned Ethereum accounts OR smart contracts. // Operators are also able to act as AutoTrader contracts on behalf of the account owner if the // operator is a smart contract and implements the IAutoTrader interface. // @param args A list of OperatorArgs which have an address and a boolean. The boolean value // denotes whether to approve (true) or revoke approval (false) for that address. function setOperators(OperatorArg[] calldata args) external; /// @dev Return true if a particular address is approved as an operator for an owner's accounts. /// Approved operators can act on the accounts of the owner as if it were the operator's own. /// @param owner The owner of the accounts /// @param operator The possible operator /// @return isLocalOperator True if operator is approved for owner's accounts function getIsLocalOperator( address owner, address operator ) external view returns (bool isLocalOperator); /// @dev Get the ERC20 token address for a market. /// @param marketId The market to query /// @return tokenAddress The token address function getMarketTokenAddress( uint256 marketId ) external view returns (address tokenAddress); /// @dev Get all risk parameters in a single struct. /// @return riskParams All global risk parameters function getRiskParams() external view returns (RiskParams memory riskParams); /// @dev Get the price of the token for a market. /// @param marketId The market to query /// @return price The price of each atomic unit of the token function getMarketPrice( uint256 marketId ) external view returns (Price memory price); /// @dev Get the margin premium for a market. A margin premium makes it so that any positions that /// include the market require a higher collateralization to avoid being liquidated. /// @param marketId The market to query /// @return premium The market's margin premium function getMarketMarginPremium(uint256 marketId) external view returns (D256 memory premium); /// @dev Get the total supplied and total borrowed values of an account adjusted by the marginPremium /// of each market. Supplied values are divided by (1 + marginPremium) for each market and /// borrowed values are multiplied by (1 + marginPremium) for each market. Comparing these /// adjusted values gives the margin-ratio of the account which will be compared to the global /// margin-ratio when determining if the account can be liquidated. /// @param account The account to query /// @return supplyValue The supplied value of the account (adjusted for marginPremium) /// @return borrowValue The borrowed value of the account (adjusted for marginPremium) function getAdjustedAccountValues( AccountInfo calldata account ) external view returns (Value memory supplyValue, Value memory borrowValue); } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.9; interface IDydxBridge { /// @dev This is the subset of `IDydx.ActionType` that are supported by the bridge. enum BridgeActionType { Deposit, // Deposit tokens into dydx account. Withdraw // Withdraw tokens from dydx account. } struct BridgeAction { BridgeActionType actionType; // Action to run on dydx account. uint256 accountIdx; // Index in `BridgeData.accountNumbers` for this action. uint256 marketId; // Market to operate on. uint256 conversionRateNumerator; // Optional. If set, transfer amount is scaled by (conversionRateNumerator/conversionRateDenominator). uint256 conversionRateDenominator; // Optional. If set, transfer amount is scaled by (conversionRateNumerator/conversionRateDenominator). } struct BridgeData { uint256[] accountNumbers; // Account number used to identify the owner's specific account. BridgeAction[] actions; // Actions to carry out on the owner's accounts. } } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.9; pragma experimental ABIEncoderV2; /// @title ERC-1155 Multi Token Standard /// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1155.md /// Note: The ERC-165 identifier for this interface is 0xd9b67a26. interface IERC1155 { /// @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, /// including zero value transfers as well as minting or burning. /// Operator will always be msg.sender. /// Either event from address `0x0` signifies a minting operation. /// An event to address `0x0` signifies a burning or melting operation. /// The total value transferred from address 0x0 minus the total value transferred to 0x0 may /// be used by clients and exchanges to be added to the "circulating supply" for a given token ID. /// To define a token ID with no initial balance, the contract SHOULD emit the TransferSingle event /// from `0x0` to `0x0`, with the token creator as `_operator`. event TransferSingle( address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value ); /// @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, /// including zero value transfers as well as minting or burning. ///Operator will always be msg.sender. /// Either event from address `0x0` signifies a minting operation. /// An event to address `0x0` signifies a burning or melting operation. /// The total value transferred from address 0x0 minus the total value transferred to 0x0 may /// be used by clients and exchanges to be added to the "circulating supply" for a given token ID. /// To define multiple token IDs with no initial balance, this SHOULD emit the TransferBatch event /// from `0x0` to `0x0`, with the token creator as `_operator`. event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /// @dev MUST emit when an approval is updated. event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); /// @dev MUST emit when the URI is updated for a token ID. /// URIs are defined in RFC 3986. /// The URI MUST point a JSON file that conforms to the "ERC-1155 Metadata JSON Schema". event URI( string value, uint256 indexed id ); /// @notice Transfers value amount of an _id from the _from address to the _to address specified. /// @dev MUST emit TransferSingle event on success. /// Caller must be approved to manage the _from account's tokens (see isApprovedForAll). /// MUST throw if `_to` is the zero address. /// MUST throw if balance of sender for token `_id` is lower than the `_value` sent. /// MUST throw on any other error. /// When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). /// If so, it MUST call `onERC1155Received` on `_to` and revert if the return value /// is not `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`. /// @param from Source address /// @param to Target address /// @param id ID of the token type /// @param value Transfer amount /// @param data Additional data with no specified format, sent in call to `_to` function safeTransferFrom( address from, address to, uint256 id, uint256 value, bytes calldata data ) external; /// @notice Send multiple types of Tokens from a 3rd party in one transfer (with safety call). /// @dev MUST emit TransferBatch event on success. /// Caller must be approved to manage the _from account's tokens (see isApprovedForAll). /// MUST throw if `_to` is the zero address. /// MUST throw if length of `_ids` is not the same as length of `_values`. /// MUST throw if any of the balance of sender for token `_ids` is lower than the respective `_values` sent. /// MUST throw on any other error. /// When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). /// If so, it MUST call `onERC1155BatchReceived` on `_to` and revert if the return value /// is not `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`. /// @param from Source addresses /// @param to Target addresses /// @param ids IDs of each token type /// @param values Transfer amounts per token type /// @param data Additional data with no specified format, sent in call to `_to` function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external; /// @notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens. /// @dev MUST emit the ApprovalForAll event on success. /// @param operator Address to add to the set of authorized operators /// @param approved True if the operator is approved, false to revoke approval function setApprovalForAll(address operator, bool approved) external; /// @notice Queries the approval status of an operator for a given owner. /// @param owner The owner of the Tokens /// @param operator Address of authorized operator /// @return True if the operator is approved, false if not function isApprovedForAll(address owner, address operator) external view returns (bool); /// @notice Get the balance of an account's Tokens. /// @param owner The address of the token holder /// @param id ID of the Token /// @return The _owner's balance of the Token type requested function balanceOf(address owner, uint256 id) external view returns (uint256); /// @notice Get the balance of multiple account/token pairs /// @param owners The addresses of the token holders /// @param ids ID of the Tokens /// @return The _owner's balance of the Token types requested function balanceOfBatch( address[] calldata owners, uint256[] calldata ids ) external view returns (uint256[] memory balances_); } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.9; import "@0x/contracts-utils/contracts/src/LibRichErrors.sol"; import "@0x/contracts-utils/contracts/src/LibBytes.sol"; import "../src/interfaces/IERC20Token.sol"; library LibERC20Token { bytes constant private DECIMALS_CALL_DATA = hex"313ce567"; /// @dev Calls `IERC20Token(token).approve()`. /// Reverts if `false` is returned or if the return /// data length is nonzero and not 32 bytes. /// @param token The address of the token contract. /// @param spender The address that receives an allowance. /// @param allowance The allowance to set. function approve( address token, address spender, uint256 allowance ) internal { bytes memory callData = abi.encodeWithSelector( IERC20Token(0).approve.selector, spender, allowance ); _callWithOptionalBooleanResult(token, callData); } /// @dev Calls `IERC20Token(token).approve()` and sets the allowance to the /// maximum if the current approval is not already >= an amount. /// Reverts if `false` is returned or if the return /// data length is nonzero and not 32 bytes. /// @param token The address of the token contract. /// @param spender The address that receives an allowance. /// @param amount The minimum allowance needed. function approveIfBelow( address token, address spender, uint256 amount ) internal { if (IERC20Token(token).allowance(address(this), spender) < amount) { approve(token, spender, uint256(-1)); } } /// @dev Calls `IERC20Token(token).transfer()`. /// Reverts if `false` is returned or if the return /// data length is nonzero and not 32 bytes. /// @param token The address of the token contract. /// @param to The address that receives the tokens /// @param amount Number of tokens to transfer. function transfer( address token, address to, uint256 amount ) internal { bytes memory callData = abi.encodeWithSelector( IERC20Token(0).transfer.selector, to, amount ); _callWithOptionalBooleanResult(token, callData); } /// @dev Calls `IERC20Token(token).transferFrom()`. /// Reverts if `false` is returned or if the return /// data length is nonzero and not 32 bytes. /// @param token The address of the token contract. /// @param from The owner of the tokens. /// @param to The address that receives the tokens /// @param amount Number of tokens to transfer. function transferFrom( address token, address from, address to, uint256 amount ) internal { bytes memory callData = abi.encodeWithSelector( IERC20Token(0).transferFrom.selector, from, to, amount ); _callWithOptionalBooleanResult(token, callData); } /// @dev Retrieves the number of decimals for a token. /// Returns `18` if the call reverts. /// @param token The address of the token contract. /// @return tokenDecimals The number of decimals places for the token. function decimals(address token) internal view returns (uint8 tokenDecimals) { tokenDecimals = 18; (bool didSucceed, bytes memory resultData) = token.staticcall(DECIMALS_CALL_DATA); if (didSucceed && resultData.length == 32) { tokenDecimals = uint8(LibBytes.readUint256(resultData, 0)); } } /// @dev Retrieves the allowance for a token, owner, and spender. /// Returns `0` if the call reverts. /// @param token The address of the token contract. /// @param owner The owner of the tokens. /// @param spender The address the spender. /// @return allowance The allowance for a token, owner, and spender. function allowance(address token, address owner, address spender) internal view returns (uint256 allowance_) { (bool didSucceed, bytes memory resultData) = token.staticcall( abi.encodeWithSelector( IERC20Token(0).allowance.selector, owner, spender ) ); if (didSucceed && resultData.length == 32) { allowance_ = LibBytes.readUint256(resultData, 0); } } /// @dev Retrieves the balance for a token owner. /// Returns `0` if the call reverts. /// @param token The address of the token contract. /// @param owner The owner of the tokens. /// @return balance The token balance of an owner. function balanceOf(address token, address owner) internal view returns (uint256 balance) { (bool didSucceed, bytes memory resultData) = token.staticcall( abi.encodeWithSelector( IERC20Token(0).balanceOf.selector, owner ) ); if (didSucceed && resultData.length == 32) { balance = LibBytes.readUint256(resultData, 0); } } /// @dev Executes a call on address `target` with calldata `callData` /// and asserts that either nothing was returned or a single boolean /// was returned equal to `true`. /// @param target The call target. /// @param callData The abi-encoded call data. function _callWithOptionalBooleanResult( address target, bytes memory callData ) private { (bool didSucceed, bytes memory resultData) = target.call(callData); if (didSucceed) { if (resultData.length == 0) { return; } if (resultData.length == 32) { uint256 result = LibBytes.readUint256(resultData, 0); if (result == 1) { return; } } } LibRichErrors.rrevert(resultData); } } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.9; contract IERC20Token { // solhint-disable no-simple-event-func-name event Transfer( address indexed _from, address indexed _to, uint256 _value ); event Approval( address indexed _owner, address indexed _spender, uint256 _value ); /// @dev 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 True if transfer was successful function transfer(address _to, uint256 _value) external returns (bool); /// @dev 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 True if transfer was successful function transferFrom( address _from, address _to, uint256 _value ) external returns (bool); /// @dev `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Always true if the call has enough gas to complete execution function approve(address _spender, uint256 _value) external returns (bool); /// @dev Query total supply of token /// @return Total supply of token function totalSupply() external view returns (uint256); /// @param _owner The address from which the balance will be retrieved /// @return Balance of owner function balanceOf(address _owner) external view returns (uint256); /// @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) external view returns (uint256); } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.9; contract IERC721Token { /// @dev This emits when ownership of any NFT changes by any mechanism. /// This event emits when NFTs are created (`from` == 0) and destroyed /// (`to` == 0). Exception: during contract creation, any number of NFTs /// may be created and assigned without emitting Transfer. At the time of /// any transfer, the approved address for that NFT (if any) is reset to none. event Transfer( address indexed _from, address indexed _to, uint256 indexed _tokenId ); /// @dev This emits when the approved address for an NFT is changed or /// reaffirmed. The zero address indicates there is no approved address. /// When a Transfer event emits, this also indicates that the approved /// address for that NFT (if any) is reset to none. event Approval( address indexed _owner, address indexed _approved, uint256 indexed _tokenId ); /// @dev This emits when an operator is enabled or disabled for an owner. /// The operator can manage all NFTs of the owner. event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); /// @notice Transfers the ownership of an NFT from one address to another address /// @dev Throws unless `msg.sender` is the current owner, an authorized /// perator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. When transfer is complete, this function /// checks if `_to` is a smart contract (code size > 0). If so, it calls /// `onERC721Received` on `_to` and throws if the return value is not /// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer /// @param _data Additional data with no specified format, sent in call to `_to` function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes calldata _data ) external; /// @notice Transfers the ownership of an NFT from one address to another address /// @dev This works identically to the other function with an extra data parameter, /// except this function just sets data to "". /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function safeTransferFrom( address _from, address _to, uint256 _tokenId ) external; /// @notice Change or reaffirm the approved address for an NFT /// @dev The zero address indicates there is no approved address. /// Throws unless `msg.sender` is the current NFT owner, or an authorized /// operator of the current owner. /// @param _approved The new approved NFT controller /// @param _tokenId The NFT to approve function approve(address _approved, uint256 _tokenId) external; /// @notice Enable or disable approval for a third party ("operator") to manage /// all of `msg.sender`'s assets /// @dev Emits the ApprovalForAll event. The contract MUST allow /// multiple operators per owner. /// @param _operator Address to add to the set of authorized operators /// @param _approved True if the operator is approved, false to revoke approval function setApprovalForAll(address _operator, bool _approved) external; /// @notice Count all NFTs assigned to an owner /// @dev NFTs assigned to the zero address are considered invalid, and this /// function throws for queries about the zero address. /// @param _owner An address for whom to query the balance /// @return The number of NFTs owned by `_owner`, possibly zero function balanceOf(address _owner) external view returns (uint256); /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE /// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE /// THEY MAY BE PERMANENTLY LOST /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function transferFrom( address _from, address _to, uint256 _tokenId ) public; /// @notice Find the owner of an NFT /// @dev NFTs assigned to zero address are considered invalid, and queries /// about them do throw. /// @param _tokenId The identifier for an NFT /// @return The address of the owner of the NFT function ownerOf(uint256 _tokenId) public view returns (address); /// @notice Get the approved address for a single NFT /// @dev Throws if `_tokenId` is not a valid NFT. /// @param _tokenId The NFT to find the approved address for /// @return The approved address for this NFT, or the zero address if there is none function getApproved(uint256 _tokenId) public view returns (address); /// @notice Query if an address is an authorized operator for another address /// @param _owner The address that owns the NFTs /// @param _operator The address that acts on behalf of the owner /// @return True if `_operator` is an approved operator for `_owner`, false otherwise function isApprovedForAll(address _owner, address _operator) public view returns (bool); } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.9; import "@0x/contracts-utils/contracts/src/LibEIP712.sol"; contract LibEIP712ExchangeDomain { // EIP712 Exchange Domain Name value string constant internal _EIP712_EXCHANGE_DOMAIN_NAME = "0x Protocol"; // EIP712 Exchange Domain Version value string constant internal _EIP712_EXCHANGE_DOMAIN_VERSION = "3.0.0"; // solhint-disable var-name-mixedcase /// @dev Hash of the EIP712 Domain Separator data /// @return 0 Domain hash. bytes32 public EIP712_EXCHANGE_DOMAIN_HASH; // solhint-enable var-name-mixedcase /// @param chainId Chain ID of the network this contract is deployed on. /// @param verifyingContractAddressIfExists Address of the verifying contract (null if the address of this contract) constructor ( uint256 chainId, address verifyingContractAddressIfExists ) public { address verifyingContractAddress = verifyingContractAddressIfExists == address(0) ? address(this) : verifyingContractAddressIfExists; EIP712_EXCHANGE_DOMAIN_HASH = LibEIP712.hashEIP712Domain( _EIP712_EXCHANGE_DOMAIN_NAME, _EIP712_EXCHANGE_DOMAIN_VERSION, chainId, verifyingContractAddress ); } } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.9; import "@0x/contracts-utils/contracts/src/LibRichErrors.sol"; import "./LibOrder.sol"; library LibExchangeRichErrors { enum AssetProxyDispatchErrorCodes { INVALID_ASSET_DATA_LENGTH, UNKNOWN_ASSET_PROXY } enum BatchMatchOrdersErrorCodes { ZERO_LEFT_ORDERS, ZERO_RIGHT_ORDERS, INVALID_LENGTH_LEFT_SIGNATURES, INVALID_LENGTH_RIGHT_SIGNATURES } enum ExchangeContextErrorCodes { INVALID_MAKER, INVALID_TAKER, INVALID_SENDER } enum FillErrorCodes { INVALID_TAKER_AMOUNT, TAKER_OVERPAY, OVERFILL, INVALID_FILL_PRICE } enum SignatureErrorCodes { BAD_ORDER_SIGNATURE, BAD_TRANSACTION_SIGNATURE, INVALID_LENGTH, UNSUPPORTED, ILLEGAL, INAPPROPRIATE_SIGNATURE_TYPE, INVALID_SIGNER } enum TransactionErrorCodes { ALREADY_EXECUTED, EXPIRED } enum IncompleteFillErrorCode { INCOMPLETE_MARKET_BUY_ORDERS, INCOMPLETE_MARKET_SELL_ORDERS, INCOMPLETE_FILL_ORDER } // bytes4(keccak256("SignatureError(uint8,bytes32,address,bytes)")) bytes4 internal constant SIGNATURE_ERROR_SELECTOR = 0x7e5a2318; // bytes4(keccak256("SignatureValidatorNotApprovedError(address,address)")) bytes4 internal constant SIGNATURE_VALIDATOR_NOT_APPROVED_ERROR_SELECTOR = 0xa15c0d06; // bytes4(keccak256("EIP1271SignatureError(address,bytes,bytes,bytes)")) bytes4 internal constant EIP1271_SIGNATURE_ERROR_SELECTOR = 0x5bd0428d; // bytes4(keccak256("SignatureWalletError(bytes32,address,bytes,bytes)")) bytes4 internal constant SIGNATURE_WALLET_ERROR_SELECTOR = 0x1b8388f7; // bytes4(keccak256("OrderStatusError(bytes32,uint8)")) bytes4 internal constant ORDER_STATUS_ERROR_SELECTOR = 0xfdb6ca8d; // bytes4(keccak256("ExchangeInvalidContextError(uint8,bytes32,address)")) bytes4 internal constant EXCHANGE_INVALID_CONTEXT_ERROR_SELECTOR = 0xe53c76c8; // bytes4(keccak256("FillError(uint8,bytes32)")) bytes4 internal constant FILL_ERROR_SELECTOR = 0xe94a7ed0; // bytes4(keccak256("OrderEpochError(address,address,uint256)")) bytes4 internal constant ORDER_EPOCH_ERROR_SELECTOR = 0x4ad31275; // bytes4(keccak256("AssetProxyExistsError(bytes4,address)")) bytes4 internal constant ASSET_PROXY_EXISTS_ERROR_SELECTOR = 0x11c7b720; // bytes4(keccak256("AssetProxyDispatchError(uint8,bytes32,bytes)")) bytes4 internal constant ASSET_PROXY_DISPATCH_ERROR_SELECTOR = 0x488219a6; // bytes4(keccak256("AssetProxyTransferError(bytes32,bytes,bytes)")) bytes4 internal constant ASSET_PROXY_TRANSFER_ERROR_SELECTOR = 0x4678472b; // bytes4(keccak256("NegativeSpreadError(bytes32,bytes32)")) bytes4 internal constant NEGATIVE_SPREAD_ERROR_SELECTOR = 0xb6555d6f; // bytes4(keccak256("TransactionError(uint8,bytes32)")) bytes4 internal constant TRANSACTION_ERROR_SELECTOR = 0xf5985184; // bytes4(keccak256("TransactionExecutionError(bytes32,bytes)")) bytes4 internal constant TRANSACTION_EXECUTION_ERROR_SELECTOR = 0x20d11f61; // bytes4(keccak256("TransactionGasPriceError(bytes32,uint256,uint256)")) bytes4 internal constant TRANSACTION_GAS_PRICE_ERROR_SELECTOR = 0xa26dac09; // bytes4(keccak256("TransactionInvalidContextError(bytes32,address)")) bytes4 internal constant TRANSACTION_INVALID_CONTEXT_ERROR_SELECTOR = 0xdec4aedf; // bytes4(keccak256("IncompleteFillError(uint8,uint256,uint256)")) bytes4 internal constant INCOMPLETE_FILL_ERROR_SELECTOR = 0x18e4b141; // bytes4(keccak256("BatchMatchOrdersError(uint8)")) bytes4 internal constant BATCH_MATCH_ORDERS_ERROR_SELECTOR = 0xd4092f4f; // bytes4(keccak256("PayProtocolFeeError(bytes32,uint256,address,address,bytes)")) bytes4 internal constant PAY_PROTOCOL_FEE_ERROR_SELECTOR = 0x87cb1e75; // solhint-disable func-name-mixedcase function SignatureErrorSelector() internal pure returns (bytes4) { return SIGNATURE_ERROR_SELECTOR; } function SignatureValidatorNotApprovedErrorSelector() internal pure returns (bytes4) { return SIGNATURE_VALIDATOR_NOT_APPROVED_ERROR_SELECTOR; } function EIP1271SignatureErrorSelector() internal pure returns (bytes4) { return EIP1271_SIGNATURE_ERROR_SELECTOR; } function SignatureWalletErrorSelector() internal pure returns (bytes4) { return SIGNATURE_WALLET_ERROR_SELECTOR; } function OrderStatusErrorSelector() internal pure returns (bytes4) { return ORDER_STATUS_ERROR_SELECTOR; } function ExchangeInvalidContextErrorSelector() internal pure returns (bytes4) { return EXCHANGE_INVALID_CONTEXT_ERROR_SELECTOR; } function FillErrorSelector() internal pure returns (bytes4) { return FILL_ERROR_SELECTOR; } function OrderEpochErrorSelector() internal pure returns (bytes4) { return ORDER_EPOCH_ERROR_SELECTOR; } function AssetProxyExistsErrorSelector() internal pure returns (bytes4) { return ASSET_PROXY_EXISTS_ERROR_SELECTOR; } function AssetProxyDispatchErrorSelector() internal pure returns (bytes4) { return ASSET_PROXY_DISPATCH_ERROR_SELECTOR; } function AssetProxyTransferErrorSelector() internal pure returns (bytes4) { return ASSET_PROXY_TRANSFER_ERROR_SELECTOR; } function NegativeSpreadErrorSelector() internal pure returns (bytes4) { return NEGATIVE_SPREAD_ERROR_SELECTOR; } function TransactionErrorSelector() internal pure returns (bytes4) { return TRANSACTION_ERROR_SELECTOR; } function TransactionExecutionErrorSelector() internal pure returns (bytes4) { return TRANSACTION_EXECUTION_ERROR_SELECTOR; } function IncompleteFillErrorSelector() internal pure returns (bytes4) { return INCOMPLETE_FILL_ERROR_SELECTOR; } function BatchMatchOrdersErrorSelector() internal pure returns (bytes4) { return BATCH_MATCH_ORDERS_ERROR_SELECTOR; } function TransactionGasPriceErrorSelector() internal pure returns (bytes4) { return TRANSACTION_GAS_PRICE_ERROR_SELECTOR; } function TransactionInvalidContextErrorSelector() internal pure returns (bytes4) { return TRANSACTION_INVALID_CONTEXT_ERROR_SELECTOR; } function PayProtocolFeeErrorSelector() internal pure returns (bytes4) { return PAY_PROTOCOL_FEE_ERROR_SELECTOR; } function BatchMatchOrdersError( BatchMatchOrdersErrorCodes errorCode ) internal pure returns (bytes memory) { return abi.encodeWithSelector( BATCH_MATCH_ORDERS_ERROR_SELECTOR, errorCode ); } function SignatureError( SignatureErrorCodes errorCode, bytes32 hash, address signerAddress, bytes memory signature ) internal pure returns (bytes memory) { return abi.encodeWithSelector( SIGNATURE_ERROR_SELECTOR, errorCode, hash, signerAddress, signature ); } function SignatureValidatorNotApprovedError( address signerAddress, address validatorAddress ) internal pure returns (bytes memory) { return abi.encodeWithSelector( SIGNATURE_VALIDATOR_NOT_APPROVED_ERROR_SELECTOR, signerAddress, validatorAddress ); } function EIP1271SignatureError( address verifyingContractAddress, bytes memory data, bytes memory signature, bytes memory errorData ) internal pure returns (bytes memory) { return abi.encodeWithSelector( EIP1271_SIGNATURE_ERROR_SELECTOR, verifyingContractAddress, data, signature, errorData ); } function SignatureWalletError( bytes32 hash, address walletAddress, bytes memory signature, bytes memory errorData ) internal pure returns (bytes memory) { return abi.encodeWithSelector( SIGNATURE_WALLET_ERROR_SELECTOR, hash, walletAddress, signature, errorData ); } function OrderStatusError( bytes32 orderHash, LibOrder.OrderStatus orderStatus ) internal pure returns (bytes memory) { return abi.encodeWithSelector( ORDER_STATUS_ERROR_SELECTOR, orderHash, orderStatus ); } function ExchangeInvalidContextError( ExchangeContextErrorCodes errorCode, bytes32 orderHash, address contextAddress ) internal pure returns (bytes memory) { return abi.encodeWithSelector( EXCHANGE_INVALID_CONTEXT_ERROR_SELECTOR, errorCode, orderHash, contextAddress ); } function FillError( FillErrorCodes errorCode, bytes32 orderHash ) internal pure returns (bytes memory) { return abi.encodeWithSelector( FILL_ERROR_SELECTOR, errorCode, orderHash ); } function OrderEpochError( address makerAddress, address orderSenderAddress, uint256 currentEpoch ) internal pure returns (bytes memory) { return abi.encodeWithSelector( ORDER_EPOCH_ERROR_SELECTOR, makerAddress, orderSenderAddress, currentEpoch ); } function AssetProxyExistsError( bytes4 assetProxyId, address assetProxyAddress ) internal pure returns (bytes memory) { return abi.encodeWithSelector( ASSET_PROXY_EXISTS_ERROR_SELECTOR, assetProxyId, assetProxyAddress ); } function AssetProxyDispatchError( AssetProxyDispatchErrorCodes errorCode, bytes32 orderHash, bytes memory assetData ) internal pure returns (bytes memory) { return abi.encodeWithSelector( ASSET_PROXY_DISPATCH_ERROR_SELECTOR, errorCode, orderHash, assetData ); } function AssetProxyTransferError( bytes32 orderHash, bytes memory assetData, bytes memory errorData ) internal pure returns (bytes memory) { return abi.encodeWithSelector( ASSET_PROXY_TRANSFER_ERROR_SELECTOR, orderHash, assetData, errorData ); } function NegativeSpreadError( bytes32 leftOrderHash, bytes32 rightOrderHash ) internal pure returns (bytes memory) { return abi.encodeWithSelector( NEGATIVE_SPREAD_ERROR_SELECTOR, leftOrderHash, rightOrderHash ); } function TransactionError( TransactionErrorCodes errorCode, bytes32 transactionHash ) internal pure returns (bytes memory) { return abi.encodeWithSelector( TRANSACTION_ERROR_SELECTOR, errorCode, transactionHash ); } function TransactionExecutionError( bytes32 transactionHash, bytes memory errorData ) internal pure returns (bytes memory) { return abi.encodeWithSelector( TRANSACTION_EXECUTION_ERROR_SELECTOR, transactionHash, errorData ); } function TransactionGasPriceError( bytes32 transactionHash, uint256 actualGasPrice, uint256 requiredGasPrice ) internal pure returns (bytes memory) { return abi.encodeWithSelector( TRANSACTION_GAS_PRICE_ERROR_SELECTOR, transactionHash, actualGasPrice, requiredGasPrice ); } function TransactionInvalidContextError( bytes32 transactionHash, address currentContextAddress ) internal pure returns (bytes memory) { return abi.encodeWithSelector( TRANSACTION_INVALID_CONTEXT_ERROR_SELECTOR, transactionHash, currentContextAddress ); } function IncompleteFillError( IncompleteFillErrorCode errorCode, uint256 expectedAssetFillAmount, uint256 actualAssetFillAmount ) internal pure returns (bytes memory) { return abi.encodeWithSelector( INCOMPLETE_FILL_ERROR_SELECTOR, errorCode, expectedAssetFillAmount, actualAssetFillAmount ); } function PayProtocolFeeError( bytes32 orderHash, uint256 protocolFee, address makerAddress, address takerAddress, bytes memory errorData ) internal pure returns (bytes memory) { return abi.encodeWithSelector( PAY_PROTOCOL_FEE_ERROR_SELECTOR, orderHash, protocolFee, makerAddress, takerAddress, errorData ); } } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.9; import "@0x/contracts-utils/contracts/src/LibSafeMath.sol"; import "./LibMath.sol"; import "./LibOrder.sol"; library LibFillResults { using LibSafeMath for uint256; struct BatchMatchedFillResults { FillResults[] left; // Fill results for left orders FillResults[] right; // Fill results for right orders uint256 profitInLeftMakerAsset; // Profit taken from left makers uint256 profitInRightMakerAsset; // Profit taken from right makers } struct FillResults { uint256 makerAssetFilledAmount; // Total amount of makerAsset(s) filled. uint256 takerAssetFilledAmount; // Total amount of takerAsset(s) filled. uint256 makerFeePaid; // Total amount of fees paid by maker(s) to feeRecipient(s). uint256 takerFeePaid; // Total amount of fees paid by taker to feeRecipients(s). uint256 protocolFeePaid; // Total amount of fees paid by taker to the staking contract. } struct MatchedFillResults { FillResults left; // Amounts filled and fees paid of left order. FillResults right; // Amounts filled and fees paid of right order. uint256 profitInLeftMakerAsset; // Profit taken from the left maker uint256 profitInRightMakerAsset; // Profit taken from the right maker } /// @dev Calculates amounts filled and fees paid by maker and taker. /// @param order to be filled. /// @param takerAssetFilledAmount Amount of takerAsset that will be filled. /// @param protocolFeeMultiplier The current protocol fee of the exchange contract. /// @param gasPrice The gasprice of the transaction. This is provided so that the function call can continue /// to be pure rather than view. /// @return fillResults Amounts filled and fees paid by maker and taker. function calculateFillResults( LibOrder.Order memory order, uint256 takerAssetFilledAmount, uint256 protocolFeeMultiplier, uint256 gasPrice ) internal pure returns (FillResults memory fillResults) { // Compute proportional transfer amounts fillResults.takerAssetFilledAmount = takerAssetFilledAmount; fillResults.makerAssetFilledAmount = LibMath.safeGetPartialAmountFloor( takerAssetFilledAmount, order.takerAssetAmount, order.makerAssetAmount ); fillResults.makerFeePaid = LibMath.safeGetPartialAmountFloor( takerAssetFilledAmount, order.takerAssetAmount, order.makerFee ); fillResults.takerFeePaid = LibMath.safeGetPartialAmountFloor( takerAssetFilledAmount, order.takerAssetAmount, order.takerFee ); // Compute the protocol fee that should be paid for a single fill. fillResults.protocolFeePaid = gasPrice.safeMul(protocolFeeMultiplier); return fillResults; } /// @dev Calculates fill amounts for the matched orders. /// Each order is filled at their respective price point. However, the calculations are /// carried out as though the orders are both being filled at the right order's price point. /// The profit made by the leftOrder order goes to the taker (who matched the two orders). /// @param leftOrder First order to match. /// @param rightOrder Second order to match. /// @param leftOrderTakerAssetFilledAmount Amount of left order already filled. /// @param rightOrderTakerAssetFilledAmount Amount of right order already filled. /// @param protocolFeeMultiplier The current protocol fee of the exchange contract. /// @param gasPrice The gasprice of the transaction. This is provided so that the function call can continue /// to be pure rather than view. /// @param shouldMaximallyFillOrders A value that indicates whether or not this calculation should use /// the maximal fill order matching strategy. /// @param matchedFillResults Amounts to fill and fees to pay by maker and taker of matched orders. function calculateMatchedFillResults( LibOrder.Order memory leftOrder, LibOrder.Order memory rightOrder, uint256 leftOrderTakerAssetFilledAmount, uint256 rightOrderTakerAssetFilledAmount, uint256 protocolFeeMultiplier, uint256 gasPrice, bool shouldMaximallyFillOrders ) internal pure returns (MatchedFillResults memory matchedFillResults) { // Derive maker asset amounts for left & right orders, given store taker assert amounts uint256 leftTakerAssetAmountRemaining = leftOrder.takerAssetAmount.safeSub(leftOrderTakerAssetFilledAmount); uint256 leftMakerAssetAmountRemaining = LibMath.safeGetPartialAmountFloor( leftOrder.makerAssetAmount, leftOrder.takerAssetAmount, leftTakerAssetAmountRemaining ); uint256 rightTakerAssetAmountRemaining = rightOrder.takerAssetAmount.safeSub(rightOrderTakerAssetFilledAmount); uint256 rightMakerAssetAmountRemaining = LibMath.safeGetPartialAmountFloor( rightOrder.makerAssetAmount, rightOrder.takerAssetAmount, rightTakerAssetAmountRemaining ); // Maximally fill the orders and pay out profits to the matcher in one or both of the maker assets. if (shouldMaximallyFillOrders) { matchedFillResults = _calculateMatchedFillResultsWithMaximalFill( leftOrder, rightOrder, leftMakerAssetAmountRemaining, leftTakerAssetAmountRemaining, rightMakerAssetAmountRemaining, rightTakerAssetAmountRemaining ); } else { matchedFillResults = _calculateMatchedFillResults( leftOrder, rightOrder, leftMakerAssetAmountRemaining, leftTakerAssetAmountRemaining, rightMakerAssetAmountRemaining, rightTakerAssetAmountRemaining ); } // Compute fees for left order matchedFillResults.left.makerFeePaid = LibMath.safeGetPartialAmountFloor( matchedFillResults.left.makerAssetFilledAmount, leftOrder.makerAssetAmount, leftOrder.makerFee ); matchedFillResults.left.takerFeePaid = LibMath.safeGetPartialAmountFloor( matchedFillResults.left.takerAssetFilledAmount, leftOrder.takerAssetAmount, leftOrder.takerFee ); // Compute fees for right order matchedFillResults.right.makerFeePaid = LibMath.safeGetPartialAmountFloor( matchedFillResults.right.makerAssetFilledAmount, rightOrder.makerAssetAmount, rightOrder.makerFee ); matchedFillResults.right.takerFeePaid = LibMath.safeGetPartialAmountFloor( matchedFillResults.right.takerAssetFilledAmount, rightOrder.takerAssetAmount, rightOrder.takerFee ); // Compute the protocol fee that should be paid for a single fill. In this // case this should be made the protocol fee for both the left and right orders. uint256 protocolFee = gasPrice.safeMul(protocolFeeMultiplier); matchedFillResults.left.protocolFeePaid = protocolFee; matchedFillResults.right.protocolFeePaid = protocolFee; // Return fill results return matchedFillResults; } /// @dev Adds properties of both FillResults instances. /// @param fillResults1 The first FillResults. /// @param fillResults2 The second FillResults. /// @return The sum of both fill results. function addFillResults( FillResults memory fillResults1, FillResults memory fillResults2 ) internal pure returns (FillResults memory totalFillResults) { totalFillResults.makerAssetFilledAmount = fillResults1.makerAssetFilledAmount.safeAdd(fillResults2.makerAssetFilledAmount); totalFillResults.takerAssetFilledAmount = fillResults1.takerAssetFilledAmount.safeAdd(fillResults2.takerAssetFilledAmount); totalFillResults.makerFeePaid = fillResults1.makerFeePaid.safeAdd(fillResults2.makerFeePaid); totalFillResults.takerFeePaid = fillResults1.takerFeePaid.safeAdd(fillResults2.takerFeePaid); totalFillResults.protocolFeePaid = fillResults1.protocolFeePaid.safeAdd(fillResults2.protocolFeePaid); return totalFillResults; } /// @dev Calculates part of the matched fill results for a given situation using the fill strategy that only /// awards profit denominated in the left maker asset. /// @param leftOrder The left order in the order matching situation. /// @param rightOrder The right order in the order matching situation. /// @param leftMakerAssetAmountRemaining The amount of the left order maker asset that can still be filled. /// @param leftTakerAssetAmountRemaining The amount of the left order taker asset that can still be filled. /// @param rightMakerAssetAmountRemaining The amount of the right order maker asset that can still be filled. /// @param rightTakerAssetAmountRemaining The amount of the right order taker asset that can still be filled. /// @return MatchFillResults struct that does not include fees paid. function _calculateMatchedFillResults( LibOrder.Order memory leftOrder, LibOrder.Order memory rightOrder, uint256 leftMakerAssetAmountRemaining, uint256 leftTakerAssetAmountRemaining, uint256 rightMakerAssetAmountRemaining, uint256 rightTakerAssetAmountRemaining ) private pure returns (MatchedFillResults memory matchedFillResults) { // Calculate fill results for maker and taker assets: at least one order will be fully filled. // The maximum amount the left maker can buy is `leftTakerAssetAmountRemaining` // The maximum amount the right maker can sell is `rightMakerAssetAmountRemaining` // We have two distinct cases for calculating the fill results: // Case 1. // If the left maker can buy more than the right maker can sell, then only the right order is fully filled. // If the left maker can buy exactly what the right maker can sell, then both orders are fully filled. // Case 2. // If the left maker cannot buy more than the right maker can sell, then only the left order is fully filled. // Case 3. // If the left maker can buy exactly as much as the right maker can sell, then both orders are fully filled. if (leftTakerAssetAmountRemaining > rightMakerAssetAmountRemaining) { // Case 1: Right order is fully filled matchedFillResults = _calculateCompleteRightFill( leftOrder, rightMakerAssetAmountRemaining, rightTakerAssetAmountRemaining ); } else if (leftTakerAssetAmountRemaining < rightMakerAssetAmountRemaining) { // Case 2: Left order is fully filled matchedFillResults.left.makerAssetFilledAmount = leftMakerAssetAmountRemaining; matchedFillResults.left.takerAssetFilledAmount = leftTakerAssetAmountRemaining; matchedFillResults.right.makerAssetFilledAmount = leftTakerAssetAmountRemaining; // Round up to ensure the maker's exchange rate does not exceed the price specified by the order. // We favor the maker when the exchange rate must be rounded. matchedFillResults.right.takerAssetFilledAmount = LibMath.safeGetPartialAmountCeil( rightOrder.takerAssetAmount, rightOrder.makerAssetAmount, leftTakerAssetAmountRemaining // matchedFillResults.right.makerAssetFilledAmount ); } else { // leftTakerAssetAmountRemaining == rightMakerAssetAmountRemaining // Case 3: Both orders are fully filled. Technically, this could be captured by the above cases, but // this calculation will be more precise since it does not include rounding. matchedFillResults = _calculateCompleteFillBoth( leftMakerAssetAmountRemaining, leftTakerAssetAmountRemaining, rightMakerAssetAmountRemaining, rightTakerAssetAmountRemaining ); } // Calculate amount given to taker matchedFillResults.profitInLeftMakerAsset = matchedFillResults.left.makerAssetFilledAmount.safeSub( matchedFillResults.right.takerAssetFilledAmount ); return matchedFillResults; } /// @dev Calculates part of the matched fill results for a given situation using the maximal fill order matching /// strategy. /// @param leftOrder The left order in the order matching situation. /// @param rightOrder The right order in the order matching situation. /// @param leftMakerAssetAmountRemaining The amount of the left order maker asset that can still be filled. /// @param leftTakerAssetAmountRemaining The amount of the left order taker asset that can still be filled. /// @param rightMakerAssetAmountRemaining The amount of the right order maker asset that can still be filled. /// @param rightTakerAssetAmountRemaining The amount of the right order taker asset that can still be filled. /// @return MatchFillResults struct that does not include fees paid. function _calculateMatchedFillResultsWithMaximalFill( LibOrder.Order memory leftOrder, LibOrder.Order memory rightOrder, uint256 leftMakerAssetAmountRemaining, uint256 leftTakerAssetAmountRemaining, uint256 rightMakerAssetAmountRemaining, uint256 rightTakerAssetAmountRemaining ) private pure returns (MatchedFillResults memory matchedFillResults) { // If a maker asset is greater than the opposite taker asset, than there will be a spread denominated in that maker asset. bool doesLeftMakerAssetProfitExist = leftMakerAssetAmountRemaining > rightTakerAssetAmountRemaining; bool doesRightMakerAssetProfitExist = rightMakerAssetAmountRemaining > leftTakerAssetAmountRemaining; // Calculate the maximum fill results for the maker and taker assets. At least one of the orders will be fully filled. // // The maximum that the left maker can possibly buy is the amount that the right order can sell. // The maximum that the right maker can possibly buy is the amount that the left order can sell. // // If the left order is fully filled, profit will be paid out in the left maker asset. If the right order is fully filled, // the profit will be out in the right maker asset. // // There are three cases to consider: // Case 1. // If the left maker can buy more than the right maker can sell, then only the right order is fully filled. // Case 2. // If the right maker can buy more than the left maker can sell, then only the right order is fully filled. // Case 3. // If the right maker can sell the max of what the left maker can buy and the left maker can sell the max of // what the right maker can buy, then both orders are fully filled. if (leftTakerAssetAmountRemaining > rightMakerAssetAmountRemaining) { // Case 1: Right order is fully filled with the profit paid in the left makerAsset matchedFillResults = _calculateCompleteRightFill( leftOrder, rightMakerAssetAmountRemaining, rightTakerAssetAmountRemaining ); } else if (rightTakerAssetAmountRemaining > leftMakerAssetAmountRemaining) { // Case 2: Left order is fully filled with the profit paid in the right makerAsset. matchedFillResults.left.makerAssetFilledAmount = leftMakerAssetAmountRemaining; matchedFillResults.left.takerAssetFilledAmount = leftTakerAssetAmountRemaining; // Round down to ensure the right maker's exchange rate does not exceed the price specified by the order. // We favor the right maker when the exchange rate must be rounded and the profit is being paid in the // right maker asset. matchedFillResults.right.makerAssetFilledAmount = LibMath.safeGetPartialAmountFloor( rightOrder.makerAssetAmount, rightOrder.takerAssetAmount, leftMakerAssetAmountRemaining ); matchedFillResults.right.takerAssetFilledAmount = leftMakerAssetAmountRemaining; } else { // Case 3: The right and left orders are fully filled matchedFillResults = _calculateCompleteFillBoth( leftMakerAssetAmountRemaining, leftTakerAssetAmountRemaining, rightMakerAssetAmountRemaining, rightTakerAssetAmountRemaining ); } // Calculate amount given to taker in the left order's maker asset if the left spread will be part of the profit. if (doesLeftMakerAssetProfitExist) { matchedFillResults.profitInLeftMakerAsset = matchedFillResults.left.makerAssetFilledAmount.safeSub( matchedFillResults.right.takerAssetFilledAmount ); } // Calculate amount given to taker in the right order's maker asset if the right spread will be part of the profit. if (doesRightMakerAssetProfitExist) { matchedFillResults.profitInRightMakerAsset = matchedFillResults.right.makerAssetFilledAmount.safeSub( matchedFillResults.left.takerAssetFilledAmount ); } return matchedFillResults; } /// @dev Calculates the fill results for the maker and taker in the order matching and writes the results /// to the fillResults that are being collected on the order. Both orders will be fully filled in this /// case. /// @param leftMakerAssetAmountRemaining The amount of the left maker asset that is remaining to be filled. /// @param leftTakerAssetAmountRemaining The amount of the left taker asset that is remaining to be filled. /// @param rightMakerAssetAmountRemaining The amount of the right maker asset that is remaining to be filled. /// @param rightTakerAssetAmountRemaining The amount of the right taker asset that is remaining to be filled. /// @return MatchFillResults struct that does not include fees paid or spreads taken. function _calculateCompleteFillBoth( uint256 leftMakerAssetAmountRemaining, uint256 leftTakerAssetAmountRemaining, uint256 rightMakerAssetAmountRemaining, uint256 rightTakerAssetAmountRemaining ) private pure returns (MatchedFillResults memory matchedFillResults) { // Calculate the fully filled results for both orders. matchedFillResults.left.makerAssetFilledAmount = leftMakerAssetAmountRemaining; matchedFillResults.left.takerAssetFilledAmount = leftTakerAssetAmountRemaining; matchedFillResults.right.makerAssetFilledAmount = rightMakerAssetAmountRemaining; matchedFillResults.right.takerAssetFilledAmount = rightTakerAssetAmountRemaining; return matchedFillResults; } /// @dev Calculates the fill results for the maker and taker in the order matching and writes the results /// to the fillResults that are being collected on the order. /// @param leftOrder The left order that is being maximally filled. All of the information about fill amounts /// can be derived from this order and the right asset remaining fields. /// @param rightMakerAssetAmountRemaining The amount of the right maker asset that is remaining to be filled. /// @param rightTakerAssetAmountRemaining The amount of the right taker asset that is remaining to be filled. /// @return MatchFillResults struct that does not include fees paid or spreads taken. function _calculateCompleteRightFill( LibOrder.Order memory leftOrder, uint256 rightMakerAssetAmountRemaining, uint256 rightTakerAssetAmountRemaining ) private pure returns (MatchedFillResults memory matchedFillResults) { matchedFillResults.right.makerAssetFilledAmount = rightMakerAssetAmountRemaining; matchedFillResults.right.takerAssetFilledAmount = rightTakerAssetAmountRemaining; matchedFillResults.left.takerAssetFilledAmount = rightMakerAssetAmountRemaining; // Round down to ensure the left maker's exchange rate does not exceed the price specified by the order. // We favor the left maker when the exchange rate must be rounded and the profit is being paid in the // left maker asset. matchedFillResults.left.makerAssetFilledAmount = LibMath.safeGetPartialAmountFloor( leftOrder.makerAssetAmount, leftOrder.takerAssetAmount, rightMakerAssetAmountRemaining ); return matchedFillResults; } } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.9; import "@0x/contracts-utils/contracts/src/LibSafeMath.sol"; import "@0x/contracts-utils/contracts/src/LibRichErrors.sol"; import "./LibMathRichErrors.sol"; library LibMath { using LibSafeMath for uint256; /// @dev Calculates partial value given a numerator and denominator rounded down. /// Reverts if rounding error is >= 0.1% /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to calculate partial of. /// @return Partial value of target rounded down. function safeGetPartialAmountFloor( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256 partialAmount) { if (isRoundingErrorFloor( numerator, denominator, target )) { LibRichErrors.rrevert(LibMathRichErrors.RoundingError( numerator, denominator, target )); } partialAmount = numerator.safeMul(target).safeDiv(denominator); return partialAmount; } /// @dev Calculates partial value given a numerator and denominator rounded down. /// Reverts if rounding error is >= 0.1% /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to calculate partial of. /// @return Partial value of target rounded up. function safeGetPartialAmountCeil( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256 partialAmount) { if (isRoundingErrorCeil( numerator, denominator, target )) { LibRichErrors.rrevert(LibMathRichErrors.RoundingError( numerator, denominator, target )); } // safeDiv computes `floor(a / b)`. We use the identity (a, b integer): // ceil(a / b) = floor((a + b - 1) / b) // To implement `ceil(a / b)` using safeDiv. partialAmount = numerator.safeMul(target) .safeAdd(denominator.safeSub(1)) .safeDiv(denominator); return partialAmount; } /// @dev Calculates partial value given a numerator and denominator rounded down. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to calculate partial of. /// @return Partial value of target rounded down. function getPartialAmountFloor( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256 partialAmount) { partialAmount = numerator.safeMul(target).safeDiv(denominator); return partialAmount; } /// @dev Calculates partial value given a numerator and denominator rounded down. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to calculate partial of. /// @return Partial value of target rounded up. function getPartialAmountCeil( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256 partialAmount) { // safeDiv computes `floor(a / b)`. We use the identity (a, b integer): // ceil(a / b) = floor((a + b - 1) / b) // To implement `ceil(a / b)` using safeDiv. partialAmount = numerator.safeMul(target) .safeAdd(denominator.safeSub(1)) .safeDiv(denominator); return partialAmount; } /// @dev Checks if rounding error >= 0.1% when rounding down. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to multiply with numerator/denominator. /// @return Rounding error is present. function isRoundingErrorFloor( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (bool isError) { if (denominator == 0) { LibRichErrors.rrevert(LibMathRichErrors.DivisionByZeroError()); } // The absolute rounding error is the difference between the rounded // value and the ideal value. The relative rounding error is the // absolute rounding error divided by the absolute value of the // ideal value. This is undefined when the ideal value is zero. // // The ideal value is `numerator * target / denominator`. // Let's call `numerator * target % denominator` the remainder. // The absolute error is `remainder / denominator`. // // When the ideal value is zero, we require the absolute error to // be zero. Fortunately, this is always the case. The ideal value is // zero iff `numerator == 0` and/or `target == 0`. In this case the // remainder and absolute error are also zero. if (target == 0 || numerator == 0) { return false; } // Otherwise, we want the relative rounding error to be strictly // less than 0.1%. // The relative error is `remainder / (numerator * target)`. // We want the relative error less than 1 / 1000: // remainder / (numerator * denominator) < 1 / 1000 // or equivalently: // 1000 * remainder < numerator * target // so we have a rounding error iff: // 1000 * remainder >= numerator * target uint256 remainder = mulmod( target, numerator, denominator ); isError = remainder.safeMul(1000) >= numerator.safeMul(target); return isError; } /// @dev Checks if rounding error >= 0.1% when rounding up. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to multiply with numerator/denominator. /// @return Rounding error is present. function isRoundingErrorCeil( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (bool isError) { if (denominator == 0) { LibRichErrors.rrevert(LibMathRichErrors.DivisionByZeroError()); } // See the comments in `isRoundingError`. if (target == 0 || numerator == 0) { // When either is zero, the ideal value and rounded value are zero // and there is no rounding error. (Although the relative error // is undefined.) return false; } // Compute remainder as before uint256 remainder = mulmod( target, numerator, denominator ); remainder = denominator.safeSub(remainder) % denominator; isError = remainder.safeMul(1000) >= numerator.safeMul(target); return isError; } } pragma solidity ^0.5.9; library LibMathRichErrors { // bytes4(keccak256("DivisionByZeroError()")) bytes internal constant DIVISION_BY_ZERO_ERROR = hex"a791837c"; // bytes4(keccak256("RoundingError(uint256,uint256,uint256)")) bytes4 internal constant ROUNDING_ERROR_SELECTOR = 0x339f3de2; // solhint-disable func-name-mixedcase function DivisionByZeroError() internal pure returns (bytes memory) { return DIVISION_BY_ZERO_ERROR; } function RoundingError( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (bytes memory) { return abi.encodeWithSelector( ROUNDING_ERROR_SELECTOR, numerator, denominator, target ); } } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.9; import "@0x/contracts-utils/contracts/src/LibEIP712.sol"; library LibOrder { using LibOrder for Order; // Hash for the EIP712 Order Schema: // keccak256(abi.encodePacked( // "Order(", // "address makerAddress,", // "address takerAddress,", // "address feeRecipientAddress,", // "address senderAddress,", // "uint256 makerAssetAmount,", // "uint256 takerAssetAmount,", // "uint256 makerFee,", // "uint256 takerFee,", // "uint256 expirationTimeSeconds,", // "uint256 salt,", // "bytes makerAssetData,", // "bytes takerAssetData,", // "bytes makerFeeAssetData,", // "bytes takerFeeAssetData", // ")" // )) bytes32 constant internal _EIP712_ORDER_SCHEMA_HASH = 0xf80322eb8376aafb64eadf8f0d7623f22130fd9491a221e902b713cb984a7534; // A valid order remains fillable until it is expired, fully filled, or cancelled. // An order's status is unaffected by external factors, like account balances. enum OrderStatus { INVALID, // Default value INVALID_MAKER_ASSET_AMOUNT, // Order does not have a valid maker asset amount INVALID_TAKER_ASSET_AMOUNT, // Order does not have a valid taker asset amount FILLABLE, // Order is fillable EXPIRED, // Order has already expired FULLY_FILLED, // Order is fully filled CANCELLED // Order has been cancelled } // solhint-disable max-line-length /// @dev Canonical order structure. struct Order { address makerAddress; // Address that created the order. address takerAddress; // Address that is allowed to fill the order. If set to 0, any address is allowed to fill the order. address feeRecipientAddress; // Address that will recieve fees when order is filled. address senderAddress; // Address that is allowed to call Exchange contract methods that affect this order. If set to 0, any address is allowed to call these methods. uint256 makerAssetAmount; // Amount of makerAsset being offered by maker. Must be greater than 0. uint256 takerAssetAmount; // Amount of takerAsset being bid on by maker. Must be greater than 0. uint256 makerFee; // Fee paid to feeRecipient by maker when order is filled. uint256 takerFee; // Fee paid to feeRecipient by taker when order is filled. uint256 expirationTimeSeconds; // Timestamp in seconds at which order expires. uint256 salt; // Arbitrary number to facilitate uniqueness of the order's hash. bytes makerAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring makerAsset. The leading bytes4 references the id of the asset proxy. bytes takerAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring takerAsset. The leading bytes4 references the id of the asset proxy. bytes makerFeeAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring makerFeeAsset. The leading bytes4 references the id of the asset proxy. bytes takerFeeAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring takerFeeAsset. The leading bytes4 references the id of the asset proxy. } // solhint-enable max-line-length /// @dev Order information returned by `getOrderInfo()`. struct OrderInfo { OrderStatus orderStatus; // Status that describes order's validity and fillability. bytes32 orderHash; // EIP712 typed data hash of the order (see LibOrder.getTypedDataHash). uint256 orderTakerAssetFilledAmount; // Amount of order that has already been filled. } /// @dev Calculates the EIP712 typed data hash of an order with a given domain separator. /// @param order The order structure. /// @return EIP712 typed data hash of the order. function getTypedDataHash(Order memory order, bytes32 eip712ExchangeDomainHash) internal pure returns (bytes32 orderHash) { orderHash = LibEIP712.hashEIP712Message( eip712ExchangeDomainHash, order.getStructHash() ); return orderHash; } /// @dev Calculates EIP712 hash of the order struct. /// @param order The order structure. /// @return EIP712 hash of the order struct. function getStructHash(Order memory order) internal pure returns (bytes32 result) { bytes32 schemaHash = _EIP712_ORDER_SCHEMA_HASH; bytes memory makerAssetData = order.makerAssetData; bytes memory takerAssetData = order.takerAssetData; bytes memory makerFeeAssetData = order.makerFeeAssetData; bytes memory takerFeeAssetData = order.takerFeeAssetData; // Assembly for more efficiently computing: // keccak256(abi.encodePacked( // EIP712_ORDER_SCHEMA_HASH, // uint256(order.makerAddress), // uint256(order.takerAddress), // uint256(order.feeRecipientAddress), // uint256(order.senderAddress), // order.makerAssetAmount, // order.takerAssetAmount, // order.makerFee, // order.takerFee, // order.expirationTimeSeconds, // order.salt, // keccak256(order.makerAssetData), // keccak256(order.takerAssetData), // keccak256(order.makerFeeAssetData), // keccak256(order.takerFeeAssetData) // )); assembly { // Assert order offset (this is an internal error that should never be triggered) if lt(order, 32) { invalid() } // Calculate memory addresses that will be swapped out before hashing let pos1 := sub(order, 32) let pos2 := add(order, 320) let pos3 := add(order, 352) let pos4 := add(order, 384) let pos5 := add(order, 416) // Backup let temp1 := mload(pos1) let temp2 := mload(pos2) let temp3 := mload(pos3) let temp4 := mload(pos4) let temp5 := mload(pos5) // Hash in place mstore(pos1, schemaHash) mstore(pos2, keccak256(add(makerAssetData, 32), mload(makerAssetData))) // store hash of makerAssetData mstore(pos3, keccak256(add(takerAssetData, 32), mload(takerAssetData))) // store hash of takerAssetData mstore(pos4, keccak256(add(makerFeeAssetData, 32), mload(makerFeeAssetData))) // store hash of makerFeeAssetData mstore(pos5, keccak256(add(takerFeeAssetData, 32), mload(takerFeeAssetData))) // store hash of takerFeeAssetData result := keccak256(pos1, 480) // Restore mstore(pos1, temp1) mstore(pos2, temp2) mstore(pos3, temp3) mstore(pos4, temp4) mstore(pos5, temp5) } return result; } } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.9; pragma experimental ABIEncoderV2; import "@0x/contracts-utils/contracts/src/LibEIP712.sol"; library LibZeroExTransaction { using LibZeroExTransaction for ZeroExTransaction; // Hash for the EIP712 0x transaction schema // keccak256(abi.encodePacked( // "ZeroExTransaction(", // "uint256 salt,", // "uint256 expirationTimeSeconds,", // "uint256 gasPrice,", // "address signerAddress,", // "bytes data", // ")" // )); bytes32 constant internal _EIP712_ZEROEX_TRANSACTION_SCHEMA_HASH = 0xec69816980a3a3ca4554410e60253953e9ff375ba4536a98adfa15cc71541508; struct ZeroExTransaction { uint256 salt; // Arbitrary number to ensure uniqueness of transaction hash. uint256 expirationTimeSeconds; // Timestamp in seconds at which transaction expires. uint256 gasPrice; // gasPrice that transaction is required to be executed with. address signerAddress; // Address of transaction signer. bytes data; // AbiV2 encoded calldata. } /// @dev Calculates the EIP712 typed data hash of a transaction with a given domain separator. /// @param transaction 0x transaction structure. /// @return EIP712 typed data hash of the transaction. function getTypedDataHash(ZeroExTransaction memory transaction, bytes32 eip712ExchangeDomainHash) internal pure returns (bytes32 transactionHash) { // Hash the transaction with the domain separator of the Exchange contract. transactionHash = LibEIP712.hashEIP712Message( eip712ExchangeDomainHash, transaction.getStructHash() ); return transactionHash; } /// @dev Calculates EIP712 hash of the 0x transaction struct. /// @param transaction 0x transaction structure. /// @return EIP712 hash of the transaction struct. function getStructHash(ZeroExTransaction memory transaction) internal pure returns (bytes32 result) { bytes32 schemaHash = _EIP712_ZEROEX_TRANSACTION_SCHEMA_HASH; bytes memory data = transaction.data; uint256 salt = transaction.salt; uint256 expirationTimeSeconds = transaction.expirationTimeSeconds; uint256 gasPrice = transaction.gasPrice; address signerAddress = transaction.signerAddress; // Assembly for more efficiently computing: // result = keccak256(abi.encodePacked( // schemaHash, // salt, // expirationTimeSeconds, // gasPrice, // uint256(signerAddress), // keccak256(data) // )); assembly { // Compute hash of data let dataHash := keccak256(add(data, 32), mload(data)) // Load free memory pointer let memPtr := mload(64) mstore(memPtr, schemaHash) // hash of schema mstore(add(memPtr, 32), salt) // salt mstore(add(memPtr, 64), expirationTimeSeconds) // expirationTimeSeconds mstore(add(memPtr, 96), gasPrice) // gasPrice mstore(add(memPtr, 128), and(signerAddress, 0xffffffffffffffffffffffffffffffffffffffff)) // signerAddress mstore(add(memPtr, 160), dataHash) // hash of data // Compute hash result := keccak256(memPtr, 192) } return result; } } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.9; contract IAssetProxyDispatcher { // Logs registration of new asset proxy event AssetProxyRegistered( bytes4 id, // Id of new registered AssetProxy. address assetProxy // Address of new registered AssetProxy. ); /// @dev Registers an asset proxy to its asset proxy id. /// Once an asset proxy is registered, it cannot be unregistered. /// @param assetProxy Address of new asset proxy to register. function registerAssetProxy(address assetProxy) external; /// @dev Gets an asset proxy. /// @param assetProxyId Id of the asset proxy. /// @return The asset proxy registered to assetProxyId. Returns 0x0 if no proxy is registered. function getAssetProxy(bytes4 assetProxyId) external view returns (address); } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.9; pragma experimental ABIEncoderV2; import "./IExchangeCore.sol"; import "./IProtocolFees.sol"; import "./IMatchOrders.sol"; import "./ISignatureValidator.sol"; import "./ITransactions.sol"; import "./IAssetProxyDispatcher.sol"; import "./IWrapperFunctions.sol"; import "./ITransferSimulator.sol"; // solhint-disable no-empty-blocks contract IExchange is IProtocolFees, IExchangeCore, IMatchOrders, ISignatureValidator, ITransactions, IAssetProxyDispatcher, ITransferSimulator, IWrapperFunctions {} /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.9; pragma experimental ABIEncoderV2; import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol"; import "@0x/contracts-exchange-libs/contracts/src/LibFillResults.sol"; contract IExchangeCore { // Fill event is emitted whenever an order is filled. event Fill( address indexed makerAddress, // Address that created the order. address indexed feeRecipientAddress, // Address that received fees. bytes makerAssetData, // Encoded data specific to makerAsset. bytes takerAssetData, // Encoded data specific to takerAsset. bytes makerFeeAssetData, // Encoded data specific to makerFeeAsset. bytes takerFeeAssetData, // Encoded data specific to takerFeeAsset. bytes32 indexed orderHash, // EIP712 hash of order (see LibOrder.getTypedDataHash). address takerAddress, // Address that filled the order. address senderAddress, // Address that called the Exchange contract (msg.sender). uint256 makerAssetFilledAmount, // Amount of makerAsset sold by maker and bought by taker. uint256 takerAssetFilledAmount, // Amount of takerAsset sold by taker and bought by maker. uint256 makerFeePaid, // Amount of makerFeeAssetData paid to feeRecipient by maker. uint256 takerFeePaid, // Amount of takerFeeAssetData paid to feeRecipient by taker. uint256 protocolFeePaid // Amount of eth or weth paid to the staking contract. ); // Cancel event is emitted whenever an individual order is cancelled. event Cancel( address indexed makerAddress, // Address that created the order. address indexed feeRecipientAddress, // Address that would have recieved fees if order was filled. bytes makerAssetData, // Encoded data specific to makerAsset. bytes takerAssetData, // Encoded data specific to takerAsset. address senderAddress, // Address that called the Exchange contract (msg.sender). bytes32 indexed orderHash // EIP712 hash of order (see LibOrder.getTypedDataHash). ); // CancelUpTo event is emitted whenever `cancelOrdersUpTo` is executed succesfully. event CancelUpTo( address indexed makerAddress, // Orders cancelled must have been created by this address. address indexed orderSenderAddress, // Orders cancelled must have a `senderAddress` equal to this address. uint256 orderEpoch // Orders with specified makerAddress and senderAddress with a salt less than this value are considered cancelled. ); /// @dev Cancels all orders created by makerAddress with a salt less than or equal to the targetOrderEpoch /// and senderAddress equal to msg.sender (or null address if msg.sender == makerAddress). /// @param targetOrderEpoch Orders created with a salt less or equal to this value will be cancelled. function cancelOrdersUpTo(uint256 targetOrderEpoch) external payable; /// @dev Fills the input order. /// @param order Order struct containing order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param signature Proof that order has been created by maker. /// @return Amounts filled and fees paid by maker and taker. function fillOrder( LibOrder.Order memory order, uint256 takerAssetFillAmount, bytes memory signature ) public payable returns (LibFillResults.FillResults memory fillResults); /// @dev After calling, the order can not be filled anymore. /// @param order Order struct containing order specifications. function cancelOrder(LibOrder.Order memory order) public payable; /// @dev Gets information about an order: status, hash, and amount filled. /// @param order Order to gather information on. /// @return OrderInfo Information about the order and its state. /// See LibOrder.OrderInfo for a complete description. function getOrderInfo(LibOrder.Order memory order) public view returns (LibOrder.OrderInfo memory orderInfo); } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.9; pragma experimental ABIEncoderV2; import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol"; import "@0x/contracts-exchange-libs/contracts/src/LibFillResults.sol"; contract IMatchOrders { /// @dev Match complementary orders that have a profitable spread. /// Each order is filled at their respective price point, and /// the matcher receives a profit denominated in the left maker asset. /// @param leftOrders Set of orders with the same maker / taker asset. /// @param rightOrders Set of orders to match against `leftOrders` /// @param leftSignatures Proof that left orders were created by the left makers. /// @param rightSignatures Proof that right orders were created by the right makers. /// @return batchMatchedFillResults Amounts filled and profit generated. function batchMatchOrders( LibOrder.Order[] memory leftOrders, LibOrder.Order[] memory rightOrders, bytes[] memory leftSignatures, bytes[] memory rightSignatures ) public payable returns (LibFillResults.BatchMatchedFillResults memory batchMatchedFillResults); /// @dev Match complementary orders that have a profitable spread. /// Each order is maximally filled at their respective price point, and /// the matcher receives a profit denominated in either the left maker asset, /// right maker asset, or a combination of both. /// @param leftOrders Set of orders with the same maker / taker asset. /// @param rightOrders Set of orders to match against `leftOrders` /// @param leftSignatures Proof that left orders were created by the left makers. /// @param rightSignatures Proof that right orders were created by the right makers. /// @return batchMatchedFillResults Amounts filled and profit generated. function batchMatchOrdersWithMaximalFill( LibOrder.Order[] memory leftOrders, LibOrder.Order[] memory rightOrders, bytes[] memory leftSignatures, bytes[] memory rightSignatures ) public payable returns (LibFillResults.BatchMatchedFillResults memory batchMatchedFillResults); /// @dev Match two complementary orders that have a profitable spread. /// Each order is filled at their respective price point. However, the calculations are /// carried out as though the orders are both being filled at the right order's price point. /// The profit made by the left order goes to the taker (who matched the two orders). /// @param leftOrder First order to match. /// @param rightOrder Second order to match. /// @param leftSignature Proof that order was created by the left maker. /// @param rightSignature Proof that order was created by the right maker. /// @return matchedFillResults Amounts filled and fees paid by maker and taker of matched orders. function matchOrders( LibOrder.Order memory leftOrder, LibOrder.Order memory rightOrder, bytes memory leftSignature, bytes memory rightSignature ) public payable returns (LibFillResults.MatchedFillResults memory matchedFillResults); /// @dev Match two complementary orders that have a profitable spread. /// Each order is maximally filled at their respective price point, and /// the matcher receives a profit denominated in either the left maker asset, /// right maker asset, or a combination of both. /// @param leftOrder First order to match. /// @param rightOrder Second order to match. /// @param leftSignature Proof that order was created by the left maker. /// @param rightSignature Proof that order was created by the right maker. /// @return matchedFillResults Amounts filled by maker and taker of matched orders. function matchOrdersWithMaximalFill( LibOrder.Order memory leftOrder, LibOrder.Order memory rightOrder, bytes memory leftSignature, bytes memory rightSignature ) public payable returns (LibFillResults.MatchedFillResults memory matchedFillResults); } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.9; contract IProtocolFees { // Logs updates to the protocol fee multiplier. event ProtocolFeeMultiplier(uint256 oldProtocolFeeMultiplier, uint256 updatedProtocolFeeMultiplier); // Logs updates to the protocolFeeCollector address. event ProtocolFeeCollectorAddress(address oldProtocolFeeCollector, address updatedProtocolFeeCollector); /// @dev Allows the owner to update the protocol fee multiplier. /// @param updatedProtocolFeeMultiplier The updated protocol fee multiplier. function setProtocolFeeMultiplier(uint256 updatedProtocolFeeMultiplier) external; /// @dev Allows the owner to update the protocolFeeCollector address. /// @param updatedProtocolFeeCollector The updated protocolFeeCollector contract address. function setProtocolFeeCollectorAddress(address updatedProtocolFeeCollector) external; /// @dev Returns the protocolFeeMultiplier function protocolFeeMultiplier() external view returns (uint256); /// @dev Returns the protocolFeeCollector address function protocolFeeCollector() external view returns (address); } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.9; pragma experimental ABIEncoderV2; import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol"; import "@0x/contracts-exchange-libs/contracts/src/LibZeroExTransaction.sol"; contract ISignatureValidator { // Allowed signature types. enum SignatureType { Illegal, // 0x00, default value Invalid, // 0x01 EIP712, // 0x02 EthSign, // 0x03 Wallet, // 0x04 Validator, // 0x05 PreSigned, // 0x06 EIP1271Wallet, // 0x07 NSignatureTypes // 0x08, number of signature types. Always leave at end. } event SignatureValidatorApproval( address indexed signerAddress, // Address that approves or disapproves a contract to verify signatures. address indexed validatorAddress, // Address of signature validator contract. bool isApproved // Approval or disapproval of validator contract. ); /// @dev Approves a hash on-chain. /// After presigning a hash, the preSign signature type will become valid for that hash and signer. /// @param hash Any 32-byte hash. function preSign(bytes32 hash) external payable; /// @dev Approves/unnapproves a Validator contract to verify signatures on signer's behalf. /// @param validatorAddress Address of Validator contract. /// @param approval Approval or disapproval of Validator contract. function setSignatureValidatorApproval( address validatorAddress, bool approval ) external payable; /// @dev Verifies that a hash has been signed by the given signer. /// @param hash Any 32-byte hash. /// @param signature Proof that the hash has been signed by signer. /// @return isValid `true` if the signature is valid for the given hash and signer. function isValidHashSignature( bytes32 hash, address signerAddress, bytes memory signature ) public view returns (bool isValid); /// @dev Verifies that a signature for an order is valid. /// @param order The order. /// @param signature Proof that the order has been signed by signer. /// @return isValid true if the signature is valid for the given order and signer. function isValidOrderSignature( LibOrder.Order memory order, bytes memory signature ) public view returns (bool isValid); /// @dev Verifies that a signature for a transaction is valid. /// @param transaction The transaction. /// @param signature Proof that the order has been signed by signer. /// @return isValid true if the signature is valid for the given transaction and signer. function isValidTransactionSignature( LibZeroExTransaction.ZeroExTransaction memory transaction, bytes memory signature ) public view returns (bool isValid); /// @dev Verifies that an order, with provided order hash, has been signed /// by the given signer. /// @param order The order. /// @param orderHash The hash of the order. /// @param signature Proof that the hash has been signed by signer. /// @return isValid True if the signature is valid for the given order and signer. function _isValidOrderWithHashSignature( LibOrder.Order memory order, bytes32 orderHash, bytes memory signature ) internal view returns (bool isValid); /// @dev Verifies that a transaction, with provided order hash, has been signed /// by the given signer. /// @param transaction The transaction. /// @param transactionHash The hash of the transaction. /// @param signature Proof that the hash has been signed by signer. /// @return isValid True if the signature is valid for the given transaction and signer. function _isValidTransactionWithHashSignature( LibZeroExTransaction.ZeroExTransaction memory transaction, bytes32 transactionHash, bytes memory signature ) internal view returns (bool isValid); } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.9; pragma experimental ABIEncoderV2; import "@0x/contracts-exchange-libs/contracts/src/LibZeroExTransaction.sol"; contract ITransactions { // TransactionExecution event is emitted when a ZeroExTransaction is executed. event TransactionExecution(bytes32 indexed transactionHash); /// @dev Executes an Exchange method call in the context of signer. /// @param transaction 0x transaction containing salt, signerAddress, and data. /// @param signature Proof that transaction has been signed by signer. /// @return ABI encoded return data of the underlying Exchange function call. function executeTransaction( LibZeroExTransaction.ZeroExTransaction memory transaction, bytes memory signature ) public payable returns (bytes memory); /// @dev Executes a batch of Exchange method calls in the context of signer(s). /// @param transactions Array of 0x transactions containing salt, signerAddress, and data. /// @param signatures Array of proofs that transactions have been signed by signer(s). /// @return Array containing ABI encoded return data for each of the underlying Exchange function calls. function batchExecuteTransactions( LibZeroExTransaction.ZeroExTransaction[] memory transactions, bytes[] memory signatures ) public payable returns (bytes[] memory); /// @dev The current function will be called in the context of this address (either 0x transaction signer or `msg.sender`). /// If calling a fill function, this address will represent the taker. /// If calling a cancel function, this address will represent the maker. /// @return Signer of 0x transaction if entry point is `executeTransaction`. /// `msg.sender` if entry point is any other function. function _getCurrentContextAddress() internal view returns (address); } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.9; pragma experimental ABIEncoderV2; contract ITransferSimulator { /// @dev This function may be used to simulate any amount of transfers /// As they would occur through the Exchange contract. Note that this function /// will always revert, even if all transfers are successful. However, it may /// be used with eth_call or with a try/catch pattern in order to simulate /// the results of the transfers. /// @param assetData Array of asset details, each encoded per the AssetProxy contract specification. /// @param fromAddresses Array containing the `from` addresses that correspond with each transfer. /// @param toAddresses Array containing the `to` addresses that correspond with each transfer. /// @param amounts Array containing the amounts that correspond to each transfer. /// @return This function does not return a value. However, it will always revert with /// `Error("TRANSFERS_SUCCESSFUL")` if all of the transfers were successful. function simulateDispatchTransferFromCalls( bytes[] memory assetData, address[] memory fromAddresses, address[] memory toAddresses, uint256[] memory amounts ) public; } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.9; pragma experimental ABIEncoderV2; import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol"; import "@0x/contracts-exchange-libs/contracts/src/LibFillResults.sol"; contract IWrapperFunctions { /// @dev Fills the input order. Reverts if exact takerAssetFillAmount not filled. /// @param order Order struct containing order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param signature Proof that order has been created by maker. function fillOrKillOrder( LibOrder.Order memory order, uint256 takerAssetFillAmount, bytes memory signature ) public payable returns (LibFillResults.FillResults memory fillResults); /// @dev Executes multiple calls of fillOrder. /// @param orders Array of order specifications. /// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders. /// @param signatures Proofs that orders have been created by makers. /// @return Array of amounts filled and fees paid by makers and taker. function batchFillOrders( LibOrder.Order[] memory orders, uint256[] memory takerAssetFillAmounts, bytes[] memory signatures ) public payable returns (LibFillResults.FillResults[] memory fillResults); /// @dev Executes multiple calls of fillOrKillOrder. /// @param orders Array of order specifications. /// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders. /// @param signatures Proofs that orders have been created by makers. /// @return Array of amounts filled and fees paid by makers and taker. function batchFillOrKillOrders( LibOrder.Order[] memory orders, uint256[] memory takerAssetFillAmounts, bytes[] memory signatures ) public payable returns (LibFillResults.FillResults[] memory fillResults); /// @dev Executes multiple calls of fillOrder. If any fill reverts, the error is caught and ignored. /// @param orders Array of order specifications. /// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders. /// @param signatures Proofs that orders have been created by makers. /// @return Array of amounts filled and fees paid by makers and taker. function batchFillOrdersNoThrow( LibOrder.Order[] memory orders, uint256[] memory takerAssetFillAmounts, bytes[] memory signatures ) public payable returns (LibFillResults.FillResults[] memory fillResults); /// @dev Executes multiple calls of fillOrder until total amount of takerAsset is sold by taker. /// If any fill reverts, the error is caught and ignored. /// NOTE: This function does not enforce that the takerAsset is the same for each order. /// @param orders Array of order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param signatures Proofs that orders have been signed by makers. /// @return Amounts filled and fees paid by makers and taker. function marketSellOrdersNoThrow( LibOrder.Order[] memory orders, uint256 takerAssetFillAmount, bytes[] memory signatures ) public payable returns (LibFillResults.FillResults memory fillResults); /// @dev Executes multiple calls of fillOrder until total amount of makerAsset is bought by taker. /// If any fill reverts, the error is caught and ignored. /// NOTE: This function does not enforce that the makerAsset is the same for each order. /// @param orders Array of order specifications. /// @param makerAssetFillAmount Desired amount of makerAsset to buy. /// @param signatures Proofs that orders have been signed by makers. /// @return Amounts filled and fees paid by makers and taker. function marketBuyOrdersNoThrow( LibOrder.Order[] memory orders, uint256 makerAssetFillAmount, bytes[] memory signatures ) public payable returns (LibFillResults.FillResults memory fillResults); /// @dev Calls marketSellOrdersNoThrow then reverts if < takerAssetFillAmount has been sold. /// NOTE: This function does not enforce that the takerAsset is the same for each order. /// @param orders Array of order specifications. /// @param takerAssetFillAmount Minimum amount of takerAsset to sell. /// @param signatures Proofs that orders have been signed by makers. /// @return Amounts filled and fees paid by makers and taker. function marketSellOrdersFillOrKill( LibOrder.Order[] memory orders, uint256 takerAssetFillAmount, bytes[] memory signatures ) public payable returns (LibFillResults.FillResults memory fillResults); /// @dev Calls marketBuyOrdersNoThrow then reverts if < makerAssetFillAmount has been bought. /// NOTE: This function does not enforce that the makerAsset is the same for each order. /// @param orders Array of order specifications. /// @param makerAssetFillAmount Minimum amount of makerAsset to buy. /// @param signatures Proofs that orders have been signed by makers. /// @return Amounts filled and fees paid by makers and taker. function marketBuyOrdersFillOrKill( LibOrder.Order[] memory orders, uint256 makerAssetFillAmount, bytes[] memory signatures ) public payable returns (LibFillResults.FillResults memory fillResults); /// @dev Executes multiple calls of cancelOrder. /// @param orders Array of order specifications. function batchCancelOrders(LibOrder.Order[] memory orders) public payable; } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.9; import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol"; import "@0x/contracts-exchange-libs/contracts/src/LibExchangeRichErrors.sol"; import "@0x/contracts-utils/contracts/src/LibBytes.sol"; library LibExchangeRichErrorDecoder { using LibBytes for bytes; /// @dev Decompose an ABI-encoded SignatureError. /// @param encoded ABI-encoded revert error. /// @return errorCode The error code. /// @return signerAddress The expected signer of the hash. /// @return signature The full signature. function decodeSignatureError(bytes memory encoded) internal pure returns ( LibExchangeRichErrors.SignatureErrorCodes errorCode, bytes32 hash, address signerAddress, bytes memory signature ) { _assertSelectorBytes(encoded, LibExchangeRichErrors.SignatureErrorSelector()); uint8 _errorCode; (_errorCode, hash, signerAddress, signature) = abi.decode( encoded.sliceDestructive(4, encoded.length), (uint8, bytes32, address, bytes) ); errorCode = LibExchangeRichErrors.SignatureErrorCodes(_errorCode); } /// @dev Decompose an ABI-encoded SignatureValidatorError. /// @param encoded ABI-encoded revert error. /// @return signerAddress The expected signer of the hash. /// @return signature The full signature bytes. /// @return errorData The revert data thrown by the validator contract. function decodeEIP1271SignatureError(bytes memory encoded) internal pure returns ( address verifyingContractAddress, bytes memory data, bytes memory signature, bytes memory errorData ) { _assertSelectorBytes(encoded, LibExchangeRichErrors.EIP1271SignatureErrorSelector()); (verifyingContractAddress, data, signature, errorData) = abi.decode( encoded.sliceDestructive(4, encoded.length), (address, bytes, bytes, bytes) ); } /// @dev Decompose an ABI-encoded SignatureValidatorNotApprovedError. /// @param encoded ABI-encoded revert error. /// @return signerAddress The expected signer of the hash. /// @return validatorAddress The expected validator. function decodeSignatureValidatorNotApprovedError(bytes memory encoded) internal pure returns ( address signerAddress, address validatorAddress ) { _assertSelectorBytes(encoded, LibExchangeRichErrors.SignatureValidatorNotApprovedErrorSelector()); (signerAddress, validatorAddress) = abi.decode( encoded.sliceDestructive(4, encoded.length), (address, address) ); } /// @dev Decompose an ABI-encoded SignatureWalletError. /// @param encoded ABI-encoded revert error. /// @return errorCode The error code. /// @return signerAddress The expected signer of the hash. /// @return signature The full signature bytes. /// @return errorData The revert data thrown by the validator contract. function decodeSignatureWalletError(bytes memory encoded) internal pure returns ( bytes32 hash, address signerAddress, bytes memory signature, bytes memory errorData ) { _assertSelectorBytes(encoded, LibExchangeRichErrors.SignatureWalletErrorSelector()); (hash, signerAddress, signature, errorData) = abi.decode( encoded.sliceDestructive(4, encoded.length), (bytes32, address, bytes, bytes) ); } /// @dev Decompose an ABI-encoded OrderStatusError. /// @param encoded ABI-encoded revert error. /// @return orderHash The order hash. /// @return orderStatus The order status. function decodeOrderStatusError(bytes memory encoded) internal pure returns ( bytes32 orderHash, LibOrder.OrderStatus orderStatus ) { _assertSelectorBytes(encoded, LibExchangeRichErrors.OrderStatusErrorSelector()); uint8 _orderStatus; (orderHash, _orderStatus) = abi.decode( encoded.sliceDestructive(4, encoded.length), (bytes32, uint8) ); orderStatus = LibOrder.OrderStatus(_orderStatus); } /// @dev Decompose an ABI-encoded OrderStatusError. /// @param encoded ABI-encoded revert error. /// @return errorCode Error code that corresponds to invalid maker, taker, or sender. /// @return orderHash The order hash. /// @return contextAddress The maker, taker, or sender address function decodeExchangeInvalidContextError(bytes memory encoded) internal pure returns ( LibExchangeRichErrors.ExchangeContextErrorCodes errorCode, bytes32 orderHash, address contextAddress ) { _assertSelectorBytes(encoded, LibExchangeRichErrors.ExchangeInvalidContextErrorSelector()); uint8 _errorCode; (_errorCode, orderHash, contextAddress) = abi.decode( encoded.sliceDestructive(4, encoded.length), (uint8, bytes32, address) ); errorCode = LibExchangeRichErrors.ExchangeContextErrorCodes(_errorCode); } /// @dev Decompose an ABI-encoded FillError. /// @param encoded ABI-encoded revert error. /// @return errorCode The error code. /// @return orderHash The order hash. function decodeFillError(bytes memory encoded) internal pure returns ( LibExchangeRichErrors.FillErrorCodes errorCode, bytes32 orderHash ) { _assertSelectorBytes(encoded, LibExchangeRichErrors.FillErrorSelector()); uint8 _errorCode; (_errorCode, orderHash) = abi.decode( encoded.sliceDestructive(4, encoded.length), (uint8, bytes32) ); errorCode = LibExchangeRichErrors.FillErrorCodes(_errorCode); } /// @dev Decompose an ABI-encoded OrderEpochError. /// @param encoded ABI-encoded revert error. /// @return makerAddress The order maker. /// @return orderSenderAddress The order sender. /// @return currentEpoch The current epoch for the maker. function decodeOrderEpochError(bytes memory encoded) internal pure returns ( address makerAddress, address orderSenderAddress, uint256 currentEpoch ) { _assertSelectorBytes(encoded, LibExchangeRichErrors.OrderEpochErrorSelector()); (makerAddress, orderSenderAddress, currentEpoch) = abi.decode( encoded.sliceDestructive(4, encoded.length), (address, address, uint256) ); } /// @dev Decompose an ABI-encoded AssetProxyExistsError. /// @param encoded ABI-encoded revert error. /// @return assetProxyId Id of asset proxy. /// @return assetProxyAddress The address of the asset proxy. function decodeAssetProxyExistsError(bytes memory encoded) internal pure returns ( bytes4 assetProxyId, address assetProxyAddress) { _assertSelectorBytes(encoded, LibExchangeRichErrors.AssetProxyExistsErrorSelector()); (assetProxyId, assetProxyAddress) = abi.decode( encoded.sliceDestructive(4, encoded.length), (bytes4, address) ); } /// @dev Decompose an ABI-encoded AssetProxyDispatchError. /// @param encoded ABI-encoded revert error. /// @return errorCode The error code. /// @return orderHash Hash of the order being dispatched. /// @return assetData Asset data of the order being dispatched. function decodeAssetProxyDispatchError(bytes memory encoded) internal pure returns ( LibExchangeRichErrors.AssetProxyDispatchErrorCodes errorCode, bytes32 orderHash, bytes memory assetData ) { _assertSelectorBytes(encoded, LibExchangeRichErrors.AssetProxyDispatchErrorSelector()); uint8 _errorCode; (_errorCode, orderHash, assetData) = abi.decode( encoded.sliceDestructive(4, encoded.length), (uint8, bytes32, bytes) ); errorCode = LibExchangeRichErrors.AssetProxyDispatchErrorCodes(_errorCode); } /// @dev Decompose an ABI-encoded AssetProxyTransferError. /// @param encoded ABI-encoded revert error. /// @return orderHash Hash of the order being dispatched. /// @return assetData Asset data of the order being dispatched. /// @return errorData ABI-encoded revert data from the asset proxy. function decodeAssetProxyTransferError(bytes memory encoded) internal pure returns ( bytes32 orderHash, bytes memory assetData, bytes memory errorData ) { _assertSelectorBytes(encoded, LibExchangeRichErrors.AssetProxyTransferErrorSelector()); (orderHash, assetData, errorData) = abi.decode( encoded.sliceDestructive(4, encoded.length), (bytes32, bytes, bytes) ); } /// @dev Decompose an ABI-encoded NegativeSpreadError. /// @param encoded ABI-encoded revert error. /// @return leftOrderHash Hash of the left order being matched. /// @return rightOrderHash Hash of the right order being matched. function decodeNegativeSpreadError(bytes memory encoded) internal pure returns ( bytes32 leftOrderHash, bytes32 rightOrderHash ) { _assertSelectorBytes(encoded, LibExchangeRichErrors.NegativeSpreadErrorSelector()); (leftOrderHash, rightOrderHash) = abi.decode( encoded.sliceDestructive(4, encoded.length), (bytes32, bytes32) ); } /// @dev Decompose an ABI-encoded TransactionError. /// @param encoded ABI-encoded revert error. /// @return errorCode The error code. /// @return transactionHash Hash of the transaction. function decodeTransactionError(bytes memory encoded) internal pure returns ( LibExchangeRichErrors.TransactionErrorCodes errorCode, bytes32 transactionHash ) { _assertSelectorBytes(encoded, LibExchangeRichErrors.TransactionErrorSelector()); uint8 _errorCode; (_errorCode, transactionHash) = abi.decode( encoded.sliceDestructive(4, encoded.length), (uint8, bytes32) ); errorCode = LibExchangeRichErrors.TransactionErrorCodes(_errorCode); } /// @dev Decompose an ABI-encoded TransactionExecutionError. /// @param encoded ABI-encoded revert error. /// @return transactionHash Hash of the transaction. /// @return errorData Error thrown by exeucteTransaction(). function decodeTransactionExecutionError(bytes memory encoded) internal pure returns ( bytes32 transactionHash, bytes memory errorData ) { _assertSelectorBytes(encoded, LibExchangeRichErrors.TransactionExecutionErrorSelector()); (transactionHash, errorData) = abi.decode( encoded.sliceDestructive(4, encoded.length), (bytes32, bytes) ); } /// @dev Decompose an ABI-encoded IncompleteFillError. /// @param encoded ABI-encoded revert error. /// @return orderHash Hash of the order being filled. function decodeIncompleteFillError(bytes memory encoded) internal pure returns ( LibExchangeRichErrors.IncompleteFillErrorCode errorCode, uint256 expectedAssetFillAmount, uint256 actualAssetFillAmount ) { _assertSelectorBytes(encoded, LibExchangeRichErrors.IncompleteFillErrorSelector()); uint8 _errorCode; (_errorCode, expectedAssetFillAmount, actualAssetFillAmount) = abi.decode( encoded.sliceDestructive(4, encoded.length), (uint8, uint256, uint256) ); errorCode = LibExchangeRichErrors.IncompleteFillErrorCode(_errorCode); } /// @dev Revert if the leading 4 bytes of `encoded` is not `selector`. function _assertSelectorBytes(bytes memory encoded, bytes4 selector) private pure { bytes4 actualSelector = LibBytes.readBytes4(encoded, 0); require( actualSelector == selector, "BAD_SELECTOR" ); } } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.16; /// @dev A library for working with 18 digit, base 10 decimals. library D18 { /// @dev Decimal places for dydx value quantities. uint256 private constant PRECISION = 18; /// @dev 1.0 in base-18 decimal. int256 private constant DECIMAL_ONE = int256(10 ** PRECISION); /// @dev Minimum signed integer value. int256 private constant MIN_INT256_VALUE = int256(0x8000000000000000000000000000000000000000000000000000000000000000); /// @dev Return `1.0` function one() internal pure returns (int256 r) { r = DECIMAL_ONE; } /// @dev Add two decimals. function add(int256 a, int256 b) internal pure returns (int256 r) { r = _add(a, b); } /// @dev Add two decimals. function add(uint256 a, int256 b) internal pure returns (int256 r) { require(int256(a) >= 0, "D18/DECIMAL_VALUE_TOO_BIG"); r = _add(int256(a), b); } /// @dev Add two decimals. function add(int256 a, uint256 b) internal pure returns (int256 r) { require(int256(b) >= 0, "D18/DECIMAL_VALUE_TOO_BIG"); r = _add(a, int256(b)); } /// @dev Add two decimals. function add(uint256 a, uint256 b) internal pure returns (int256 r) { require(int256(a) >= 0, "D18/DECIMAL_VALUE_TOO_BIG"); require(int256(b) >= 0, "D18/DECIMAL_VALUE_TOO_BIG"); r = _add(int256(a), int256(b)); } /// @dev Subract two decimals. function sub(int256 a, int256 b) internal pure returns (int256 r) { r = _add(a, -b); } /// @dev Subract two decimals. function sub(uint256 a, int256 b) internal pure returns (int256 r) { require(int256(a) >= 0, "D18/DECIMAL_VALUE_TOO_BIG"); r = _add(int256(a), -b); } /// @dev Subract two decimals. function sub(uint256 a, uint256 b) internal pure returns (int256 r) { require(int256(a) >= 0, "D18/DECIMAL_VALUE_TOO_BIG"); require(int256(b) >= 0, "D18/DECIMAL_VALUE_TOO_BIG"); r = _add(int256(a), -int256(b)); } /// @dev Multiply two decimals. function mul(int256 a, int256 b) internal pure returns (int256 r) { r = _div(_mul(a, b), DECIMAL_ONE); } /// @dev Multiply two decimals. function mul(uint256 a, int256 b) internal pure returns (int256 r) { require(int256(a) >= 0, "D18/DECIMAL_VALUE_TOO_BIG"); r = _div(_mul(int256(a), b), DECIMAL_ONE); } /// @dev Multiply two decimals. function mul(int256 a, uint256 b) internal pure returns (int256 r) { require(int256(b) >= 0, "D18/DECIMAL_VALUE_TOO_BIG"); r = _div(_mul(a, int256(b)), DECIMAL_ONE); } /// @dev Multiply two decimals. function mul(uint256 a, uint256 b) internal pure returns (int256 r) { require(int256(a) >= 0, "D18/DECIMAL_VALUE_TOO_BIG"); require(int256(b) >= 0, "D18/DECIMAL_VALUE_TOO_BIG"); r = _div(_mul(int256(a), int256(b)), DECIMAL_ONE); } /// @dev Divide two decimals. function div(int256 a, int256 b) internal pure returns (int256 r) { r = _div(_mul(a, DECIMAL_ONE), b); } /// @dev Divide two decimals. function div(uint256 a, int256 b) internal pure returns (int256 r) { require(int256(a) >= 0, "D18/DECIMAL_VALUE_TOO_BIG"); r = _div(_mul(int256(a), DECIMAL_ONE), b); } /// @dev Divide two decimals. function div(int256 a, uint256 b) internal pure returns (int256 r) { require(int256(b) >= 0, "D18/DECIMAL_VALUE_TOO_BIG"); r = _div(_mul(a, DECIMAL_ONE), int256(b)); } /// @dev Divide two decimals. function div(uint256 a, uint256 b) internal pure returns (int256 r) { require(int256(a) >= 0, "D18/DECIMAL_VALUE_TOO_BIG"); require(int256(b) >= 0, "D18/DECIMAL_VALUE_TOO_BIG"); r = _div(_mul(int256(a), DECIMAL_ONE), int256(b)); } /// @dev Safely convert an unsigned integer into a signed integer. function toSigned(uint256 a) internal pure returns (int256 r) { require(int256(a) >= 0, "D18/DECIMAL_VALUE_TOO_BIG"); r = int256(a); } /// @dev Clip a signed value to be positive. function clip(int256 a) internal pure returns (int256 r) { r = a < 0 ? 0 : a; } /// @dev Safely multiply two signed integers. function _mul(int256 a, int256 b) private pure returns (int256 r) { if (a == 0 || b == 0) { return 0; } r = a * b; require(r / a == b && r / b == a, "D18/DECIMAL_MUL_OVERFLOW"); return r; } /// @dev Safely divide two signed integers. function _div(int256 a, int256 b) private pure returns (int256 r) { require(b != 0, "D18/DECIMAL_DIV_BY_ZERO"); require(a != MIN_INT256_VALUE || b != -1, "D18/DECIMAL_DIV_OVERFLOW"); r = a / b; } /// @dev Safely add two signed integers. function _add(int256 a, int256 b) private pure returns (int256 r) { r = a + b; require( !((a < 0 && b < 0 && r > a) || (a > 0 && b > 0 && r < a)), "D18/DECIMAL_ADD_OVERFLOW" ); } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.9; contract DeploymentConstants { // solhint-disable separate-by-one-line-in-contract // Mainnet addresses /////////////////////////////////////////////////////// /// @dev Mainnet address of the WETH contract. address constant private WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; /// @dev Mainnet address of the KyberNetworkProxy contract. address constant private KYBER_NETWORK_PROXY_ADDRESS = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e; /// @dev Mainnet address of the KyberHintHandler contract. address constant private KYBER_HINT_HANDLER_ADDRESS = 0xa1C0Fa73c39CFBcC11ec9Eb1Afc665aba9996E2C; /// @dev Mainnet address of the `UniswapExchangeFactory` contract. address constant private UNISWAP_EXCHANGE_FACTORY_ADDRESS = 0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95; /// @dev Mainnet address of the `UniswapV2Router01` contract. address constant private UNISWAP_V2_ROUTER_01_ADDRESS = 0xf164fC0Ec4E93095b804a4795bBe1e041497b92a; /// @dev Mainnet address of the Eth2Dai `MatchingMarket` contract. address constant private ETH2DAI_ADDRESS = 0x794e6e91555438aFc3ccF1c5076A74F42133d08D; /// @dev Mainnet address of the `ERC20BridgeProxy` contract address constant private ERC20_BRIDGE_PROXY_ADDRESS = 0x8ED95d1746bf1E4dAb58d8ED4724f1Ef95B20Db0; ///@dev Mainnet address of the `Dai` (multi-collateral) contract address constant private DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; /// @dev Mainnet address of the `Chai` contract address constant private CHAI_ADDRESS = 0x06AF07097C9Eeb7fD685c692751D5C66dB49c215; /// @dev Mainnet address of the 0x DevUtils contract. address constant private DEV_UTILS_ADDRESS = 0x74134CF88b21383713E096a5ecF59e297dc7f547; /// @dev Kyber ETH pseudo-address. address constant internal KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @dev Mainnet address of the dYdX contract. address constant private DYDX_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; /// @dev Mainnet address of the GST2 contract address constant private GST_ADDRESS = 0x0000000000b3F879cb30FE243b4Dfee438691c04; /// @dev Mainnet address of the GST Collector address constant private GST_COLLECTOR_ADDRESS = 0x000000D3b08566BE75A6DB803C03C85C0c1c5B96; /// @dev Mainnet address of the mStable mUSD contract. address constant private MUSD_ADDRESS = 0xe2f2a5C287993345a840Db3B0845fbC70f5935a5; /// @dev Mainnet address of the Mooniswap Registry contract address constant private MOONISWAP_REGISTRY = 0x71CD6666064C3A1354a3B4dca5fA1E2D3ee7D303; /// @dev Mainnet address of the DODO Registry (ZOO) contract address constant private DODO_REGISTRY = 0x3A97247DF274a17C59A3bd12735ea3FcDFb49950; /// @dev Mainnet address of the DODO Helper contract address constant private DODO_HELPER = 0x533dA777aeDCE766CEAe696bf90f8541A4bA80Eb; // // Ropsten addresses /////////////////////////////////////////////////////// // /// @dev Mainnet address of the WETH contract. // address constant private WETH_ADDRESS = 0xc778417E063141139Fce010982780140Aa0cD5Ab; // /// @dev Mainnet address of the KyberNetworkProxy contract. // address constant private KYBER_NETWORK_PROXY_ADDRESS = 0xd719c34261e099Fdb33030ac8909d5788D3039C4; // /// @dev Mainnet address of the `UniswapExchangeFactory` contract. // address constant private UNISWAP_EXCHANGE_FACTORY_ADDRESS = 0x9c83dCE8CA20E9aAF9D3efc003b2ea62aBC08351; // /// @dev Mainnet address of the `UniswapV2Router01` contract. // address constant private UNISWAP_V2_ROUTER_01_ADDRESS = 0xf164fC0Ec4E93095b804a4795bBe1e041497b92a; // /// @dev Mainnet address of the Eth2Dai `MatchingMarket` contract. // address constant private ETH2DAI_ADDRESS = address(0); // /// @dev Mainnet address of the `ERC20BridgeProxy` contract // address constant private ERC20_BRIDGE_PROXY_ADDRESS = 0xb344afeD348de15eb4a9e180205A2B0739628339; // ///@dev Mainnet address of the `Dai` (multi-collateral) contract // address constant private DAI_ADDRESS = address(0); // /// @dev Mainnet address of the `Chai` contract // address constant private CHAI_ADDRESS = address(0); // /// @dev Mainnet address of the 0x DevUtils contract. // address constant private DEV_UTILS_ADDRESS = 0xC812AF3f3fBC62F76ea4262576EC0f49dB8B7f1c; // /// @dev Kyber ETH pseudo-address. // address constant internal KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // /// @dev Mainnet address of the dYdX contract. // address constant private DYDX_ADDRESS = address(0); // /// @dev Mainnet address of the GST2 contract // address constant private GST_ADDRESS = address(0); // /// @dev Mainnet address of the GST Collector // address constant private GST_COLLECTOR_ADDRESS = address(0); // /// @dev Mainnet address of the mStable mUSD contract. // address constant private MUSD_ADDRESS = 0x4E1000616990D83e56f4b5fC6CC8602DcfD20459; // // Rinkeby addresses /////////////////////////////////////////////////////// // /// @dev Mainnet address of the WETH contract. // address constant private WETH_ADDRESS = 0xc778417E063141139Fce010982780140Aa0cD5Ab; // /// @dev Mainnet address of the KyberNetworkProxy contract. // address constant private KYBER_NETWORK_PROXY_ADDRESS = 0x0d5371e5EE23dec7DF251A8957279629aa79E9C5; // /// @dev Mainnet address of the `UniswapExchangeFactory` contract. // address constant private UNISWAP_EXCHANGE_FACTORY_ADDRESS = 0xf5D915570BC477f9B8D6C0E980aA81757A3AaC36; // /// @dev Mainnet address of the `UniswapV2Router01` contract. // address constant private UNISWAP_V2_ROUTER_01_ADDRESS = 0xf164fC0Ec4E93095b804a4795bBe1e041497b92a; // /// @dev Mainnet address of the Eth2Dai `MatchingMarket` contract. // address constant private ETH2DAI_ADDRESS = address(0); // /// @dev Mainnet address of the `ERC20BridgeProxy` contract // address constant private ERC20_BRIDGE_PROXY_ADDRESS = 0xA2AA4bEFED748Fba27a3bE7Dfd2C4b2c6DB1F49B; // ///@dev Mainnet address of the `Dai` (multi-collateral) contract // address constant private DAI_ADDRESS = address(0); // /// @dev Mainnet address of the `Chai` contract // address constant private CHAI_ADDRESS = address(0); // /// @dev Mainnet address of the 0x DevUtils contract. // address constant private DEV_UTILS_ADDRESS = 0x46B5BC959e8A754c0256FFF73bF34A52Ad5CdfA9; // /// @dev Kyber ETH pseudo-address. // address constant internal KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // /// @dev Mainnet address of the dYdX contract. // address constant private DYDX_ADDRESS = address(0); // /// @dev Mainnet address of the GST2 contract // address constant private GST_ADDRESS = address(0); // /// @dev Mainnet address of the GST Collector // address constant private GST_COLLECTOR_ADDRESS = address(0); // /// @dev Mainnet address of the mStable mUSD contract. // address constant private MUSD_ADDRESS = address(0); // // Kovan addresses ///////////////////////////////////////////////////////// // /// @dev Kovan address of the WETH contract. // address constant private WETH_ADDRESS = 0xd0A1E359811322d97991E03f863a0C30C2cF029C; // /// @dev Kovan address of the KyberNetworkProxy contract. // address constant private KYBER_NETWORK_PROXY_ADDRESS = 0x692f391bCc85cefCe8C237C01e1f636BbD70EA4D; // /// @dev Kovan address of the `UniswapExchangeFactory` contract. // address constant private UNISWAP_EXCHANGE_FACTORY_ADDRESS = 0xD3E51Ef092B2845f10401a0159B2B96e8B6c3D30; // /// @dev Kovan address of the `UniswapV2Router01` contract. // address constant private UNISWAP_V2_ROUTER_01_ADDRESS = 0xf164fC0Ec4E93095b804a4795bBe1e041497b92a; // /// @dev Kovan address of the Eth2Dai `MatchingMarket` contract. // address constant private ETH2DAI_ADDRESS = 0xe325acB9765b02b8b418199bf9650972299235F4; // /// @dev Kovan address of the `ERC20BridgeProxy` contract // address constant private ERC20_BRIDGE_PROXY_ADDRESS = 0x3577552C1Fb7A44aD76BeEB7aB53251668A21F8D; // /// @dev Kovan address of the `Chai` contract // address constant private CHAI_ADDRESS = address(0); // /// @dev Kovan address of the `Dai` (multi-collateral) contract // address constant private DAI_ADDRESS = 0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa; // /// @dev Kovan address of the 0x DevUtils contract. // address constant private DEV_UTILS_ADDRESS = 0x9402639A828BdF4E9e4103ac3B69E1a6E522eB59; // /// @dev Kyber ETH pseudo-address. // address constant internal KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // /// @dev Kovan address of the dYdX contract. // address constant private DYDX_ADDRESS = address(0); // /// @dev Kovan address of the GST2 contract // address constant private GST_ADDRESS = address(0); // /// @dev Kovan address of the GST Collector // address constant private GST_COLLECTOR_ADDRESS = address(0); // /// @dev Mainnet address of the mStable mUSD contract. // address constant private MUSD_ADDRESS = address(0); /// @dev Overridable way to get the `KyberNetworkProxy` address. /// @return kyberAddress The `IKyberNetworkProxy` address. function _getKyberNetworkProxyAddress() internal view returns (address kyberAddress) { return KYBER_NETWORK_PROXY_ADDRESS; } /// @dev Overridable way to get the `KyberHintHandler` address. /// @return kyberAddress The `IKyberHintHandler` address. function _getKyberHintHandlerAddress() internal view returns (address hintHandlerAddress) { return KYBER_HINT_HANDLER_ADDRESS; } /// @dev Overridable way to get the WETH address. /// @return wethAddress The WETH address. function _getWethAddress() internal view returns (address wethAddress) { return WETH_ADDRESS; } /// @dev Overridable way to get the `UniswapExchangeFactory` address. /// @return uniswapAddress The `UniswapExchangeFactory` address. function _getUniswapExchangeFactoryAddress() internal view returns (address uniswapAddress) { return UNISWAP_EXCHANGE_FACTORY_ADDRESS; } /// @dev Overridable way to get the `UniswapV2Router01` address. /// @return uniswapRouterAddress The `UniswapV2Router01` address. function _getUniswapV2Router01Address() internal view returns (address uniswapRouterAddress) { return UNISWAP_V2_ROUTER_01_ADDRESS; } /// @dev An overridable way to retrieve the Eth2Dai `MatchingMarket` contract. /// @return eth2daiAddress The Eth2Dai `MatchingMarket` contract. function _getEth2DaiAddress() internal view returns (address eth2daiAddress) { return ETH2DAI_ADDRESS; } /// @dev An overridable way to retrieve the `ERC20BridgeProxy` contract. /// @return erc20BridgeProxyAddress The `ERC20BridgeProxy` contract. function _getERC20BridgeProxyAddress() internal view returns (address erc20BridgeProxyAddress) { return ERC20_BRIDGE_PROXY_ADDRESS; } /// @dev An overridable way to retrieve the `Dai` contract. /// @return daiAddress The `Dai` contract. function _getDaiAddress() internal view returns (address daiAddress) { return DAI_ADDRESS; } /// @dev An overridable way to retrieve the `Chai` contract. /// @return chaiAddress The `Chai` contract. function _getChaiAddress() internal view returns (address chaiAddress) { return CHAI_ADDRESS; } /// @dev An overridable way to retrieve the 0x `DevUtils` contract address. /// @return devUtils The 0x `DevUtils` contract address. function _getDevUtilsAddress() internal view returns (address devUtils) { return DEV_UTILS_ADDRESS; } /// @dev Overridable way to get the DyDx contract. /// @return exchange The DyDx exchange contract. function _getDydxAddress() internal view returns (address dydxAddress) { return DYDX_ADDRESS; } /// @dev An overridable way to retrieve the GST2 contract address. /// @return gst The GST contract. function _getGstAddress() internal view returns (address gst) { return GST_ADDRESS; } /// @dev An overridable way to retrieve the GST Collector address. /// @return collector The GST collector address. function _getGstCollectorAddress() internal view returns (address collector) { return GST_COLLECTOR_ADDRESS; } /// @dev An overridable way to retrieve the mStable mUSD address. /// @return musd The mStable mUSD address. function _getMUsdAddress() internal view returns (address musd) { return MUSD_ADDRESS; } /// @dev An overridable way to retrieve the Mooniswap registry address. /// @return registry The Mooniswap registry address. function _getMooniswapAddress() internal view returns (address) { return MOONISWAP_REGISTRY; } /// @dev An overridable way to retrieve the DODO Registry contract address. /// @return registry The DODO Registry contract address. function _getDODORegistryAddress() internal view returns (address) { return DODO_REGISTRY; } /// @dev An overridable way to retrieve the DODO Helper contract address. /// @return registry The DODO Helper contract address. function _getDODOHelperAddress() internal view returns (address) { return DODO_HELPER; } } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.9; import "./LibBytesRichErrors.sol"; import "./LibRichErrors.sol"; library LibBytes { using LibBytes for bytes; /// @dev Gets the memory address for a byte array. /// @param input Byte array to lookup. /// @return memoryAddress Memory address of byte array. This /// points to the header of the byte array which contains /// the length. function rawAddress(bytes memory input) internal pure returns (uint256 memoryAddress) { assembly { memoryAddress := input } return memoryAddress; } /// @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 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 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) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired, from, to )); } if (to > b.length) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired, to, b.length )); } // Create a new bytes structure and copy contents result = new bytes(to - from); memCopy( result.contentAddress(), b.contentAddress() + from, result.length ); return result; } /// @dev Returns a slice from a byte array without preserving the input. /// @param b The byte array to take a slice from. Will be destroyed in the process. /// @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) /// @dev When `from == 0`, the original array will match the slice. In other cases its state will be corrupted. function sliceDestructive( 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) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired, from, to )); } if (to > b.length) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired, to, b.length )); } // Create a new bytes structure around [from, to) in-place. assembly { result := add(b, from) mstore(result, sub(to, from)) } return result; } /// @dev Pops the last byte off of a byte array by modifying its length. /// @param b Byte array that will be modified. /// @return The byte that was popped off. function popLastByte(bytes memory b) internal pure returns (bytes1 result) { if (b.length == 0) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanZeroRequired, b.length, 0 )); } // Store last byte. result = b[b.length - 1]; assembly { // Decrement length of byte array. let newLen := sub(mload(b), 1) mstore(b, newLen) } return result; } /// @dev Tests equality of two byte arrays. /// @param lhs First byte array to compare. /// @param rhs Second byte array to compare. /// @return True if arrays are the same. False otherwise. function equals( bytes memory lhs, bytes memory rhs ) internal pure returns (bool equal) { // Keccak gas cost is 30 + numWords * 6. This is a cheap way to compare. // We early exit on unequal lengths, but keccak would also correctly // handle this. return lhs.length == rhs.length && keccak256(lhs) == keccak256(rhs); } /// @dev Reads an address from a position in a byte array. /// @param b Byte array containing an address. /// @param index Index in byte array of address. /// @return address from byte array. function readAddress( bytes memory b, uint256 index ) internal pure returns (address result) { if (b.length < index + 20) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired, b.length, index + 20 // 20 is length of address )); } // Add offset to index: // 1. Arrays are prefixed by 32-byte length parameter (add 32 to index) // 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index) index += 20; // Read address from array memory assembly { // 1. Add index to address of bytes array // 2. Load 32-byte word from memory // 3. Apply 20-byte mask to obtain address result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff) } return result; } /// @dev Writes an address into a specific position in a byte array. /// @param b Byte array to insert address into. /// @param index Index in byte array of address. /// @param input Address to put into byte array. function writeAddress( bytes memory b, uint256 index, address input ) internal pure { if (b.length < index + 20) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired, b.length, index + 20 // 20 is length of address )); } // Add offset to index: // 1. Arrays are prefixed by 32-byte length parameter (add 32 to index) // 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index) index += 20; // Store address into array memory assembly { // The address occupies 20 bytes and mstore stores 32 bytes. // First fetch the 32-byte word where we'll be storing the address, then // apply a mask so we have only the bytes in the word that the address will not occupy. // Then combine these bytes with the address and store the 32 bytes back to memory with mstore. // 1. Add index to address of bytes array // 2. Load 32-byte word from memory // 3. Apply 12-byte mask to obtain extra bytes occupying word of memory where we'll store the address let neighbors := and( mload(add(b, index)), 0xffffffffffffffffffffffff0000000000000000000000000000000000000000 ) // Make sure input address is clean. // (Solidity does not guarantee this) input := and(input, 0xffffffffffffffffffffffffffffffffffffffff) // Store the neighbors and address into memory mstore(add(b, index), xor(input, neighbors)) } } /// @dev Reads a bytes32 value from a position in a byte array. /// @param b Byte array containing a bytes32 value. /// @param index Index in byte array of bytes32 value. /// @return bytes32 value from byte array. function readBytes32( bytes memory b, uint256 index ) internal pure returns (bytes32 result) { if (b.length < index + 32) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired, b.length, index + 32 )); } // Arrays are prefixed by a 256 bit length parameter index += 32; // Read the bytes32 from array memory assembly { result := mload(add(b, index)) } return result; } /// @dev Writes a bytes32 into a specific position in a byte array. /// @param b Byte array to insert <input> into. /// @param index Index in byte array of <input>. /// @param input bytes32 to put into byte array. function writeBytes32( bytes memory b, uint256 index, bytes32 input ) internal pure { if (b.length < index + 32) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired, b.length, index + 32 )); } // Arrays are prefixed by a 256 bit length parameter index += 32; // Read the bytes32 from array memory assembly { mstore(add(b, index), input) } } /// @dev Reads a uint256 value from a position in a byte array. /// @param b Byte array containing a uint256 value. /// @param index Index in byte array of uint256 value. /// @return uint256 value from byte array. function readUint256( bytes memory b, uint256 index ) internal pure returns (uint256 result) { result = uint256(readBytes32(b, index)); return result; } /// @dev Writes a uint256 into a specific position in a byte array. /// @param b Byte array to insert <input> into. /// @param index Index in byte array of <input>. /// @param input uint256 to put into byte array. function writeUint256( bytes memory b, uint256 index, uint256 input ) internal pure { writeBytes32(b, index, bytes32(input)); } /// @dev Reads an unpadded bytes4 value from a position in a byte array. /// @param b Byte array containing a bytes4 value. /// @param index Index in byte array of bytes4 value. /// @return bytes4 value from byte array. function readBytes4( bytes memory b, uint256 index ) internal pure returns (bytes4 result) { if (b.length < index + 4) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsFourRequired, b.length, index + 4 )); } // Arrays are prefixed by a 32 byte length field index += 32; // Read the bytes4 from array memory assembly { result := mload(add(b, index)) // Solidity does not require us to clean the trailing bytes. // We do it anyway result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000) } return result; } /// @dev Writes a new length to a byte array. /// Decreasing length will lead to removing the corresponding lower order bytes from the byte array. /// Increasing length may lead to appending adjacent in-memory bytes to the end of the byte array. /// @param b Bytes array to write new length to. /// @param length New length of byte array. function writeLength(bytes memory b, uint256 length) internal pure { assembly { mstore(b, length) } } } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.9; library LibBytesRichErrors { enum InvalidByteOperationErrorCodes { FromLessThanOrEqualsToRequired, ToLessThanOrEqualsLengthRequired, LengthGreaterThanZeroRequired, LengthGreaterThanOrEqualsFourRequired, LengthGreaterThanOrEqualsTwentyRequired, LengthGreaterThanOrEqualsThirtyTwoRequired, LengthGreaterThanOrEqualsNestedBytesLengthRequired, DestinationLengthGreaterThanOrEqualSourceLengthRequired } // bytes4(keccak256("InvalidByteOperationError(uint8,uint256,uint256)")) bytes4 internal constant INVALID_BYTE_OPERATION_ERROR_SELECTOR = 0x28006595; // solhint-disable func-name-mixedcase function InvalidByteOperationError( InvalidByteOperationErrorCodes errorCode, uint256 offset, uint256 required ) internal pure returns (bytes memory) { return abi.encodeWithSelector( INVALID_BYTE_OPERATION_ERROR_SELECTOR, errorCode, offset, required ); } } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.9; library LibEIP712 { // Hash of the EIP712 Domain Separator Schema // keccak256(abi.encodePacked( // "EIP712Domain(", // "string name,", // "string version,", // "uint256 chainId,", // "address verifyingContract", // ")" // )) bytes32 constant internal _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f; /// @dev Calculates a EIP712 domain separator. /// @param name The EIP712 domain name. /// @param version The EIP712 domain version. /// @param verifyingContract The EIP712 verifying contract. /// @return EIP712 domain separator. function hashEIP712Domain( string memory name, string memory version, uint256 chainId, address verifyingContract ) internal pure returns (bytes32 result) { bytes32 schemaHash = _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH; // Assembly for more efficient computing: // keccak256(abi.encodePacked( // _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH, // keccak256(bytes(name)), // keccak256(bytes(version)), // chainId, // uint256(verifyingContract) // )) assembly { // Calculate hashes of dynamic data let nameHash := keccak256(add(name, 32), mload(name)) let versionHash := keccak256(add(version, 32), mload(version)) // Load free memory pointer let memPtr := mload(64) // Store params in memory mstore(memPtr, schemaHash) mstore(add(memPtr, 32), nameHash) mstore(add(memPtr, 64), versionHash) mstore(add(memPtr, 96), chainId) mstore(add(memPtr, 128), verifyingContract) // Compute hash result := keccak256(memPtr, 160) } return result; } /// @dev Calculates EIP712 encoding for a hash struct with a given domain hash. /// @param eip712DomainHash Hash of the domain domain separator data, computed /// with getDomainHash(). /// @param hashStruct The EIP712 hash struct. /// @return EIP712 hash applied to the given EIP712 Domain. function hashEIP712Message(bytes32 eip712DomainHash, bytes32 hashStruct) internal pure returns (bytes32 result) { // Assembly for more efficient computing: // keccak256(abi.encodePacked( // EIP191_HEADER, // EIP712_DOMAIN_HASH, // hashStruct // )); assembly { // Load free memory pointer let memPtr := mload(64) mstore(memPtr, 0x1901000000000000000000000000000000000000000000000000000000000000) // EIP191 header mstore(add(memPtr, 2), eip712DomainHash) // EIP712 domain hash mstore(add(memPtr, 34), hashStruct) // Hash of struct // Compute hash result := keccak256(memPtr, 66) } return result; } } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.9; library LibRichErrors { // bytes4(keccak256("Error(string)")) bytes4 internal constant STANDARD_ERROR_SELECTOR = 0x08c379a0; // solhint-disable func-name-mixedcase /// @dev ABI encode a standard, string revert error payload. /// This is the same payload that would be included by a `revert(string)` /// solidity statement. It has the function signature `Error(string)`. /// @param message The error string. /// @return The ABI encoded error. function StandardError( string memory message ) internal pure returns (bytes memory) { return abi.encodeWithSelector( STANDARD_ERROR_SELECTOR, bytes(message) ); } // solhint-enable func-name-mixedcase /// @dev Reverts an encoded rich revert reason `errorData`. /// @param errorData ABI encoded error data. function rrevert(bytes memory errorData) internal pure { assembly { revert(add(errorData, 0x20), mload(errorData)) } } } pragma solidity ^0.5.9; import "./LibRichErrors.sol"; import "./LibSafeMathRichErrors.sol"; library LibSafeMath { function safeMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; if (c / a != b) { LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError( LibSafeMathRichErrors.BinOpErrorCodes.MULTIPLICATION_OVERFLOW, a, b )); } return c; } function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) { if (b == 0) { LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError( LibSafeMathRichErrors.BinOpErrorCodes.DIVISION_BY_ZERO, a, b )); } uint256 c = a / b; return c; } function safeSub(uint256 a, uint256 b) internal pure returns (uint256) { if (b > a) { LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError( LibSafeMathRichErrors.BinOpErrorCodes.SUBTRACTION_UNDERFLOW, a, b )); } return a - b; } function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; if (c < a) { LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError( LibSafeMathRichErrors.BinOpErrorCodes.ADDITION_OVERFLOW, a, b )); } return c; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } pragma solidity ^0.5.9; library LibSafeMathRichErrors { // bytes4(keccak256("Uint256BinOpError(uint8,uint256,uint256)")) bytes4 internal constant UINT256_BINOP_ERROR_SELECTOR = 0xe946c1bb; // bytes4(keccak256("Uint256DowncastError(uint8,uint256)")) bytes4 internal constant UINT256_DOWNCAST_ERROR_SELECTOR = 0xc996af7b; enum BinOpErrorCodes { ADDITION_OVERFLOW, MULTIPLICATION_OVERFLOW, SUBTRACTION_UNDERFLOW, DIVISION_BY_ZERO } enum DowncastErrorCodes { VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT32, VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT64, VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT96 } // solhint-disable func-name-mixedcase function Uint256BinOpError( BinOpErrorCodes errorCode, uint256 a, uint256 b ) internal pure returns (bytes memory) { return abi.encodeWithSelector( UINT256_BINOP_ERROR_SELECTOR, errorCode, a, b ); } function Uint256DowncastError( DowncastErrorCodes errorCode, uint256 a ) internal pure returns (bytes memory) { return abi.encodeWithSelector( UINT256_DOWNCAST_ERROR_SELECTOR, errorCode, a ); } }
Scale total allowance down by corresponding value in assetData
uint256 scaledAllowance = totalAllowance / amounts[i];
11,990,976
[ 1, 5587, 2078, 1699, 1359, 2588, 635, 4656, 460, 316, 3310, 751, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7734, 2254, 5034, 12304, 7009, 1359, 273, 2078, 7009, 1359, 342, 30980, 63, 77, 15533, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.21; /** * @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 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 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); 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 balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract DET is StandardToken { string public name = "Decentralized Ecosystem Token"; string public symbol = "DET"; uint8 public decimals = 18; uint public totalSupply = 10 ** 27; function () payable public { revert(); } function DET() public { balances[msg.sender] = totalSupply; } }
* @title Standard ERC20 token @dev Implementation of the basic standard token./
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; 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; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } 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; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } else { }
1,421,575
[ 1, 8336, 4232, 39, 3462, 1147, 225, 25379, 434, 326, 5337, 4529, 1147, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 8263, 1345, 353, 4232, 39, 3462, 16, 7651, 1345, 288, 203, 225, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 2713, 2935, 31, 203, 225, 445, 7412, 1265, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 5034, 389, 1132, 13, 1071, 1135, 261, 6430, 13, 288, 203, 565, 2583, 24899, 869, 480, 1758, 12, 20, 10019, 203, 565, 2583, 24899, 1132, 1648, 324, 26488, 63, 67, 2080, 19226, 203, 565, 2583, 24899, 1132, 1648, 2935, 63, 67, 2080, 6362, 3576, 18, 15330, 19226, 203, 565, 324, 26488, 63, 67, 2080, 65, 273, 324, 26488, 63, 67, 2080, 8009, 1717, 24899, 1132, 1769, 203, 565, 324, 26488, 63, 67, 869, 65, 273, 324, 26488, 63, 67, 869, 8009, 1289, 24899, 1132, 1769, 203, 565, 2935, 63, 67, 2080, 6362, 3576, 18, 15330, 65, 273, 2935, 63, 67, 2080, 6362, 3576, 18, 15330, 8009, 1717, 24899, 1132, 1769, 203, 565, 3626, 12279, 24899, 2080, 16, 389, 869, 16, 389, 1132, 1769, 203, 565, 327, 638, 31, 203, 225, 289, 203, 225, 445, 6617, 537, 12, 2867, 389, 87, 1302, 264, 16, 2254, 5034, 389, 1132, 13, 1071, 1135, 261, 6430, 13, 288, 203, 565, 2935, 63, 3576, 18, 15330, 6362, 67, 87, 1302, 264, 65, 273, 389, 1132, 31, 203, 565, 3626, 1716, 685, 1125, 12, 3576, 18, 15330, 16, 389, 87, 1302, 264, 16, 389, 1132, 1769, 203, 565, 327, 638, 31, 203, 225, 289, 203, 225, 445, 1699, 1359, 12, 2867, 389, 8443, 16, 1758, 389, 87, 1302, 2 ]
pragma solidity 0.4.26; // optimization enabled, runs: 500 /************** TPL Extended Jurisdiction - YES token integration ************* * This digital jurisdiction supports assigning YES token, or other contracts * * with a similar validation mechanism, as additional attribute validators. * * https://github.com/TPL-protocol/tpl-contracts/tree/yes-token-integration * * Implements an Attribute Registry https://github.com/0age/AttributeRegistry * * * * Source layout: Line # * * - library ECDSA 41 * * - library SafeMath 108 * * - library Roles 172 * * - contract PauserRole 212 * * - using Roles for Roles.Role * * - contract Pausable 257 * * - is PauserRole * * - contract Ownable 313 * * - interface AttributeRegistryInterface 386 * * - interface BasicJurisdictionInterface 440 * * - interface ExtendedJurisdictionInterface 658 * * - interface IERC20 (partial) 926 * * - ExtendedJurisdiction 934 * * - is Ownable * * - is Pausable * * - is AttributeRegistryInterface * * - is BasicJurisdictionInterface * * - is ExtendedJurisdictionInterface * * - using ECDSA for bytes32 * * - using SafeMath for uint256 * * * * https://github.com/TPL-protocol/tpl-contracts/blob/master/LICENSE.md * ******************************************************************************/ /** * @title Elliptic curve signature operations * @dev Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d * TODO Remove this library once solidity supports passing a signature to ecrecover. * See https://github.com/ethereum/solidity/issues/864 */ library ECDSA { /** * @dev Recover signer address from a message by using their signature * @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address. * @param signature bytes signature, the signature is generated using web3.eth.sign() */ function recover(bytes32 hash, bytes signature) internal pure returns (address) { bytes32 r; bytes32 s; uint8 v; // Check the signature length if (signature.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solium-disable-next-line security/no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // If the version is correct return the signer address if (v != 27 && v != 28) { return (address(0)); } else { // solium-disable-next-line arg-overflow return ecrecover(hash, v, r, s); } } /** * toEthSignedMessageHash * @dev prefix a bytes32 value with "\x19Ethereum Signed Message:" * and hash the result */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n32", hash) ); } } /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title 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(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); 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)); return role.bearer[account]; } } contract PauserRole { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private pausers; constructor() internal { _addPauser(msg.sender); } modifier onlyPauser() { require(isPauser(msg.sender)); _; } function isPauser(address account) public view returns (bool) { return pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(msg.sender); } function _addPauser(address account) internal { pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { pausers.remove(account); emit PauserRemoved(account); } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is PauserRole { event Paused(address account); event Unpaused(address account); bool private _paused; constructor() internal { _paused = false; } /** * @return true if the contract is paused, false otherwise. */ function paused() public view returns(bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(msg.sender); } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns(address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns(bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @title Attribute Registry interface. EIP-165 ID: 0x5f46473f */ interface AttributeRegistryInterface { /** * @notice Check if an attribute of the type with ID `attributeTypeID` has * been assigned to the account at `account` and is currently valid. * @param account address The account to check for a valid attribute. * @param attributeTypeID uint256 The ID of the attribute type to check for. * @return True if the attribute is assigned and valid, false otherwise. * @dev This function MUST return either true or false - i.e. calling this * function MUST NOT cause the caller to revert. */ function hasAttribute( address account, uint256 attributeTypeID ) external view returns (bool); /** * @notice Retrieve the value of the attribute of the type with ID * `attributeTypeID` on the account at `account`, assuming it is valid. * @param account address The account to check for the given attribute value. * @param attributeTypeID uint256 The ID of the attribute type to check for. * @return The attribute value if the attribute is valid, reverts otherwise. * @dev This function MUST revert if a directly preceding or subsequent * function call to `hasAttribute` with identical `account` and * `attributeTypeID` parameters would return false. */ function getAttributeValue( address account, uint256 attributeTypeID ) external view returns (uint256); /** * @notice Count the number of attribute types defined by the registry. * @return The number of available attribute types. * @dev This function MUST return a positive integer value - i.e. calling * this function MUST NOT cause the caller to revert. */ function countAttributeTypes() external view returns (uint256); /** * @notice Get the ID of the attribute type at index `index`. * @param index uint256 The index of the attribute type in question. * @return The ID of the attribute type. * @dev This function MUST revert if the provided `index` value falls outside * of the range of the value returned from a directly preceding or subsequent * function call to `countAttributeTypes`. It MUST NOT revert if the provided * `index` value falls inside said range. */ function getAttributeTypeID(uint256 index) external view returns (uint256); } /** * @title Basic TPL Jurisdiction Interface. */ interface BasicJurisdictionInterface { // declare events event AttributeTypeAdded(uint256 indexed attributeTypeID, string description); event AttributeTypeRemoved(uint256 indexed attributeTypeID); event ValidatorAdded(address indexed validator, string description); event ValidatorRemoved(address indexed validator); event ValidatorApprovalAdded( address validator, uint256 indexed attributeTypeID ); event ValidatorApprovalRemoved( address validator, uint256 indexed attributeTypeID ); event AttributeAdded( address validator, address indexed attributee, uint256 attributeTypeID, uint256 attributeValue ); event AttributeRemoved( address validator, address indexed attributee, uint256 attributeTypeID ); /** * @notice Add an attribute type with ID `ID` and description `description` to * the jurisdiction. * @param ID uint256 The ID of the attribute type to add. * @param description string A description of the attribute type. * @dev Once an attribute type is added with a given ID, the description of the * attribute type cannot be changed, even if the attribute type is removed and * added back later. */ function addAttributeType(uint256 ID, string description) external; /** * @notice Remove the attribute type with ID `ID` from the jurisdiction. * @param ID uint256 The ID of the attribute type to remove. * @dev All issued attributes of the given type will become invalid upon * removal, but will become valid again if the attribute is reinstated. */ function removeAttributeType(uint256 ID) external; /** * @notice Add account `validator` as a validator with a description * `description` who can be approved to set attributes of specific types. * @param validator address The account to assign as the validator. * @param description string A description of the validator. * @dev Note that the jurisdiction can add iteslf as a validator if desired. */ function addValidator(address validator, string description) external; /** * @notice Remove the validator at address `validator` from the jurisdiction. * @param validator address The account of the validator to remove. * @dev Any attributes issued by the validator will become invalid upon their * removal. If the validator is reinstated, those attributes will become valid * again. Any approvals to issue attributes of a given type will need to be * set from scratch in the event a validator is reinstated. */ function removeValidator(address validator) external; /** * @notice Approve the validator at address `validator` to issue attributes of * the type with ID `attributeTypeID`. * @param validator address The account of the validator to approve. * @param attributeTypeID uint256 The ID of the approved attribute type. */ function addValidatorApproval( address validator, uint256 attributeTypeID ) external; /** * @notice Deny the validator at address `validator` the ability to continue to * issue attributes of the type with ID `attributeTypeID`. * @param validator address The account of the validator with removed approval. * @param attributeTypeID uint256 The ID of the attribute type to unapprove. * @dev Any attributes of the specified type issued by the validator in * question will become invalid once the approval is removed. If the approval * is reinstated, those attributes will become valid again. The approval will * also be removed if the approved validator is removed. */ function removeValidatorApproval( address validator, uint256 attributeTypeID ) external; /** * @notice Issue an attribute of the type with ID `attributeTypeID` and a value * of `value` to `account` if `message.caller.address()` is approved validator. * @param account address The account to issue the attribute on. * @param attributeTypeID uint256 The ID of the attribute type to issue. * @param value uint256 An optional value for the issued attribute. * @dev Existing attributes of the given type on the address must be removed * in order to set a new attribute. Be aware that ownership of the account to * which the attribute is assigned may still be transferable - restricting * assignment to externally-owned accounts may partially alleviate this issue. */ function issueAttribute( address account, uint256 attributeTypeID, uint256 value ) external payable; /** * @notice Revoke the attribute of the type with ID `attributeTypeID` from * `account` if `message.caller.address()` is the issuing validator. * @param account address The account to issue the attribute on. * @param attributeTypeID uint256 The ID of the attribute type to issue. * @dev Validators may still revoke issued attributes even after they have been * removed or had their approval to issue the attribute type removed - this * enables them to address any objectionable issuances before being reinstated. */ function revokeAttribute( address account, uint256 attributeTypeID ) external; /** * @notice Determine if a validator at account `validator` is able to issue * attributes of the type with ID `attributeTypeID`. * @param validator address The account of the validator. * @param attributeTypeID uint256 The ID of the attribute type to check. * @return True if the validator can issue attributes of the given type, false * otherwise. */ function canIssueAttributeType( address validator, uint256 attributeTypeID ) external view returns (bool); /** * @notice Get a description of the attribute type with ID `attributeTypeID`. * @param attributeTypeID uint256 The ID of the attribute type to check for. * @return A description of the attribute type. */ function getAttributeTypeDescription( uint256 attributeTypeID ) external view returns (string description); /** * @notice Get a description of the validator at account `validator`. * @param validator address The account of the validator in question. * @return A description of the validator. */ function getValidatorDescription( address validator ) external view returns (string description); /** * @notice Find the validator that issued the attribute of the type with ID * `attributeTypeID` on the account at `account` and determine if the * validator is still valid. * @param account address The account that contains the attribute be checked. * @param attributeTypeID uint256 The ID of the attribute type in question. * @return The validator and the current status of the validator as it * pertains to the attribute type in question. * @dev if no attribute of the given attribute type exists on the account, the * function will return (address(0), false). */ function getAttributeValidator( address account, uint256 attributeTypeID ) external view returns (address validator, bool isStillValid); /** * @notice Count the number of attribute types defined by the jurisdiction. * @return The number of available attribute types. */ function countAttributeTypes() external view returns (uint256); /** * @notice Get the ID of the attribute type at index `index`. * @param index uint256 The index of the attribute type in question. * @return The ID of the attribute type. */ function getAttributeTypeID(uint256 index) external view returns (uint256); /** * @notice Get the IDs of all available attribute types on the jurisdiction. * @return A dynamic array containing all available attribute type IDs. */ function getAttributeTypeIDs() external view returns (uint256[]); /** * @notice Count the number of validators defined by the jurisdiction. * @return The number of defined validators. */ function countValidators() external view returns (uint256); /** * @notice Get the account of the validator at index `index`. * @param index uint256 The index of the validator in question. * @return The account of the validator. */ function getValidator(uint256 index) external view returns (address); /** * @notice Get the accounts of all available validators on the jurisdiction. * @return A dynamic array containing all available validator accounts. */ function getValidators() external view returns (address[]); } /** * @title Extended TPL Jurisdiction Interface. * @dev this extends BasicJurisdictionInterface for additional functionality. */ interface ExtendedJurisdictionInterface { // declare events (NOTE: consider which fields should be indexed) event ValidatorSigningKeyModified( address indexed validator, address newSigningKey ); event StakeAllocated( address indexed staker, uint256 indexed attribute, uint256 amount ); event StakeRefunded( address indexed staker, uint256 indexed attribute, uint256 amount ); event FeePaid( address indexed recipient, address indexed payee, uint256 indexed attribute, uint256 amount ); event TransactionRebatePaid( address indexed submitter, address indexed payee, uint256 indexed attribute, uint256 amount ); /** * @notice Add a restricted attribute type with ID `ID` and description * `description` to the jurisdiction. Restricted attribute types can only be * removed by the issuing validator or the jurisdiction. * @param ID uint256 The ID of the restricted attribute type to add. * @param description string A description of the restricted attribute type. * @dev Once an attribute type is added with a given ID, the description or the * restricted status of the attribute type cannot be changed, even if the * attribute type is removed and added back later. */ function addRestrictedAttributeType(uint256 ID, string description) external; /** * @notice Enable or disable a restriction for a given attribute type ID `ID` * that prevents attributes of the given type from being set by operators based * on the provided value for `onlyPersonal`. * @param ID uint256 The attribute type ID in question. * @param onlyPersonal bool Whether the address may only be set personally. */ function setAttributeTypeOnlyPersonal(uint256 ID, bool onlyPersonal) external; /** * @notice Set a secondary source for a given attribute type ID `ID`, with an * address `registry` of the secondary source in question and a given * `sourceAttributeTypeID` for attribute type ID to check on the secondary * source. The secondary source will only be checked for the given attribute in * cases where no attribute of the given attribute type ID is assigned locally. * @param ID uint256 The attribute type ID to set the secondary source for. * @param attributeRegistry address The secondary attribute registry account. * @param sourceAttributeTypeID uint256 The attribute type ID on the secondary * source to check. * @dev To remove a secondary source on an attribute type, the registry address * should be set to the null address. */ function setAttributeTypeSecondarySource( uint256 ID, address attributeRegistry, uint256 sourceAttributeTypeID ) external; /** * @notice Set a minimum required stake for a given attribute type ID `ID` and * an amount of `stake`, to be locked in the jurisdiction upon assignment of * attributes of the given type. The stake will be applied toward a transaction * rebate in the event the attribute is revoked, with the remainder returned to * the staker. * @param ID uint256 The attribute type ID to set a minimum required stake for. * @param minimumRequiredStake uint256 The minimum required funds to lock up. * @dev To remove a stake requirement from an attribute type, the stake amount * should be set to 0. */ function setAttributeTypeMinimumRequiredStake( uint256 ID, uint256 minimumRequiredStake ) external; /** * @notice Set a required fee for a given attribute type ID `ID` and an amount * of `fee`, to be paid to the owner of the jurisdiction upon assignment of * attributes of the given type. * @param ID uint256 The attribute type ID to set the required fee for. * @param fee uint256 The required fee amount to be paid upon assignment. * @dev To remove a fee requirement from an attribute type, the fee amount * should be set to 0. */ function setAttributeTypeJurisdictionFee(uint256 ID, uint256 fee) external; /** * @notice Set the public address associated with a validator signing key, used * to sign off-chain attribute approvals, as `newSigningKey`. * @param newSigningKey address The address associated with signing key to set. */ function setValidatorSigningKey(address newSigningKey) external; /** * @notice Add an attribute of the type with ID `attributeTypeID`, an attribute * value of `value`, and an associated validator fee of `validatorFee` to * account of `msg.sender` by passing in a signed attribute approval with * signature `signature`. * @param attributeTypeID uint256 The ID of the attribute type to add. * @param value uint256 The value for the attribute to add. * @param validatorFee uint256 The fee to be paid to the issuing validator. * @param signature bytes The signature from the validator attribute approval. */ function addAttribute( uint256 attributeTypeID, uint256 value, uint256 validatorFee, bytes signature ) external payable; /** * @notice Remove an attribute of the type with ID `attributeTypeID` from * account of `msg.sender`. * @param attributeTypeID uint256 The ID of the attribute type to remove. */ function removeAttribute(uint256 attributeTypeID) external; /** * @notice Add an attribute of the type with ID `attributeTypeID`, an attribute * value of `value`, and an associated validator fee of `validatorFee` to * account `account` by passing in a signed attribute approval with signature * `signature`. * @param account address The account to add the attribute to. * @param attributeTypeID uint256 The ID of the attribute type to add. * @param value uint256 The value for the attribute to add. * @param validatorFee uint256 The fee to be paid to the issuing validator. * @param signature bytes The signature from the validator attribute approval. * @dev Restricted attribute types can only be removed by issuing validators or * the jurisdiction itself. */ function addAttributeFor( address account, uint256 attributeTypeID, uint256 value, uint256 validatorFee, bytes signature ) external payable; /** * @notice Remove an attribute of the type with ID `attributeTypeID` from * account of `account`. * @param account address The account to remove the attribute from. * @param attributeTypeID uint256 The ID of the attribute type to remove. * @dev Restricted attribute types can only be removed by issuing validators or * the jurisdiction itself. */ function removeAttributeFor(address account, uint256 attributeTypeID) external; /** * @notice Invalidate a signed attribute approval before it has been set by * supplying the hash of the approval `hash` and the signature `signature`. * @param hash bytes32 The hash of the attribute approval. * @param signature bytes The hash's signature, resolving to the signing key. * @dev Attribute approvals can only be removed by issuing validators or the * jurisdiction itself. */ function invalidateAttributeApproval( bytes32 hash, bytes signature ) external; /** * @notice Get the hash of a given attribute approval. * @param account address The account specified by the attribute approval. * @param operator address An optional account permitted to submit approval. * @param attributeTypeID uint256 The ID of the attribute type in question. * @param value uint256 The value of the attribute in the approval. * @param fundsRequired uint256 The amount to be included with the approval. * @param validatorFee uint256 The required fee to be paid to the validator. * @return The hash of the attribute approval. */ function getAttributeApprovalHash( address account, address operator, uint256 attributeTypeID, uint256 value, uint256 fundsRequired, uint256 validatorFee ) external view returns (bytes32 hash); /** * @notice Check if a given signed attribute approval is currently valid when * submitted directly by `msg.sender`. * @param attributeTypeID uint256 The ID of the attribute type in question. * @param value uint256 The value of the attribute in the approval. * @param fundsRequired uint256 The amount to be included with the approval. * @param validatorFee uint256 The required fee to be paid to the validator. * @param signature bytes The attribute approval signature, based on a hash of * the other parameters and the submitting account. * @return True if the approval is currently valid, false otherwise. */ function canAddAttribute( uint256 attributeTypeID, uint256 value, uint256 fundsRequired, uint256 validatorFee, bytes signature ) external view returns (bool); /** * @notice Check if a given signed attribute approval is currently valid for a * given account when submitted by the operator at `msg.sender`. * @param account address The account specified by the attribute approval. * @param attributeTypeID uint256 The ID of the attribute type in question. * @param value uint256 The value of the attribute in the approval. * @param fundsRequired uint256 The amount to be included with the approval. * @param validatorFee uint256 The required fee to be paid to the validator. * @param signature bytes The attribute approval signature, based on a hash of * the other parameters and the submitting account. * @return True if the approval is currently valid, false otherwise. */ function canAddAttributeFor( address account, uint256 attributeTypeID, uint256 value, uint256 fundsRequired, uint256 validatorFee, bytes signature ) external view returns (bool); /** * @notice Get comprehensive information on an attribute type with ID * `attributeTypeID`. * @param attributeTypeID uint256 The attribute type ID in question. * @return Information on the attribute type in question. */ function getAttributeTypeInformation( uint256 attributeTypeID ) external view returns ( string description, bool isRestricted, bool isOnlyPersonal, address secondarySource, uint256 secondaryId, uint256 minimumRequiredStake, uint256 jurisdictionFee ); /** * @notice Get a validator's signing key. * @param validator address The account of the validator. * @return The account referencing the public component of the signing key. */ function getValidatorSigningKey( address validator ) external view returns ( address signingKey ); } /** * @title Interface for checking attribute assignment on YES token and for token * recovery. */ interface IERC20 { function balanceOf(address) external view returns (uint256); function transfer(address, uint256) external returns (bool); } /** * @title An extended TPL jurisdiction for assigning attributes to addresses. */ contract ExtendedJurisdiction is Ownable, Pausable, AttributeRegistryInterface, BasicJurisdictionInterface, ExtendedJurisdictionInterface { using ECDSA for bytes32; using SafeMath for uint256; // validators are entities who can add or authorize addition of new attributes struct Validator { bool exists; uint256 index; // NOTE: consider use of uint88 to pack struct address signingKey; string description; } // attributes are properties that validators associate with specific addresses struct IssuedAttribute { bool exists; bool setPersonally; address operator; address validator; uint256 value; uint256 stake; } // attributes also have associated type - metadata common to each attribute struct AttributeType { bool exists; bool restricted; bool onlyPersonal; uint256 index; // NOTE: consider use of uint72 to pack struct address secondarySource; uint256 secondaryAttributeTypeID; uint256 minimumStake; uint256 jurisdictionFee; string description; mapping(address => bool) approvedValidators; } // top-level information about attribute types is held in a mapping of structs mapping(uint256 => AttributeType) private _attributeTypes; // the jurisdiction retains a mapping of addresses with assigned attributes mapping(address => mapping(uint256 => IssuedAttribute)) private _issuedAttributes; // there is also a mapping to identify all approved validators and their keys mapping(address => Validator) private _validators; // each registered signing key maps back to a specific validator mapping(address => address) private _signingKeys; // once attribute types are assigned to an ID, they cannot be modified mapping(uint256 => bytes32) private _attributeTypeHashes; // submitted attribute approvals are retained to prevent reuse after removal mapping(bytes32 => bool) private _invalidAttributeApprovalHashes; // attribute approvals by validator are held in a mapping mapping(address => uint256[]) private _validatorApprovals; // attribute approval index by validator is tracked as well mapping(address => mapping(uint256 => uint256)) private _validatorApprovalsIndex; // IDs for all supplied attributes are held in an array (enables enumeration) uint256[] private _attributeIDs; // addresses for all designated validators are also held in an array address[] private _validatorAccounts; // track any recoverable funds locked in the contract uint256 private _recoverableFunds; /** * @notice Add an attribute type with ID `ID` and description `description` to * the jurisdiction. * @param ID uint256 The ID of the attribute type to add. * @param description string A description of the attribute type. * @dev Once an attribute type is added with a given ID, the description of the * attribute type cannot be changed, even if the attribute type is removed and * added back later. */ function addAttributeType( uint256 ID, string description ) external onlyOwner whenNotPaused { // prevent existing attributes with the same id from being overwritten require( !isAttributeType(ID), "an attribute type with the provided ID already exists" ); // calculate a hash of the attribute type based on the type's properties bytes32 hash = keccak256( abi.encodePacked( ID, false, description ) ); // store hash if attribute type is the first one registered with provided ID if (_attributeTypeHashes[ID] == bytes32(0)) { _attributeTypeHashes[ID] = hash; } // prevent addition if different attribute type with the same ID has existed require( hash == _attributeTypeHashes[ID], "attribute type properties must match initial properties assigned to ID" ); // set the attribute mapping, assigning the index as the end of attributeID _attributeTypes[ID] = AttributeType({ exists: true, restricted: false, // when true: users can't remove attribute onlyPersonal: false, // when true: operators can't add attribute index: _attributeIDs.length, secondarySource: address(0), // the address of a remote registry secondaryAttributeTypeID: uint256(0), // the attribute type id to query minimumStake: uint256(0), // when > 0: users must stake ether to set jurisdictionFee: uint256(0), description: description // NOTE: no approvedValidators variable declaration - must be added later }); // add the attribute type id to the end of the attributeID array _attributeIDs.push(ID); // log the addition of the attribute type emit AttributeTypeAdded(ID, description); } /** * @notice Add a restricted attribute type with ID `ID` and description * `description` to the jurisdiction. Restricted attribute types can only be * removed by the issuing validator or the jurisdiction. * @param ID uint256 The ID of the restricted attribute type to add. * @param description string A description of the restricted attribute type. * @dev Once an attribute type is added with a given ID, the description or the * restricted status of the attribute type cannot be changed, even if the * attribute type is removed and added back later. */ function addRestrictedAttributeType( uint256 ID, string description ) external onlyOwner whenNotPaused { // prevent existing attributes with the same id from being overwritten require( !isAttributeType(ID), "an attribute type with the provided ID already exists" ); // calculate a hash of the attribute type based on the type's properties bytes32 hash = keccak256( abi.encodePacked( ID, true, description ) ); // store hash if attribute type is the first one registered with provided ID if (_attributeTypeHashes[ID] == bytes32(0)) { _attributeTypeHashes[ID] = hash; } // prevent addition if different attribute type with the same ID has existed require( hash == _attributeTypeHashes[ID], "attribute type properties must match initial properties assigned to ID" ); // set the attribute mapping, assigning the index as the end of attributeID _attributeTypes[ID] = AttributeType({ exists: true, restricted: true, // when true: users can't remove attribute onlyPersonal: false, // when true: operators can't add attribute index: _attributeIDs.length, secondarySource: address(0), // the address of a remote registry secondaryAttributeTypeID: uint256(0), // the attribute type id to query minimumStake: uint256(0), // when > 0: users must stake ether to set jurisdictionFee: uint256(0), description: description // NOTE: no approvedValidators variable declaration - must be added later }); // add the attribute type id to the end of the attributeID array _attributeIDs.push(ID); // log the addition of the attribute type emit AttributeTypeAdded(ID, description); } /** * @notice Enable or disable a restriction for a given attribute type ID `ID` * that prevents attributes of the given type from being set by operators based * on the provided value for `onlyPersonal`. * @param ID uint256 The attribute type ID in question. * @param onlyPersonal bool Whether the address may only be set personally. */ function setAttributeTypeOnlyPersonal(uint256 ID, bool onlyPersonal) external { // if the attribute type ID does not exist, there is nothing to remove require( isAttributeType(ID), "unable to set to only personal, no attribute type with the provided ID" ); // modify the attribute type in the mapping _attributeTypes[ID].onlyPersonal = onlyPersonal; } /** * @notice Set a secondary source for a given attribute type ID `ID`, with an * address `registry` of the secondary source in question and a given * `sourceAttributeTypeID` for attribute type ID to check on the secondary * source. The secondary source will only be checked for the given attribute in * cases where no attribute of the given attribute type ID is assigned locally. * @param ID uint256 The attribute type ID to set the secondary source for. * @param attributeRegistry address The secondary attribute registry account. * @param sourceAttributeTypeID uint256 The attribute type ID on the secondary * source to check. * @dev To remove a secondary source on an attribute type, the registry address * should be set to the null address. */ function setAttributeTypeSecondarySource( uint256 ID, address attributeRegistry, uint256 sourceAttributeTypeID ) external { // if the attribute type ID does not exist, there is nothing to remove require( isAttributeType(ID), "unable to set secondary source, no attribute type with the provided ID" ); // modify the attribute type in the mapping _attributeTypes[ID].secondarySource = attributeRegistry; _attributeTypes[ID].secondaryAttributeTypeID = sourceAttributeTypeID; } /** * @notice Set a minimum required stake for a given attribute type ID `ID` and * an amount of `stake`, to be locked in the jurisdiction upon assignment of * attributes of the given type. The stake will be applied toward a transaction * rebate in the event the attribute is revoked, with the remainder returned to * the staker. * @param ID uint256 The attribute type ID to set a minimum required stake for. * @param minimumRequiredStake uint256 The minimum required funds to lock up. * @dev To remove a stake requirement from an attribute type, the stake amount * should be set to 0. */ function setAttributeTypeMinimumRequiredStake( uint256 ID, uint256 minimumRequiredStake ) external { // if the attribute type ID does not exist, there is nothing to remove require( isAttributeType(ID), "unable to set minimum stake, no attribute type with the provided ID" ); // modify the attribute type in the mapping _attributeTypes[ID].minimumStake = minimumRequiredStake; } /** * @notice Set a required fee for a given attribute type ID `ID` and an amount * of `fee`, to be paid to the owner of the jurisdiction upon assignment of * attributes of the given type. * @param ID uint256 The attribute type ID to set the required fee for. * @param fee uint256 The required fee amount to be paid upon assignment. * @dev To remove a fee requirement from an attribute type, the fee amount * should be set to 0. */ function setAttributeTypeJurisdictionFee(uint256 ID, uint256 fee) external { // if the attribute type ID does not exist, there is nothing to remove require( isAttributeType(ID), "unable to set fee, no attribute type with the provided ID" ); // modify the attribute type in the mapping _attributeTypes[ID].jurisdictionFee = fee; } /** * @notice Remove the attribute type with ID `ID` from the jurisdiction. * @param ID uint256 The ID of the attribute type to remove. * @dev All issued attributes of the given type will become invalid upon * removal, but will become valid again if the attribute is reinstated. */ function removeAttributeType(uint256 ID) external onlyOwner whenNotPaused { // if the attribute type ID does not exist, there is nothing to remove require( isAttributeType(ID), "unable to remove, no attribute type with the provided ID" ); // get the attribute ID at the last index of the array uint256 lastAttributeID = _attributeIDs[_attributeIDs.length.sub(1)]; // set the attributeID at attribute-to-delete.index to the last attribute ID _attributeIDs[_attributeTypes[ID].index] = lastAttributeID; // update the index of the attribute type that was moved _attributeTypes[lastAttributeID].index = _attributeTypes[ID].index; // remove the (now duplicate) attribute ID at the end by trimming the array _attributeIDs.length--; // delete the attribute type's record from the mapping delete _attributeTypes[ID]; // log the removal of the attribute type emit AttributeTypeRemoved(ID); } /** * @notice Add account `validator` as a validator with a description * `description` who can be approved to set attributes of specific types. * @param validator address The account to assign as the validator. * @param description string A description of the validator. * @dev Note that the jurisdiction can add iteslf as a validator if desired. */ function addValidator( address validator, string description ) external onlyOwner whenNotPaused { // check that an empty address was not provided by mistake require(validator != address(0), "must supply a valid address"); // prevent existing validators from being overwritten require( !isValidator(validator), "a validator with the provided address already exists" ); // prevent duplicate signing keys from being created require( _signingKeys[validator] == address(0), "a signing key matching the provided address already exists" ); // create a record for the validator _validators[validator] = Validator({ exists: true, index: _validatorAccounts.length, signingKey: validator, // NOTE: this will be initially set to same address description: description }); // set the initial signing key (the validator's address) resolving to itself _signingKeys[validator] = validator; // add the validator to the end of the _validatorAccounts array _validatorAccounts.push(validator); // log the addition of the new validator emit ValidatorAdded(validator, description); } /** * @notice Remove the validator at address `validator` from the jurisdiction. * @param validator address The account of the validator to remove. * @dev Any attributes issued by the validator will become invalid upon their * removal. If the validator is reinstated, those attributes will become valid * again. Any approvals to issue attributes of a given type will need to be * set from scratch in the event a validator is reinstated. */ function removeValidator(address validator) external onlyOwner whenNotPaused { // check that a validator exists at the provided address require( isValidator(validator), "unable to remove, no validator located at the provided address" ); // first, start removing validator approvals until gas is exhausted while (_validatorApprovals[validator].length > 0 && gasleft() > 25000) { // locate the index of last attribute ID in the validator approval group uint256 lastIndex = _validatorApprovals[validator].length.sub(1); // locate the validator approval to be removed uint256 targetApproval = _validatorApprovals[validator][lastIndex]; // remove the record of the approval from the associated attribute type delete _attributeTypes[targetApproval].approvedValidators[validator]; // remove the record of the index of the approval delete _validatorApprovalsIndex[validator][targetApproval]; // drop the last attribute ID from the validator approval group _validatorApprovals[validator].length--; } // require that all approvals were successfully removed require( _validatorApprovals[validator].length == 0, "Cannot remove validator - first remove any existing validator approvals" ); // get the validator address at the last index of the array address lastAccount = _validatorAccounts[_validatorAccounts.length.sub(1)]; // set the address at validator-to-delete.index to last validator address _validatorAccounts[_validators[validator].index] = lastAccount; // update the index of the attribute type that was moved _validators[lastAccount].index = _validators[validator].index; // remove (duplicate) validator address at the end by trimming the array _validatorAccounts.length--; // remove the validator's signing key from its mapping delete _signingKeys[_validators[validator].signingKey]; // remove the validator record delete _validators[validator]; // log the removal of the validator emit ValidatorRemoved(validator); } /** * @notice Approve the validator at address `validator` to issue attributes of * the type with ID `attributeTypeID`. * @param validator address The account of the validator to approve. * @param attributeTypeID uint256 The ID of the approved attribute type. */ function addValidatorApproval( address validator, uint256 attributeTypeID ) external onlyOwner whenNotPaused { // check that the attribute is predefined and that the validator exists require( isValidator(validator) && isAttributeType(attributeTypeID), "must specify both a valid attribute and an available validator" ); // check that the validator is not already approved require( !_attributeTypes[attributeTypeID].approvedValidators[validator], "validator is already approved on the provided attribute" ); // set the validator approval status on the attribute _attributeTypes[attributeTypeID].approvedValidators[validator] = true; // add the record of the index of the validator approval to be added uint256 index = _validatorApprovals[validator].length; _validatorApprovalsIndex[validator][attributeTypeID] = index; // include the attribute type in the validator approval mapping _validatorApprovals[validator].push(attributeTypeID); // log the addition of the validator's attribute type approval emit ValidatorApprovalAdded(validator, attributeTypeID); } /** * @notice Deny the validator at address `validator` the ability to continue to * issue attributes of the type with ID `attributeTypeID`. * @param validator address The account of the validator with removed approval. * @param attributeTypeID uint256 The ID of the attribute type to unapprove. * @dev Any attributes of the specified type issued by the validator in * question will become invalid once the approval is removed. If the approval * is reinstated, those attributes will become valid again. The approval will * also be removed if the approved validator is removed. */ function removeValidatorApproval( address validator, uint256 attributeTypeID ) external onlyOwner whenNotPaused { // check that the attribute is predefined and that the validator exists require( canValidate(validator, attributeTypeID), "unable to remove validator approval, attribute is already unapproved" ); // remove the validator approval status from the attribute delete _attributeTypes[attributeTypeID].approvedValidators[validator]; // locate the index of the last validator approval uint256 lastIndex = _validatorApprovals[validator].length.sub(1); // locate the last attribute ID in the validator approval group uint256 lastAttributeID = _validatorApprovals[validator][lastIndex]; // locate the index of the validator approval to be removed uint256 index = _validatorApprovalsIndex[validator][attributeTypeID]; // replace the validator approval with the last approval in the array _validatorApprovals[validator][index] = lastAttributeID; // drop the last attribute ID from the validator approval group _validatorApprovals[validator].length--; // update the record of the index of the swapped-in approval _validatorApprovalsIndex[validator][lastAttributeID] = index; // remove the record of the index of the removed approval delete _validatorApprovalsIndex[validator][attributeTypeID]; // log the removal of the validator's attribute type approval emit ValidatorApprovalRemoved(validator, attributeTypeID); } /** * @notice Set the public address associated with a validator signing key, used * to sign off-chain attribute approvals, as `newSigningKey`. * @param newSigningKey address The address associated with signing key to set. * @dev Consider having the validator submit a signed proof demonstrating that * the provided signing key is indeed a signing key in their control - this * helps mitigate the fringe attack vector where a validator could set the * address of another validator candidate (especially in the case of a deployed * smart contract) as their "signing key" in order to block them from being * added to the jurisdiction (due to the required property of signing keys * being unique, coupled with the fact that new validators are set up with * their address as the default initial signing key). */ function setValidatorSigningKey(address newSigningKey) external { require( isValidator(msg.sender), "only validators may modify validator signing keys"); // prevent duplicate signing keys from being created require( _signingKeys[newSigningKey] == address(0), "a signing key matching the provided address already exists" ); // remove validator address as the resolved value for the old key delete _signingKeys[_validators[msg.sender].signingKey]; // set the signing key to the new value _validators[msg.sender].signingKey = newSigningKey; // add validator address as the resolved value for the new key _signingKeys[newSigningKey] = msg.sender; // log the modification of the signing key emit ValidatorSigningKeyModified(msg.sender, newSigningKey); } /** * @notice Issue an attribute of the type with ID `attributeTypeID` and a value * of `value` to `account` if `message.caller.address()` is approved validator. * @param account address The account to issue the attribute on. * @param attributeTypeID uint256 The ID of the attribute type to issue. * @param value uint256 An optional value for the issued attribute. * @dev Existing attributes of the given type on the address must be removed * in order to set a new attribute. Be aware that ownership of the account to * which the attribute is assigned may still be transferable - restricting * assignment to externally-owned accounts may partially alleviate this issue. */ function issueAttribute( address account, uint256 attributeTypeID, uint256 value ) external payable whenNotPaused { require( canValidate(msg.sender, attributeTypeID), "only approved validators may assign attributes of this type" ); require( !_issuedAttributes[account][attributeTypeID].exists, "duplicate attributes are not supported, remove existing attribute first" ); // retrieve required minimum stake and jurisdiction fees on attribute type uint256 minimumStake = _attributeTypes[attributeTypeID].minimumStake; uint256 jurisdictionFee = _attributeTypes[attributeTypeID].jurisdictionFee; uint256 stake = msg.value.sub(jurisdictionFee); require( stake >= minimumStake, "attribute requires a greater value than is currently provided" ); // store attribute value and amount of ether staked in correct scope _issuedAttributes[account][attributeTypeID] = IssuedAttribute({ exists: true, setPersonally: false, operator: address(0), validator: msg.sender, value: value, stake: stake }); // log the addition of the attribute emit AttributeAdded(msg.sender, account, attributeTypeID, value); // log allocation of staked funds to the attribute if applicable if (stake > 0) { emit StakeAllocated(msg.sender, attributeTypeID, stake); } // pay jurisdiction fee to the owner of the jurisdiction if applicable if (jurisdictionFee > 0) { // NOTE: send is chosen over transfer to prevent cases where a improperly // configured fallback function could block addition of an attribute if (owner().send(jurisdictionFee)) { emit FeePaid(owner(), msg.sender, attributeTypeID, jurisdictionFee); } else { _recoverableFunds = _recoverableFunds.add(jurisdictionFee); } } } /** * @notice Revoke the attribute of the type with ID `attributeTypeID` from * `account` if `message.caller.address()` is the issuing validator. * @param account address The account to issue the attribute on. * @param attributeTypeID uint256 The ID of the attribute type to issue. * @dev Validators may still revoke issued attributes even after they have been * removed or had their approval to issue the attribute type removed - this * enables them to address any objectionable issuances before being reinstated. */ function revokeAttribute( address account, uint256 attributeTypeID ) external whenNotPaused { // ensure that an attribute with the given account and attribute exists require( _issuedAttributes[account][attributeTypeID].exists, "only existing attributes may be removed" ); // determine the assigned validator on the user attribute address validator = _issuedAttributes[account][attributeTypeID].validator; // caller must be either the jurisdiction owner or the assigning validator require( msg.sender == validator || msg.sender == owner(), "only jurisdiction or issuing validators may revoke arbitrary attributes" ); // determine if attribute has any stake in order to refund transaction fee uint256 stake = _issuedAttributes[account][attributeTypeID].stake; // determine the correct address to refund the staked amount to address refundAddress; if (_issuedAttributes[account][attributeTypeID].setPersonally) { refundAddress = account; } else { address operator = _issuedAttributes[account][attributeTypeID].operator; if (operator == address(0)) { refundAddress = validator; } else { refundAddress = operator; } } // remove the attribute from the designated user account delete _issuedAttributes[account][attributeTypeID]; // log the removal of the attribute emit AttributeRemoved(validator, account, attributeTypeID); // pay out any refunds and return the excess stake to the user if (stake > 0 && address(this).balance >= stake) { // NOTE: send is chosen over transfer to prevent cases where a malicious // fallback function could forcibly block an attribute's removal. Another // option is to allow a user to pull the staked amount after the removal. // NOTE: refine transaction rebate gas calculation! Setting this value too // high gives validators the incentive to revoke valid attributes. Simply // checking against gasLeft() & adding the final gas usage won't give the // correct transaction cost, as freeing space refunds gas upon completion. uint256 transactionGas = 37700; // <--- WARNING: THIS IS APPROXIMATE uint256 transactionCost = transactionGas.mul(tx.gasprice); // if stake exceeds allocated transaction cost, refund user the difference if (stake > transactionCost) { // refund the excess stake to the address that contributed the funds if (refundAddress.send(stake.sub(transactionCost))) { emit StakeRefunded( refundAddress, attributeTypeID, stake.sub(transactionCost) ); } else { _recoverableFunds = _recoverableFunds.add(stake.sub(transactionCost)); } // emit an event for the payment of the transaction rebate emit TransactionRebatePaid( tx.origin, refundAddress, attributeTypeID, transactionCost ); // refund the cost of the transaction to the trasaction submitter tx.origin.transfer(transactionCost); // otherwise, allocate entire stake to partially refunding the transaction } else { // emit an event for the payment of the partial transaction rebate emit TransactionRebatePaid( tx.origin, refundAddress, attributeTypeID, stake ); // refund the partial cost of the transaction to trasaction submitter tx.origin.transfer(stake); } } } /** * @notice Add an attribute of the type with ID `attributeTypeID`, an attribute * value of `value`, and an associated validator fee of `validatorFee` to * account of `msg.sender` by passing in a signed attribute approval with * signature `signature`. * @param attributeTypeID uint256 The ID of the attribute type to add. * @param value uint256 The value for the attribute to add. * @param validatorFee uint256 The fee to be paid to the issuing validator. * @param signature bytes The signature from the validator attribute approval. */ function addAttribute( uint256 attributeTypeID, uint256 value, uint256 validatorFee, bytes signature ) external payable { // NOTE: determine best course of action when the attribute already exists // NOTE: consider utilizing bytes32 type for attributes and values // NOTE: does not currently support an extraData parameter, consider adding // NOTE: if msg.sender is a proxy contract, its ownership may be transferred // at will, circumventing any token transfer restrictions. Restricting usage // to only externally owned accounts may partially alleviate this concern. // NOTE: cosider including a salt (or better, nonce) parameter so that when // a user adds an attribute, then it gets revoked, the user can get a new // signature from the validator and renew the attribute using that. The main // downside is that everyone will have to keep track of the extra parameter. // Another solution is to just modifiy the required stake or fee amount. require( !_issuedAttributes[msg.sender][attributeTypeID].exists, "duplicate attributes are not supported, remove existing attribute first" ); // retrieve required minimum stake and jurisdiction fees on attribute type uint256 minimumStake = _attributeTypes[attributeTypeID].minimumStake; uint256 jurisdictionFee = _attributeTypes[attributeTypeID].jurisdictionFee; uint256 stake = msg.value.sub(validatorFee).sub(jurisdictionFee); require( stake >= minimumStake, "attribute requires a greater value than is currently provided" ); // signed data hash constructed according to EIP-191-0x45 to prevent replays bytes32 hash = keccak256( abi.encodePacked( address(this), msg.sender, address(0), msg.value, validatorFee, attributeTypeID, value ) ); require( !_invalidAttributeApprovalHashes[hash], "signed attribute approvals from validators may not be reused" ); // extract the key used to sign the message hash address signingKey = hash.toEthSignedMessageHash().recover(signature); // retrieve the validator who controls the extracted key address validator = _signingKeys[signingKey]; require( canValidate(validator, attributeTypeID), "signature does not match an approved validator for given attribute type" ); // store attribute value and amount of ether staked in correct scope _issuedAttributes[msg.sender][attributeTypeID] = IssuedAttribute({ exists: true, setPersonally: true, operator: address(0), validator: validator, value: value, stake: stake // NOTE: no extraData included }); // flag the signed approval as invalid once it's been used to set attribute _invalidAttributeApprovalHashes[hash] = true; // log the addition of the attribute emit AttributeAdded(validator, msg.sender, attributeTypeID, value); // log allocation of staked funds to the attribute if applicable if (stake > 0) { emit StakeAllocated(msg.sender, attributeTypeID, stake); } // pay jurisdiction fee to the owner of the jurisdiction if applicable if (jurisdictionFee > 0) { // NOTE: send is chosen over transfer to prevent cases where a improperly // configured fallback function could block addition of an attribute if (owner().send(jurisdictionFee)) { emit FeePaid(owner(), msg.sender, attributeTypeID, jurisdictionFee); } else { _recoverableFunds = _recoverableFunds.add(jurisdictionFee); } } // pay validator fee to the issuing validator's address if applicable if (validatorFee > 0) { // NOTE: send is chosen over transfer to prevent cases where a improperly // configured fallback function could block addition of an attribute if (validator.send(validatorFee)) { emit FeePaid(validator, msg.sender, attributeTypeID, validatorFee); } else { _recoverableFunds = _recoverableFunds.add(validatorFee); } } } /** * @notice Remove an attribute of the type with ID `attributeTypeID` from * account of `msg.sender`. * @param attributeTypeID uint256 The ID of the attribute type to remove. */ function removeAttribute(uint256 attributeTypeID) external { // attributes may only be removed by the user if they are not restricted require( !_attributeTypes[attributeTypeID].restricted, "only jurisdiction or issuing validator may remove a restricted attribute" ); require( _issuedAttributes[msg.sender][attributeTypeID].exists, "only existing attributes may be removed" ); // determine the assigned validator on the user attribute address validator = _issuedAttributes[msg.sender][attributeTypeID].validator; // determine if the attribute has a staked value uint256 stake = _issuedAttributes[msg.sender][attributeTypeID].stake; // determine the correct address to refund the staked amount to address refundAddress; if (_issuedAttributes[msg.sender][attributeTypeID].setPersonally) { refundAddress = msg.sender; } else { address operator = _issuedAttributes[msg.sender][attributeTypeID].operator; if (operator == address(0)) { refundAddress = validator; } else { refundAddress = operator; } } // remove the attribute from the user address delete _issuedAttributes[msg.sender][attributeTypeID]; // log the removal of the attribute emit AttributeRemoved(validator, msg.sender, attributeTypeID); // if the attribute has any staked balance, refund it to the user if (stake > 0 && address(this).balance >= stake) { // NOTE: send is chosen over transfer to prevent cases where a malicious // fallback function could forcibly block an attribute's removal if (refundAddress.send(stake)) { emit StakeRefunded(refundAddress, attributeTypeID, stake); } else { _recoverableFunds = _recoverableFunds.add(stake); } } } /** * @notice Add an attribute of the type with ID `attributeTypeID`, an attribute * value of `value`, and an associated validator fee of `validatorFee` to * account `account` by passing in a signed attribute approval with signature * `signature`. * @param account address The account to add the attribute to. * @param attributeTypeID uint256 The ID of the attribute type to add. * @param value uint256 The value for the attribute to add. * @param validatorFee uint256 The fee to be paid to the issuing validator. * @param signature bytes The signature from the validator attribute approval. * @dev Restricted attribute types can only be removed by issuing validators or * the jurisdiction itself. */ function addAttributeFor( address account, uint256 attributeTypeID, uint256 value, uint256 validatorFee, bytes signature ) external payable { // NOTE: determine best course of action when the attribute already exists // NOTE: consider utilizing bytes32 type for attributes and values // NOTE: does not currently support an extraData parameter, consider adding // NOTE: if msg.sender is a proxy contract, its ownership may be transferred // at will, circumventing any token transfer restrictions. Restricting usage // to only externally owned accounts may partially alleviate this concern. // NOTE: consider including a salt (or better, nonce) parameter so that when // a user adds an attribute, then it gets revoked, the user can get a new // signature from the validator and renew the attribute using that. The main // downside is that everyone will have to keep track of the extra parameter. // Another solution is to just modifiy the required stake or fee amount. // attributes may only be added by a third party if onlyPersonal is false require( !_attributeTypes[attributeTypeID].onlyPersonal, "only operatable attributes may be added on behalf of another address" ); require( !_issuedAttributes[account][attributeTypeID].exists, "duplicate attributes are not supported, remove existing attribute first" ); // retrieve required minimum stake and jurisdiction fees on attribute type uint256 minimumStake = _attributeTypes[attributeTypeID].minimumStake; uint256 jurisdictionFee = _attributeTypes[attributeTypeID].jurisdictionFee; uint256 stake = msg.value.sub(validatorFee).sub(jurisdictionFee); require( stake >= minimumStake, "attribute requires a greater value than is currently provided" ); // signed data hash constructed according to EIP-191-0x45 to prevent replays bytes32 hash = keccak256( abi.encodePacked( address(this), account, msg.sender, msg.value, validatorFee, attributeTypeID, value ) ); require( !_invalidAttributeApprovalHashes[hash], "signed attribute approvals from validators may not be reused" ); // extract the key used to sign the message hash address signingKey = hash.toEthSignedMessageHash().recover(signature); // retrieve the validator who controls the extracted key address validator = _signingKeys[signingKey]; require( canValidate(validator, attributeTypeID), "signature does not match an approved validator for provided attribute" ); // store attribute value and amount of ether staked in correct scope _issuedAttributes[account][attributeTypeID] = IssuedAttribute({ exists: true, setPersonally: false, operator: msg.sender, validator: validator, value: value, stake: stake // NOTE: no extraData included }); // flag the signed approval as invalid once it's been used to set attribute _invalidAttributeApprovalHashes[hash] = true; // log the addition of the attribute emit AttributeAdded(validator, account, attributeTypeID, value); // log allocation of staked funds to the attribute if applicable // NOTE: the staker is the entity that pays the fee here! if (stake > 0) { emit StakeAllocated(msg.sender, attributeTypeID, stake); } // pay jurisdiction fee to the owner of the jurisdiction if applicable if (jurisdictionFee > 0) { // NOTE: send is chosen over transfer to prevent cases where a improperly // configured fallback function could block addition of an attribute if (owner().send(jurisdictionFee)) { emit FeePaid(owner(), msg.sender, attributeTypeID, jurisdictionFee); } else { _recoverableFunds = _recoverableFunds.add(jurisdictionFee); } } // pay validator fee to the issuing validator's address if applicable if (validatorFee > 0) { // NOTE: send is chosen over transfer to prevent cases where a improperly // configured fallback function could block addition of an attribute if (validator.send(validatorFee)) { emit FeePaid(validator, msg.sender, attributeTypeID, validatorFee); } else { _recoverableFunds = _recoverableFunds.add(validatorFee); } } } /** * @notice Remove an attribute of the type with ID `attributeTypeID` from * account of `account`. * @param account address The account to remove the attribute from. * @param attributeTypeID uint256 The ID of the attribute type to remove. * @dev Restricted attribute types can only be removed by issuing validators or * the jurisdiction itself. */ function removeAttributeFor(address account, uint256 attributeTypeID) external { // attributes may only be removed by the user if they are not restricted require( !_attributeTypes[attributeTypeID].restricted, "only jurisdiction or issuing validator may remove a restricted attribute" ); require( _issuedAttributes[account][attributeTypeID].exists, "only existing attributes may be removed" ); require( _issuedAttributes[account][attributeTypeID].operator == msg.sender, "only an assigning operator may remove attribute on behalf of an address" ); // determine the assigned validator on the user attribute address validator = _issuedAttributes[account][attributeTypeID].validator; // determine if the attribute has a staked value uint256 stake = _issuedAttributes[account][attributeTypeID].stake; // remove the attribute from the user address delete _issuedAttributes[account][attributeTypeID]; // log the removal of the attribute emit AttributeRemoved(validator, account, attributeTypeID); // if the attribute has any staked balance, refund it to the user if (stake > 0 && address(this).balance >= stake) { // NOTE: send is chosen over transfer to prevent cases where a malicious // fallback function could forcibly block an attribute's removal if (msg.sender.send(stake)) { emit StakeRefunded(msg.sender, attributeTypeID, stake); } else { _recoverableFunds = _recoverableFunds.add(stake); } } } /** * @notice Invalidate a signed attribute approval before it has been set by * supplying the hash of the approval `hash` and the signature `signature`. * @param hash bytes32 The hash of the attribute approval. * @param signature bytes The hash's signature, resolving to the signing key. * @dev Attribute approvals can only be removed by issuing validators or the * jurisdiction itself. */ function invalidateAttributeApproval( bytes32 hash, bytes signature ) external { // determine the assigned validator on the signed attribute approval address validator = _signingKeys[ hash.toEthSignedMessageHash().recover(signature) // signingKey ]; // caller must be either the jurisdiction owner or the assigning validator require( msg.sender == validator || msg.sender == owner(), "only jurisdiction or issuing validator may invalidate attribute approval" ); // add the hash to the set of invalid attribute approval hashes _invalidAttributeApprovalHashes[hash] = true; } /** * @notice Check if an attribute of the type with ID `attributeTypeID` has * been assigned to the account at `account` and is currently valid. * @param account address The account to check for a valid attribute. * @param attributeTypeID uint256 The ID of the attribute type to check for. * @return True if the attribute is assigned and valid, false otherwise. * @dev This function MUST return either true or false - i.e. calling this * function MUST NOT cause the caller to revert. */ function hasAttribute( address account, uint256 attributeTypeID ) external view returns (bool) { address validator = _issuedAttributes[account][attributeTypeID].validator; return ( ( _validators[validator].exists && // isValidator(validator) _attributeTypes[attributeTypeID].approvedValidators[validator] && _attributeTypes[attributeTypeID].exists //isAttributeType(attributeTypeID) ) || ( _attributeTypes[attributeTypeID].secondarySource != address(0) && secondaryHasAttribute( _attributeTypes[attributeTypeID].secondarySource, account, _attributeTypes[attributeTypeID].secondaryAttributeTypeID ) ) ); } /** * @notice Retrieve the value of the attribute of the type with ID * `attributeTypeID` on the account at `account`, assuming it is valid. * @param account address The account to check for the given attribute value. * @param attributeTypeID uint256 The ID of the attribute type to check for. * @return The attribute value if the attribute is valid, reverts otherwise. * @dev This function MUST revert if a directly preceding or subsequent * function call to `hasAttribute` with identical `account` and * `attributeTypeID` parameters would return false. */ function getAttributeValue( address account, uint256 attributeTypeID ) external view returns (uint256 value) { // gas optimization: get validator & call canValidate function body directly address validator = _issuedAttributes[account][attributeTypeID].validator; if ( _validators[validator].exists && // isValidator(validator) _attributeTypes[attributeTypeID].approvedValidators[validator] && _attributeTypes[attributeTypeID].exists //isAttributeType(attributeTypeID) ) { return _issuedAttributes[account][attributeTypeID].value; } else if ( _attributeTypes[attributeTypeID].secondarySource != address(0) ) { // if attributeTypeID = uint256 of 'wyre-yes-token', use special handling if (_attributeTypes[attributeTypeID].secondaryAttributeTypeID == 2423228754106148037712574142965102) { require( IERC20( _attributeTypes[attributeTypeID].secondarySource ).balanceOf(account) >= 1, "no Yes Token has been issued to the provided account" ); return 1; // this could also return a specific yes token's country code? } // first ensure hasAttribute on the secondary source returns true require( AttributeRegistryInterface( _attributeTypes[attributeTypeID].secondarySource ).hasAttribute( account, _attributeTypes[attributeTypeID].secondaryAttributeTypeID ), "attribute of the provided type is not assigned to the provided account" ); return ( AttributeRegistryInterface( _attributeTypes[attributeTypeID].secondarySource ).getAttributeValue( account, _attributeTypes[attributeTypeID].secondaryAttributeTypeID ) ); } // NOTE: checking for values of invalid attributes will revert revert("could not find an attribute value at the provided account and ID"); } /** * @notice Determine if a validator at account `validator` is able to issue * attributes of the type with ID `attributeTypeID`. * @param validator address The account of the validator. * @param attributeTypeID uint256 The ID of the attribute type to check. * @return True if the validator can issue attributes of the given type, false * otherwise. */ function canIssueAttributeType( address validator, uint256 attributeTypeID ) external view returns (bool) { return canValidate(validator, attributeTypeID); } /** * @notice Get a description of the attribute type with ID `attributeTypeID`. * @param attributeTypeID uint256 The ID of the attribute type to check for. * @return A description of the attribute type. */ function getAttributeTypeDescription( uint256 attributeTypeID ) external view returns ( string description ) { return _attributeTypes[attributeTypeID].description; } /** * @notice Get comprehensive information on an attribute type with ID * `attributeTypeID`. * @param attributeTypeID uint256 The attribute type ID in question. * @return Information on the attribute type in question. */ function getAttributeTypeInformation( uint256 attributeTypeID ) external view returns ( string description, bool isRestricted, bool isOnlyPersonal, address secondarySource, uint256 secondaryAttributeTypeID, uint256 minimumRequiredStake, uint256 jurisdictionFee ) { return ( _attributeTypes[attributeTypeID].description, _attributeTypes[attributeTypeID].restricted, _attributeTypes[attributeTypeID].onlyPersonal, _attributeTypes[attributeTypeID].secondarySource, _attributeTypes[attributeTypeID].secondaryAttributeTypeID, _attributeTypes[attributeTypeID].minimumStake, _attributeTypes[attributeTypeID].jurisdictionFee ); } /** * @notice Get a description of the validator at account `validator`. * @param validator address The account of the validator in question. * @return A description of the validator. */ function getValidatorDescription( address validator ) external view returns ( string description ) { return _validators[validator].description; } /** * @notice Get the signing key of the validator at account `validator`. * @param validator address The account of the validator in question. * @return The signing key of the validator. */ function getValidatorSigningKey( address validator ) external view returns ( address signingKey ) { return _validators[validator].signingKey; } /** * @notice Find the validator that issued the attribute of the type with ID * `attributeTypeID` on the account at `account` and determine if the * validator is still valid. * @param account address The account that contains the attribute be checked. * @param attributeTypeID uint256 The ID of the attribute type in question. * @return The validator and the current status of the validator as it * pertains to the attribute type in question. * @dev if no attribute of the given attribute type exists on the account, the * function will return (address(0), false). */ function getAttributeValidator( address account, uint256 attributeTypeID ) external view returns ( address validator, bool isStillValid ) { address issuer = _issuedAttributes[account][attributeTypeID].validator; return (issuer, canValidate(issuer, attributeTypeID)); } /** * @notice Count the number of attribute types defined by the registry. * @return The number of available attribute types. * @dev This function MUST return a positive integer value - i.e. calling * this function MUST NOT cause the caller to revert. */ function countAttributeTypes() external view returns (uint256) { return _attributeIDs.length; } /** * @notice Get the ID of the attribute type at index `index`. * @param index uint256 The index of the attribute type in question. * @return The ID of the attribute type. * @dev This function MUST revert if the provided `index` value falls outside * of the range of the value returned from a directly preceding or subsequent * function call to `countAttributeTypes`. It MUST NOT revert if the provided * `index` value falls inside said range. */ function getAttributeTypeID(uint256 index) external view returns (uint256) { require( index < _attributeIDs.length, "provided index is outside of the range of defined attribute type IDs" ); return _attributeIDs[index]; } /** * @notice Get the IDs of all available attribute types on the jurisdiction. * @return A dynamic array containing all available attribute type IDs. */ function getAttributeTypeIDs() external view returns (uint256[]) { return _attributeIDs; } /** * @notice Count the number of validators defined by the jurisdiction. * @return The number of defined validators. */ function countValidators() external view returns (uint256) { return _validatorAccounts.length; } /** * @notice Get the account of the validator at index `index`. * @param index uint256 The index of the validator in question. * @return The account of the validator. */ function getValidator( uint256 index ) external view returns (address) { return _validatorAccounts[index]; } /** * @notice Get the accounts of all available validators on the jurisdiction. * @return A dynamic array containing all available validator accounts. */ function getValidators() external view returns (address[]) { return _validatorAccounts; } /** * @notice Determine if the interface ID `interfaceID` is supported (ERC-165) * @param interfaceID bytes4 The interface ID in question. * @return True if the interface is supported, false otherwise. * @dev this function will produce a compiler warning recommending that the * visibility be set to pure, but the interface expects a view function. * Supported interfaces include ERC-165 (0x01ffc9a7) and the attribute * registry interface (0x5f46473f). */ function supportsInterface(bytes4 interfaceID) external view returns (bool) { return ( interfaceID == this.supportsInterface.selector || // ERC165 interfaceID == ( this.hasAttribute.selector ^ this.getAttributeValue.selector ^ this.countAttributeTypes.selector ^ this.getAttributeTypeID.selector ) // AttributeRegistryInterface ); // 0x01ffc9a7 || 0x5f46473f } /** * @notice Get the hash of a given attribute approval. * @param account address The account specified by the attribute approval. * @param operator address An optional account permitted to submit approval. * @param attributeTypeID uint256 The ID of the attribute type in question. * @param value uint256 The value of the attribute in the approval. * @param fundsRequired uint256 The amount to be included with the approval. * @param validatorFee uint256 The required fee to be paid to the validator. * @return The hash of the attribute approval. */ function getAttributeApprovalHash( address account, address operator, uint256 attributeTypeID, uint256 value, uint256 fundsRequired, uint256 validatorFee ) external view returns ( bytes32 hash ) { return calculateAttributeApprovalHash( account, operator, attributeTypeID, value, fundsRequired, validatorFee ); } /** * @notice Check if a given signed attribute approval is currently valid when * submitted directly by `msg.sender`. * @param attributeTypeID uint256 The ID of the attribute type in question. * @param value uint256 The value of the attribute in the approval. * @param fundsRequired uint256 The amount to be included with the approval. * @param validatorFee uint256 The required fee to be paid to the validator. * @param signature bytes The attribute approval signature, based on a hash of * the other parameters and the submitting account. * @return True if the approval is currently valid, false otherwise. */ function canAddAttribute( uint256 attributeTypeID, uint256 value, uint256 fundsRequired, uint256 validatorFee, bytes signature ) external view returns (bool) { // signed data hash constructed according to EIP-191-0x45 to prevent replays bytes32 hash = calculateAttributeApprovalHash( msg.sender, address(0), attributeTypeID, value, fundsRequired, validatorFee ); // recover the address associated with the signature of the message hash address signingKey = hash.toEthSignedMessageHash().recover(signature); // retrieve variables necessary to perform checks address validator = _signingKeys[signingKey]; uint256 minimumStake = _attributeTypes[attributeTypeID].minimumStake; uint256 jurisdictionFee = _attributeTypes[attributeTypeID].jurisdictionFee; // determine if the attribute can currently be added. // NOTE: consider returning an error code along with the boolean. return ( fundsRequired >= minimumStake.add(jurisdictionFee).add(validatorFee) && !_invalidAttributeApprovalHashes[hash] && canValidate(validator, attributeTypeID) && !_issuedAttributes[msg.sender][attributeTypeID].exists ); } /** * @notice Check if a given signed attribute approval is currently valid for a * given account when submitted by the operator at `msg.sender`. * @param account address The account specified by the attribute approval. * @param attributeTypeID uint256 The ID of the attribute type in question. * @param value uint256 The value of the attribute in the approval. * @param fundsRequired uint256 The amount to be included with the approval. * @param validatorFee uint256 The required fee to be paid to the validator. * @param signature bytes The attribute approval signature, based on a hash of * the other parameters and the submitting account. * @return True if the approval is currently valid, false otherwise. */ function canAddAttributeFor( address account, uint256 attributeTypeID, uint256 value, uint256 fundsRequired, uint256 validatorFee, bytes signature ) external view returns (bool) { // signed data hash constructed according to EIP-191-0x45 to prevent replays bytes32 hash = calculateAttributeApprovalHash( account, msg.sender, attributeTypeID, value, fundsRequired, validatorFee ); // recover the address associated with the signature of the message hash address signingKey = hash.toEthSignedMessageHash().recover(signature); // retrieve variables necessary to perform checks address validator = _signingKeys[signingKey]; uint256 minimumStake = _attributeTypes[attributeTypeID].minimumStake; uint256 jurisdictionFee = _attributeTypes[attributeTypeID].jurisdictionFee; // determine if the attribute can currently be added. // NOTE: consider returning an error code along with the boolean. return ( fundsRequired >= minimumStake.add(jurisdictionFee).add(validatorFee) && !_invalidAttributeApprovalHashes[hash] && canValidate(validator, attributeTypeID) && !_issuedAttributes[account][attributeTypeID].exists ); } /** * @notice Determine if an attribute type with ID `attributeTypeID` is * currently defined on the jurisdiction. * @param attributeTypeID uint256 The attribute type ID in question. * @return True if the attribute type is defined, false otherwise. */ function isAttributeType(uint256 attributeTypeID) public view returns (bool) { return _attributeTypes[attributeTypeID].exists; } /** * @notice Determine if the account `account` is currently assigned as a * validator on the jurisdiction. * @param account address The account to check for validator status. * @return True if the account is assigned as a validator, false otherwise. */ function isValidator(address account) public view returns (bool) { return _validators[account].exists; } /** * @notice Check for recoverable funds that have become locked in the * jurisdiction as a result of improperly configured receivers for payments of * fees or remaining stake. Note that funds sent into the jurisdiction as a * result of coinbase assignment or as the recipient of a selfdestruct will * not be recoverable. * @return The total tracked recoverable funds. */ function recoverableFunds() public view returns (uint256) { // return the total tracked recoverable funds. return _recoverableFunds; } /** * @notice Check for recoverable tokens that are owned by the jurisdiction at * the token contract address of `token`. * @param token address The account where token contract is located. * @return The total recoverable tokens. */ function recoverableTokens(address token) public view returns (uint256) { // return the total tracked recoverable tokens. return IERC20(token).balanceOf(address(this)); } /** * @notice Recover funds that have become locked in the jurisdiction as a * result of improperly configured receivers for payments of fees or remaining * stake by transferring an amount of `value` to the address at `account`. * Note that funds sent into the jurisdiction as a result of coinbase * assignment or as the recipient of a selfdestruct will not be recoverable. * @param account address The account to send recovered tokens. * @param value uint256 The amount of tokens to be sent. */ function recoverFunds(address account, uint256 value) public onlyOwner { // safely deduct the value from the total tracked recoverable funds. _recoverableFunds = _recoverableFunds.sub(value); // transfer the value to the specified account & revert if any error occurs. account.transfer(value); } /** * @notice Recover tokens that are owned by the jurisdiction at the token * contract address of `token`, transferring an amount of `value` to the * address at `account`. * @param token address The account where token contract is located. * @param account address The account to send recovered funds. * @param value uint256 The amount of ether to be sent. */ function recoverTokens( address token, address account, uint256 value ) public onlyOwner { // transfer the value to the specified account & revert if any error occurs. require(IERC20(token).transfer(account, value)); } /** * @notice Internal function to determine if a validator at account * `validator` can issue attributes of the type with ID `attributeTypeID`. * @param validator address The account of the validator. * @param attributeTypeID uint256 The ID of the attribute type to check. * @return True if the validator can issue attributes of the given type, false * otherwise. */ function canValidate( address validator, uint256 attributeTypeID ) internal view returns (bool) { return ( _validators[validator].exists && // isValidator(validator) _attributeTypes[attributeTypeID].approvedValidators[validator] && _attributeTypes[attributeTypeID].exists // isAttributeType(attributeTypeID) ); } // internal helper function for getting the hash of an attribute approval function calculateAttributeApprovalHash( address account, address operator, uint256 attributeTypeID, uint256 value, uint256 fundsRequired, uint256 validatorFee ) internal view returns (bytes32 hash) { return keccak256( abi.encodePacked( address(this), account, operator, fundsRequired, validatorFee, attributeTypeID, value ) ); } // helper function, won't revert calling hasAttribute on secondary registries function secondaryHasAttribute( address source, address account, uint256 attributeTypeID ) internal view returns (bool result) { // if attributeTypeID = uint256 of 'wyre-yes-token', use special handling if (attributeTypeID == 2423228754106148037712574142965102) { return (IERC20(source).balanceOf(account) >= 1); } uint256 maxGas = gasleft() > 20000 ? 20000 : gasleft(); bytes memory encodedParams = abi.encodeWithSelector( this.hasAttribute.selector, account, attributeTypeID ); assembly { let encodedParams_data := add(0x20, encodedParams) let encodedParams_size := mload(encodedParams) let output := mload(0x40) // get storage start from free memory pointer mstore(output, 0x0) // set up the location for output of staticcall let success := staticcall( maxGas, // maximum of 20k gas can be forwarded source, // address of attribute registry to call encodedParams_data, // inputs are stored at pointer location encodedParams_size, // inputs are 68 bytes (4 + 32 * 2) output, // return to designated free space 0x20 // output is one word, or 32 bytes ) switch success // instrumentation bug: use switch instead of if case 1 { // only recognize successful staticcall output result := mload(output) // set the output to the return value } } } }
set the initial signing key (the validator's address) resolving to itself
_signingKeys[validator] = validator;
1,829,663
[ 1, 542, 326, 2172, 10611, 498, 261, 5787, 4213, 1807, 1758, 13, 17188, 358, 6174, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 389, 26907, 2396, 63, 7357, 65, 273, 4213, 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 ]
pragma solidity 0.6.2; pragma experimental ABIEncoderV2; interface Erc1820Registry { function SETINTERFACEIMPLEMENTER302(address _target, bytes32 _interfaceHash, address _implementer) external; //inject NONSTANDARD NAMING } contract Erc777TokensRecipient { constructor() public { // keccak256(abi.encodePacked("ERC777TokensRecipient")) == 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b Erc1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24).SETINTERFACEIMPLEMENTER302(address(this), 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b, address(this)); } function TOKENSRECEIVED576(address, address, address, uint256, bytes calldata, bytes calldata) external { } //inject NONSTANDARD NAMING function CANIMPLEMENTINTERFACEFORADDRESS796(bytes32 _interfaceHash, address _implementer) external view returns(bytes32) { //inject NONSTANDARD NAMING // keccak256(abi.encodePacked("ERC777TokensRecipient")) == 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b if (_implementer == address(this) && _interfaceHash == 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b) { // keccak256(abi.encodePacked("ERC1820_ACCEPT_MAGIC")) == 0xa2ef4600d742022d532d4747cb3547474667d6f13804902513b2ec01c848f4b4 return 0xa2ef4600d742022d532d4747cb3547474667d6f13804902513b2ec01c848f4b4; } else { return bytes32(0); } } } library EnumerableMap { struct Entry { address key; uint16 value; } struct Map { mapping (address => uint256) index; Entry[] entries; } function INITIALIZE417(Map storage map) internal { //inject NONSTANDARD NAMING // we initialize it with a placeholder entry in the first position because we treat the array as 1-indexed since 0 is a special index (means no entry in the index) map.entries.push(); } function CONTAINS634(Map storage map, address key) internal view returns (bool) { //inject NONSTANDARD NAMING return map.index[key] != 0; } function SET481(Map storage map, address key, uint16 value) internal { //inject NONSTANDARD NAMING uint256 index = map.index[key]; if (index == 0) { // create new entry Entry memory entry = Entry({ key: key, value: value }); map.entries.push(entry); map.index[key] = map.entries.length - 1; } else { // update existing entry map.entries[index].value = value; } require(map.entries[map.index[key]].key == key, "Key at inserted location does not match inserted key."); require(map.entries[map.index[key]].value == value, "Value at inserted location does not match inserted value."); } function REMOVE650(Map storage map, address key) internal { //inject NONSTANDARD NAMING // get the index into entries array that this entry lives at uint256 index = map.index[key]; // if this key doesn't exist in the index, then we have nothing to do if (index == 0) return; // if the entry we are removing isn't the last, overwrite it with the last entry uint256 lastIndex = map.entries.length - 1; if (index != lastIndex) { Entry storage lastEntry = map.entries[lastIndex]; map.entries[index] = lastEntry; map.index[lastEntry.key] = index; } // delete the last entry (if the item we are removing isn't last, it will have been overwritten with the last entry inside the conditional above) map.entries.pop(); // delete the index pointer delete map.index[key]; require(map.index[key] == 0, "Removed key still exists in the index."); require(index == lastIndex || map.entries[index].key != key, "Removed key still exists in the array at original index."); } function GET309(Map storage map, address key) internal view returns (uint16) { //inject NONSTANDARD NAMING uint256 index = map.index[key]; require(index != 0, "Provided key was not in the map."); return map.entries[index].value; } // this function is effectively map.entries.slice(1:), but that doesn't work with storage arrays in this version of solc so we have to do it by hand function ENUMERATE294(Map storage map) internal view returns (Entry[] memory) { //inject NONSTANDARD NAMING // output array is one shorter because we use a 1-indexed array Entry[] memory output = new Entry[](map.entries.length - 1); // first element in the array is just a placeholder (0,0), so we copy from element 1 to end for (uint256 i = 1; i < map.entries.length; ++i) { output[i - 1] = map.entries[i]; } return output; } } contract RecoverableWallet is Erc777TokensRecipient { using EnumerableMap for EnumerableMap.Map; event RECOVERYADDRESSADDED788(address indexed newRecoverer, uint16 recoveryDelayInDays); //inject NONSTANDARD NAMING event RECOVERYADDRESSREMOVED981(address indexed oldRecoverer); //inject NONSTANDARD NAMING event RECOVERYSTARTED822(address indexed newOwner); //inject NONSTANDARD NAMING event RECOVERYCANCELLED820(address indexed oldRecoverer); //inject NONSTANDARD NAMING event RECOVERYFINISHED802(address indexed oldOwner, address indexed newOwner); //inject NONSTANDARD NAMING address public owner; EnumerableMap.Map private recoveryDelaysInDays; address public activeRecoveryAddress; uint256 public activeRecoveryEndTime = uint256(-1); modifier ONLYOWNER488() { //inject NONSTANDARD NAMING require(msg.sender == owner, "Only the owner may call this method."); _; } modifier ONLYDURINGRECOVERY592() { //inject NONSTANDARD NAMING require(activeRecoveryAddress != address(0), "This method can only be called during a recovery."); _; } modifier ONLYOUTSIDERECOVERY75() { //inject NONSTANDARD NAMING require(activeRecoveryAddress == address(0), "This method cannot be called during a recovery."); _; } constructor(address _initialOwner) public { require(_initialOwner != address(0), "Wallet must have an initial owner."); owner = _initialOwner; recoveryDelaysInDays.INITIALIZE417(); } function LISTRECOVERERS745() external view returns (EnumerableMap.Entry[] memory) { //inject NONSTANDARD NAMING return recoveryDelaysInDays.ENUMERATE294(); } function GETRECOVERYDELAYINDAYS334(address recoverer) external view returns (uint16) { //inject NONSTANDARD NAMING return recoveryDelaysInDays.GET309(recoverer); } receive () external payable { } function ADDRECOVERYADDRESS704(address _newRecoveryAddress, uint16 _recoveryDelayInDays) external ONLYOWNER488 ONLYOUTSIDERECOVERY75 { //inject NONSTANDARD NAMING require(_newRecoveryAddress != address(0), "Recovery address must be supplied."); recoveryDelaysInDays.SET481(_newRecoveryAddress, _recoveryDelayInDays); emit RECOVERYADDRESSADDED788(_newRecoveryAddress, _recoveryDelayInDays); } function REMOVERECOVERYADDRESS238(address _oldRecoveryAddress) public ONLYOWNER488 ONLYOUTSIDERECOVERY75 { //inject NONSTANDARD NAMING require(_oldRecoveryAddress != address(0), "Recovery address must be supplied."); recoveryDelaysInDays.REMOVE650(_oldRecoveryAddress); emit RECOVERYADDRESSREMOVED981(_oldRecoveryAddress); } function STARTRECOVERY76() external { //inject NONSTANDARD NAMING require(recoveryDelaysInDays.CONTAINS634(msg.sender), "Caller is not registered as a recoverer for this wallet."); uint16 _proposedRecoveryDelayInDays = recoveryDelaysInDays.GET309(msg.sender); bool _inRecovery = activeRecoveryAddress != address(0); if (_inRecovery) { // NOTE: the delay for a particular recovery address cannot be changed during recovery nor can addresses be removed during recovery, so we can rely on this being != 0 uint16 _activeRecoveryDelayInDays = recoveryDelaysInDays.GET309(activeRecoveryAddress); require(_proposedRecoveryDelayInDays < _activeRecoveryDelayInDays, "Recovery is already under way and new recoverer doesn't have a higher priority."); emit RECOVERYCANCELLED820(activeRecoveryAddress); } activeRecoveryAddress = msg.sender; activeRecoveryEndTime = block.timestamp + _proposedRecoveryDelayInDays * 1 days; emit RECOVERYSTARTED822(msg.sender); } function CANCELRECOVERY426() public ONLYOWNER488 ONLYDURINGRECOVERY592 { //inject NONSTANDARD NAMING address _recoveryAddress = activeRecoveryAddress; RESETRECOVERY810(); emit RECOVERYCANCELLED820(_recoveryAddress); } function CANCELRECOVERYANDREMOVERECOVERYADDRESS810() external ONLYOWNER488 ONLYDURINGRECOVERY592 { //inject NONSTANDARD NAMING address _recoveryAddress = activeRecoveryAddress; CANCELRECOVERY426(); REMOVERECOVERYADDRESS238(_recoveryAddress); } function FINISHRECOVERY886() external ONLYDURINGRECOVERY592 { //inject NONSTANDARD NAMING require(block.timestamp >= activeRecoveryEndTime, "You must wait until the recovery delay is over before finishing the recovery."); address _oldOwner = owner; owner = activeRecoveryAddress; RESETRECOVERY810(); emit RECOVERYFINISHED802(_oldOwner, owner); } function DEPLOY471(uint256 _value, bytes calldata _data, uint256 _salt) external payable ONLYOWNER488 ONLYOUTSIDERECOVERY75 returns (address) { //inject NONSTANDARD NAMING require(address(this).balance >= _value, "Wallet does not have enough funds available to deploy the contract."); require(_data.length != 0, "Contract deployment must contain bytecode to deploy."); bytes memory _data2 = _data; address newContract; assembly { newContract := create2(_value, add(_data2, 32), mload(_data2), _salt) } require(newContract != address(0), "Contract creation returned address 0, indicating failure."); return newContract; } function EXECUTE479(address payable _to, uint256 _value, bytes calldata _data) external payable ONLYOWNER488 ONLYOUTSIDERECOVERY75 returns (bytes memory) { //inject NONSTANDARD NAMING require(_to != address(0), "Transaction execution must contain a destination. If you meant to deploy a contract, use deploy instead."); require(address(this).balance >= _value, "Wallet does not have enough funds available to execute the desired transaction."); (bool _success, bytes memory _result) = _to.call.value(_value)(_data); require(_success, "Contract execution failed."); return _result; } function RESETRECOVERY810() private { //inject NONSTANDARD NAMING activeRecoveryAddress = address(0); activeRecoveryEndTime = uint256(-1); } } contract RecoverableWalletFactory { event WALLETCREATED977(address indexed owner, RecoverableWallet indexed wallet); //inject NONSTANDARD NAMING function CREATEWALLET42() external returns (RecoverableWallet) { //inject NONSTANDARD NAMING RecoverableWallet wallet = new RecoverableWallet(msg.sender); emit WALLETCREATED977(msg.sender, wallet); return wallet; } function EXISTS199() external pure returns (bytes32) { //inject NONSTANDARD NAMING return 0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef; } }
inject NONSTANDARD NAMING
modifier ONLYOWNER488() {
5,459,509
[ 1, 22170, 18708, 882, 18264, 423, 2192, 1360, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 20597, 20747, 29602, 24, 5482, 1435, 288, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* * source https://github.com/blockbitsio/ * @name Funding Vault * @package BlockBitsIO * @author Micky Socaci <[email protected]> each purchase creates a separate funding vault contract */ pragma solidity ^0.4.17; import "./../ApplicationEntityABI.sol"; import "./../abis/ABIToken.sol"; import "./../abis/ABIFunding.sol"; import "./../abis/ABIMilestones.sol"; import "./../abis/ABIProposals.sol"; import "./../abis/ABITokenManager.sol"; import "./../abis/ABIFundingManager.sol"; import "./../abis/ABITokenSCADAVariable.sol"; contract FundingVault { /* Asset initialised or not */ bool public _initialized = false; /* Addresses: vaultOwner - the address of the wallet that stores purchases in this vault ( investor address ) outputAddress - address where funds go upon successful funding or successful milestone release managerAddress - address of the "FundingManager" */ address public vaultOwner ; address public outputAddress; address public managerAddress; /* Lock and BlackHole settings */ bool public allFundingProcessed = false; bool public DirectFundingProcessed = false; /* Assets */ // ApplicationEntityABI public ApplicationEntity; ABIFunding FundingEntity; ABIFundingManager FundingManagerEntity; ABIMilestones MilestonesEntity; ABIProposals ProposalsEntity; ABITokenSCADAVariable TokenSCADAEntity; ABIToken TokenEntity ; /* Globals */ uint256 public amount_direct = 0; uint256 public amount_milestone = 0; // bylaws bool public emergencyFundReleased = false; uint8 emergencyFundPercentage = 0; uint256 BylawsCashBackOwnerMiaDuration; uint256 BylawsCashBackVoteRejectedDuration; uint256 BylawsProposalVotingDuration; struct PurchaseStruct { uint256 unix_time; uint8 payment_method; uint256 amount; uint8 funding_stage; uint16 index; } mapping(uint16 => PurchaseStruct) public purchaseRecords; uint16 public purchaseRecordsNum; event EventPaymentReceived(uint8 indexed _payment_method, uint256 indexed _amount, uint16 indexed _index ); event VaultInitialized(address indexed _owner); function initialize( address _owner, address _output, address _fundingAddress, address _milestoneAddress, address _proposalsAddress ) public requireNotInitialised returns(bool) { VaultInitialized(_owner); outputAddress = _output; vaultOwner = _owner; // whomever creates this contract is the manager. managerAddress = msg.sender; // assets FundingEntity = ABIFunding(_fundingAddress); FundingManagerEntity = ABIFundingManager(managerAddress); MilestonesEntity = ABIMilestones(_milestoneAddress); ProposalsEntity = ABIProposals(_proposalsAddress); address TokenManagerAddress = FundingEntity.getApplicationAssetAddressByName("TokenManager"); ABITokenManager TokenManagerEntity = ABITokenManager(TokenManagerAddress); address TokenAddress = TokenManagerEntity.TokenEntity(); TokenEntity = ABIToken(TokenAddress); address TokenSCADAAddress = TokenManagerEntity.TokenSCADAEntity(); TokenSCADAEntity = ABITokenSCADAVariable(TokenSCADAAddress); // set Emergency Fund Percentage if available. address ApplicationEntityAddress = TokenManagerEntity.owner(); ApplicationEntityABI ApplicationEntity = ApplicationEntityABI(ApplicationEntityAddress); // get Application Bylaws emergencyFundPercentage = uint8( ApplicationEntity.getBylawUint256("emergency_fund_percentage") ); BylawsCashBackOwnerMiaDuration = ApplicationEntity.getBylawUint256("cashback_owner_mia_dur") ; BylawsCashBackVoteRejectedDuration = ApplicationEntity.getBylawUint256("cashback_investor_no") ; BylawsProposalVotingDuration = ApplicationEntity.getBylawUint256("proposal_voting_duration") ; // init _initialized = true; return true; } /* The funding contract decides if a vault should receive payments or not, since it's the one that creates them, no point in creating one if you can't accept payments. */ mapping (uint8 => uint256) public stageAmounts; mapping (uint8 => uint256) public stageAmountsDirect; function addPayment( uint8 _payment_method, uint8 _funding_stage ) public payable requireInitialised onlyManager returns (bool) { if(msg.value > 0 && FundingEntity.allowedPaymentMethod(_payment_method)) { // store payment PurchaseStruct storage purchase = purchaseRecords[++purchaseRecordsNum]; purchase.unix_time = now; purchase.payment_method = _payment_method; purchase.amount = msg.value; purchase.funding_stage = _funding_stage; purchase.index = purchaseRecordsNum; // assign payment to direct or milestone if(_payment_method == 1) { amount_direct+= purchase.amount; stageAmountsDirect[_funding_stage]+=purchase.amount; } if(_payment_method == 2) { amount_milestone+= purchase.amount; } // in order to not iterate through purchase records, we just increase funding stage amount. // issue with iterating over them, while processing vaults, would be that someone could create a large // number of payments, which would result in an "out of gas" / stack overflow issue, that would lock // our contract, so we don't really want to do that. // doing it this way also saves some gas stageAmounts[_funding_stage]+=purchase.amount; EventPaymentReceived( purchase.payment_method, purchase.amount, purchase.index ); return true; } else { revert(); } } function getBoughtTokens() public view returns (uint256) { return TokenSCADAEntity.getBoughtTokens( address(this), false ); } function getDirectBoughtTokens() public view returns (uint256) { return TokenSCADAEntity.getBoughtTokens( address(this), true ); } mapping (uint8 => uint256) public etherBalances; mapping (uint8 => uint256) public tokenBalances; uint8 public BalanceNum = 0; bool public BalancesInitialised = false; function initMilestoneTokenAndEtherBalances() internal { if(BalancesInitialised == false) { uint256 milestoneTokenBalance = TokenEntity.balanceOf(address(this)); uint256 milestoneEtherBalance = this.balance; // no need to worry about fractions because at the last milestone, we send everything that's left. // emergency fund takes it's percentage from initial balances. if(emergencyFundPercentage > 0) { tokenBalances[0] = milestoneTokenBalance / 100 * emergencyFundPercentage; etherBalances[0] = milestoneEtherBalance / 100 * emergencyFundPercentage; milestoneTokenBalance-=tokenBalances[0]; milestoneEtherBalance-=etherBalances[0]; } // milestones percentages are then taken from what's left. for(uint8 i = 1; i <= MilestonesEntity.RecordNum(); i++) { uint8 perc = MilestonesEntity.getMilestoneFundingPercentage(i); tokenBalances[i] = milestoneTokenBalance / 100 * perc; etherBalances[i] = milestoneEtherBalance / 100 * perc; } BalanceNum = i; BalancesInitialised = true; } } function ReleaseFundsAndTokens() public requireInitialised onlyManager returns (bool) { // first make sure cashback is not possible, and that we've not processed everything in this vault if(!canCashBack() && allFundingProcessed == false) { if(FundingManagerEntity.CurrentEntityState() == FundingManagerEntity.getEntityState("FUNDING_SUCCESSFUL_PROGRESS")) { // case 1, direct funding only if(amount_direct > 0 && amount_milestone == 0) { // if we have direct funding and no milestone balance, transfer everything and lock vault // to save gas in future processing runs. // transfer tokens to the investor TokenEntity.transfer(vaultOwner, TokenEntity.balanceOf( address(this) ) ); // transfer ether to the owner's wallet outputAddress.transfer(this.balance); // lock vault.. and enable black hole methods allFundingProcessed = true; } else { // case 2 and 3, direct funding only if(amount_direct > 0 && DirectFundingProcessed == false ) { TokenEntity.transfer(vaultOwner, getDirectBoughtTokens() ); // transfer "direct funding" ether to the owner's wallet outputAddress.transfer(amount_direct); DirectFundingProcessed = true; } // process and initialize milestone balances, emergency fund, etc, once initMilestoneTokenAndEtherBalances(); } return true; } else if(FundingManagerEntity.CurrentEntityState() == FundingManagerEntity.getEntityState("MILESTONE_PROCESS_PROGRESS")) { // get current milestone so we know which one we need to release funds for. uint8 milestoneId = MilestonesEntity.currentRecord(); uint256 transferTokens = tokenBalances[milestoneId]; uint256 transferEther = etherBalances[milestoneId]; if(milestoneId == BalanceNum - 1) { // we're processing the last milestone and balance, this means we're transferring everything left. // this is done to make sure we've transferred everything, even "ether that got mistakenly sent to this address" // as well as the emergency fund if it has not been used. transferTokens = TokenEntity.balanceOf(address(this)); transferEther = this.balance; } // set balances to 0 so we can't transfer multiple times. // tokenBalances[milestoneId] = 0; // etherBalances[milestoneId] = 0; // transfer tokens to the investor TokenEntity.transfer(vaultOwner, transferTokens ); // transfer ether to the owner's wallet outputAddress.transfer(transferEther); if(milestoneId == BalanceNum - 1) { // lock vault.. and enable black hole methods allFundingProcessed = true; } return true; } } return false; } function releaseTokensAndEtherForEmergencyFund() public requireInitialised onlyManager returns (bool) { if( emergencyFundReleased == false && emergencyFundPercentage > 0) { // transfer tokens to the investor TokenEntity.transfer(vaultOwner, tokenBalances[0] ); // transfer ether to the owner's wallet outputAddress.transfer(etherBalances[0]); emergencyFundReleased = true; return true; } return false; } function ReleaseFundsToInvestor() public requireInitialised isOwner { if(canCashBack()) { // IF we're doing a cashback // transfer vault tokens back to owner address // send all ether to wallet owner // get token balance uint256 myBalance = TokenEntity.balanceOf(address(this)); // transfer all vault tokens to owner if(myBalance > 0) { TokenEntity.transfer(outputAddress, myBalance ); } // now transfer all remaining ether back to investor address vaultOwner.transfer(this.balance); // update FundingManager Locked Token Amount, so we don't break voting FundingManagerEntity.VaultRequestedUpdateForLockedVotingTokens( vaultOwner ); // disallow further processing, so we don't break Funding Manager. // this method can still be called to collect future black hole ether to this vault. allFundingProcessed = true; } } /* 1 - if the funding of the project Failed, allows investors to claim their locked ether back. 2 - if the Investor votes NO to a Development Milestone Completion Proposal, where the majority also votes NO allows investors to claim their locked ether back. 3 - project owner misses to set the time for a Development Milestone Completion Meeting allows investors to claim their locked ether back. */ function canCashBack() public view requireInitialised returns (bool) { // case 1 if(checkFundingStateFailed()) { return true; } // case 2 if(checkMilestoneStateInvestorVotedNoVotingEndedNo()) { return true; } // case 3 if(checkOwnerFailedToSetTimeOnMeeting()) { return true; } return false; } function checkFundingStateFailed() public view returns (bool) { if(FundingEntity.CurrentEntityState() == FundingEntity.getEntityState("FAILED_FINAL") ) { return true; } // also check if funding period ended, and 7 days have passed and no processing was done. if( FundingEntity.getTimestamp() >= FundingEntity.Funding_Setting_cashback_time_start() ) { // should only be possible if funding entity has been stuck in processing for more than 7 days. if( FundingEntity.CurrentEntityState() != FundingEntity.getEntityState("SUCCESSFUL_FINAL") ) { return true; } } return false; } function checkMilestoneStateInvestorVotedNoVotingEndedNo() public view returns (bool) { if(MilestonesEntity.CurrentEntityState() == MilestonesEntity.getEntityState("VOTING_ENDED_NO") ) { // first we need to make sure we actually voted. if( ProposalsEntity.getHasVoteForCurrentMilestoneRelease(vaultOwner) == true) { // now make sure we voted NO, and if so return true if( ProposalsEntity.getMyVoteForCurrentMilestoneRelease( vaultOwner ) == false) { return true; } } } return false; } function checkOwnerFailedToSetTimeOnMeeting() public view returns (bool) { // Looks like the project owner is missing in action // they only have to do 1 thing, which is set the meeting time 7 days before the end of the milestone so that // investors know when they need to show up for a progress report meeting // as they did not, we consider them missing in action and allow investors to retrieve their locked ether back if( MilestonesEntity.CurrentEntityState() == MilestonesEntity.getEntityState("DEADLINE_MEETING_TIME_FAILED") ) { return true; } return false; } modifier isOwner() { require(msg.sender == vaultOwner); _; } modifier onlyManager() { require(msg.sender == managerAddress); _; } modifier requireInitialised() { require(_initialized == true); _; } modifier requireNotInitialised() { require(_initialized == false); _; } }
whomever creates this contract is the manager. assets set Emergency Fund Percentage if available. get Application Bylaws init
function initialize( address _owner, address _output, address _fundingAddress, address _milestoneAddress, address _proposalsAddress ) public requireNotInitialised returns(bool) { VaultInitialized(_owner); outputAddress = _output; vaultOwner = _owner; managerAddress = msg.sender; FundingEntity = ABIFunding(_fundingAddress); FundingManagerEntity = ABIFundingManager(managerAddress); MilestonesEntity = ABIMilestones(_milestoneAddress); ProposalsEntity = ABIProposals(_proposalsAddress); address TokenManagerAddress = FundingEntity.getApplicationAssetAddressByName("TokenManager"); ABITokenManager TokenManagerEntity = ABITokenManager(TokenManagerAddress); address TokenAddress = TokenManagerEntity.TokenEntity(); TokenEntity = ABIToken(TokenAddress); address TokenSCADAAddress = TokenManagerEntity.TokenSCADAEntity(); TokenSCADAEntity = ABITokenSCADAVariable(TokenSCADAAddress); address ApplicationEntityAddress = TokenManagerEntity.owner(); ApplicationEntityABI ApplicationEntity = ApplicationEntityABI(ApplicationEntityAddress); emergencyFundPercentage = uint8( ApplicationEntity.getBylawUint256("emergency_fund_percentage") ); BylawsCashBackOwnerMiaDuration = ApplicationEntity.getBylawUint256("cashback_owner_mia_dur") ; BylawsCashBackVoteRejectedDuration = ApplicationEntity.getBylawUint256("cashback_investor_no") ; BylawsProposalVotingDuration = ApplicationEntity.getBylawUint256("proposal_voting_duration") ; _initialized = true; return true; } no point in creating one if you can't accept payments. mapping (uint8 => uint256) public stageAmounts; mapping (uint8 => uint256) public stageAmountsDirect;
886,875
[ 1, 3350, 1742, 502, 3414, 333, 6835, 353, 326, 3301, 18, 7176, 444, 512, 6592, 75, 2075, 478, 1074, 21198, 410, 309, 2319, 18, 336, 4257, 2525, 80, 6850, 1208, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4046, 12, 203, 3639, 1758, 389, 8443, 16, 203, 3639, 1758, 389, 2844, 16, 203, 3639, 1758, 389, 74, 14351, 1887, 16, 203, 3639, 1758, 389, 81, 18270, 1887, 16, 203, 3639, 1758, 389, 685, 22536, 1887, 203, 565, 262, 203, 3639, 1071, 203, 3639, 2583, 1248, 4435, 5918, 203, 3639, 1135, 12, 6430, 13, 203, 565, 288, 203, 3639, 17329, 11459, 24899, 8443, 1769, 203, 203, 3639, 876, 1887, 273, 389, 2844, 31, 203, 3639, 9229, 5541, 273, 389, 8443, 31, 203, 203, 3639, 3301, 1887, 273, 1234, 18, 15330, 31, 203, 203, 3639, 478, 14351, 1943, 273, 10336, 5501, 14351, 24899, 74, 14351, 1887, 1769, 203, 3639, 478, 14351, 1318, 1943, 273, 10336, 5501, 14351, 1318, 12, 4181, 1887, 1769, 203, 3639, 490, 14849, 5322, 1943, 273, 10336, 3445, 14849, 5322, 24899, 81, 18270, 1887, 1769, 203, 3639, 1186, 22536, 1943, 273, 10336, 45, 626, 22536, 24899, 685, 22536, 1887, 1769, 203, 203, 3639, 1758, 3155, 1318, 1887, 273, 478, 14351, 1943, 18, 588, 3208, 6672, 1887, 5911, 2932, 1345, 1318, 8863, 203, 3639, 10336, 1285, 969, 1318, 3155, 1318, 1943, 273, 10336, 1285, 969, 1318, 12, 1345, 1318, 1887, 1769, 203, 203, 3639, 1758, 3155, 1887, 273, 3155, 1318, 1943, 18, 1345, 1943, 5621, 203, 3639, 3155, 1943, 273, 10336, 1285, 969, 12, 1345, 1887, 1769, 203, 203, 3639, 1758, 3155, 2312, 1880, 37, 1887, 273, 3155, 1318, 1943, 18, 1345, 2312, 1880, 37, 1943, 5621, 203, 3639, 3155, 2312, 1880, 37, 1943, 273, 10336, 1285, 969, 2312, 1880, 2 ]
// LC->05.11.2015 // наречия, которые моргут употребляться внутри аналитической конструкции // страдательного залога для простого времени: // Grachtengordel had not yet been established. // ^^^ wordentry_set PassiveInnerAdverb0= { eng_adverb:yet{}, // Grachtengordel had not yet been established. eng_adverb:legally{}, // Nobody is legally allowed to stultify himself. eng_adverb:sorely{}, // I've been sorely tried by these students. eng_adverb:almost{}, // We're almost finished. eng_adverb:Artificially{}, // Artificially induced conditions eng_adverb:Naturally{}, // Naturally grown flowers eng_adverb:Glacially{}, // Glacially deposited material eng_adverb:Judicially{}, // Judicially controlled process eng_adverb:Volcanically{}, // Volcanically created landscape eng_adverb:Religiously{}, // Religiously inspired art eng_adverb:Cortically{}, // Cortically induced arousal eng_adverb:Organically{}, // Organically bound iodine eng_adverb:Serially{}, // Serially composed music eng_adverb:Professionally{}, // Professionally trained staff eng_adverb:Catalytically{}, // Catalytically stabilized combustion of propane eng_adverb:Democratically{}, // Democratically elected government eng_adverb:insipidly{}, // insipidly expressed thoughts eng_adverb:Publicly{}, // Publicly financed schools eng_adverb:Tritely{}, // Tritely expressed emotions eng_adverb:Trivially{}, // Trivially motivated requests eng_adverb:spirally{}, // spirally fluted handles eng_adverb:murkily{}, // murkily expressed ideas eng_adverb:Finely{}, // Finely costumed actors eng_adverb:Linguistically{}, // Linguistically impaired children eng_adverb:Medically{}, // Medically trained nurses eng_adverb:Socially{}, // Socially accepted norms eng_adverb:Highly{}, // Highly paid workers eng_adverb:Inorganically{}, // Inorganically bound molecules eng_adverb:Symbolically{}, // Symbolically accepted goals eng_adverb:Photographically{}, // Photographically recorded scenes eng_adverb:loosely{}, // The loosely played game eng_adverb:internally{}, // An internally controlled environment eng_adverb:barely{}, // A barely furnished room eng_adverb:freshly{}, // A freshly cleaned floor eng_adverb:squarely{}, // A squarely cut piece of paper eng_adverb:feudally{}, // A feudally organized society eng_adverb:nicely{}, // A nicely painted house eng_adverb:privately{}, // A privately financed campaign eng_adverb:dimly{}, // A dimly lit room eng_adverb:solidly{}, // A solidly built house eng_adverb:specially{}, // A specially arranged dinner eng_adverb:heavily{}, // A heavily constructed car eng_adverb:voluptuously{}, // a voluptuously curved woman eng_adverb:skimpily{}, // a skimpily dressed woman eng_adverb:shoddily{}, // a shoddily built house eng_adverb:shabbily{}, // a shabbily dressed man eng_adverb:queerly{}, // a queerly inscribed sheet of paper eng_adverb:fierily{}, // a fierily opinionated book eng_adverb:thickly{}, // A thickly populated area eng_adverb:tightly{}, // A tightly packed pub eng_adverb:piratically{}, // The piratically published edition of his book eng_adverb:illiberally{}, // His illiberally biased way of thinking eng_adverb:canonically{}, // The deacon was canonically inducted. eng_adverb:fascinatingly{}, // Her face became fascinatingly distorted. eng_adverb:no longer{}, // Technically, the term is no longer used by experts. eng_adverb:negatively{}, // He was negatively inclined. eng_adverb:strongly{}, // He was strongly opposed to the government. eng_adverb:frequently{}, // Nouns are frequently used adjectively. eng_adverb:adversely{}, // She was adversely affected by the new regulations. eng_adverb:bureaucratically{}, // It's bureaucratically complicated. eng_adverb:inequitably{}, // Their father's possessions were inequitably divided among the sons. eng_adverb:equitably{}, // The inheritance was equitably divided among the sisters. eng_adverb:airily{}, // This cannot be airily explained to your children. eng_adverb:magnetically{}, // He was magnetically attracted to her. eng_adverb:permanently{}, // He is permanently disabled. eng_adverb:elaborately{}, // It was elaborately spelled out. eng_adverb:experimentally{}, // This can be experimentally determined. eng_adverb:locally{}, // It was locally decided. eng_adverb:sadly{}, // He was sadly neglected. eng_adverb:mighty{}, // He's mighty tired. eng_adverb:clearly{}, // They were clearly lost. eng_adverb:unhappily{}, // They were unhappily married. eng_adverb:bitterly{}, // He was bitterly disappointed. eng_adverb:soundly{}, // He was soundly defeated. eng_adverb:clinically{}, // She is clinically qualified. eng_adverb:duly{}, // She was duly apprised of the raise. eng_adverb:randomly{}, // The houses were randomly scattered. eng_adverb:mainly{}, // He is mainly interested in butterflies. eng_adverb:doubly{}, // She was doubly rewarded. eng_adverb:empirically{}, // This can be empirically tested. eng_adverb:multiply{}, // They were multiply checked for errors. eng_adverb:grimly{}, // He was grimly satisfied. eng_adverb:internationally{}, // She is internationally known. eng_adverb:newly{}, // They are newly married. eng_adverb:centrally{}, // The theater is centrally located. eng_adverb:constitutionally{}, // This was constitutionally ruled out. eng_adverb:axiomatically{}, // This is axiomatically given. eng_adverb:digitally{}, // The time was digitally displayed. eng_adverb:federally{}, // It's federally regulated. eng_adverb:realistically{}, // The figure was realistically painted. eng_adverb:similarly{}, // He was similarly affected. eng_adverb:inappropriately{}, // He was inappropriately dressed. eng_adverb:appropriately{}, // He was appropriately dressed. eng_adverb:homeostatically{}, // Blood pressure is homeostatically regulated. eng_adverb:temperamentally{}, // They are temperamentally suited to each other. eng_adverb:insufficiently{}, // He was insufficiently prepared. eng_adverb:easily{}, // She was easily confused. eng_adverb:completely{}, // The apartment was completely furnished. eng_adverb:intimately{}, // The two phenomena are intimately connected. eng_adverb:closely{}, // He was closely involved in monitoring daily progress. eng_adverb:symmetrically{}, // They were symmetrically arranged. eng_adverb:secretly{}, // They were secretly delighted at his embarrassment. eng_adverb:asymmetrically{}, // They were asymmetrically arranged. eng_adverb:lightly{}, // Her speech is only lightly accented. eng_adverb:helpfully{}, // The subtitles are helpfully conveyed. eng_adverb:superbly{}, // Her voice is superbly disciplined. eng_adverb:cleverly{}, // They were cleverly arranged. eng_adverb:formally{}, // The club will be formally recognized. eng_adverb:popularly{}, // This topic was popularly discussed. eng_adverb:diffusely{}, // The arteries were diffusely narrowed. eng_adverb:visibly{}, // The sign was visibly displayed. eng_adverb:strikingly{}, // This was strikingly demonstrated. eng_adverb:conveniently{}, // The switch was conveniently located. eng_adverb:hopelessly{}, // The papers were hopelessly jumbled. eng_adverb:eagerly{}, // The news was eagerly awaited. eng_adverb:correctly{}, // The flower had been correctly depicted by his son. eng_adverb:viciously{}, // He was viciously attacked. eng_adverb:prominently{}, // The new car was prominently displayed in the driveway. eng_adverb:unjustly{}, // He was unjustly singled out for punishment. eng_adverb:rightly{}, // He was rightly considered the greatest singer of his time. eng_adverb:busily{}, // They were busily engaged in buying souvenirs. eng_adverb:ornately{}, // The cradle was ornately carved. eng_adverb:sharply{}, // The new style of Minoan pottery was sharply defined. eng_adverb:involuntarily{}, // He was involuntarily held against his will. eng_adverb:ceremonially{}, // He was ceremonially sworn in as President. eng_adverb:sedulously{}, // This illusion has been sedulously fostered. eng_adverb:unpleasantly{}, // He had been unpleasantly surprised. eng_adverb:abundantly{}, // They were abundantly supplied with food. eng_adverb:absolutely{}, // We are absolutely opposed to the idea. eng_adverb:entirely{}, // We are entirely satisfied with the meal. eng_adverb:wholly{}, // He was wholly convinced. eng_adverb:gradually{}, // The remote areas of the country were gradually built up. eng_adverb:unattractively{}, // She was unattractively dressed last night. eng_adverb:artistically{}, // It was artistically decorated. eng_adverb:partially{}, // He was partially paralyzed. eng_adverb:imperfectly{}, // The lobe was imperfectly developed. eng_adverb:badly{}, // The buildings were badly shaken. eng_adverb:smartly{}, // He was smartly dressed. eng_adverb:obscurely{}, // This work is obscurely written. eng_adverb:lawfully{}, // We are lawfully wedded now. eng_adverb:unlawfully{}, // They were unlawfully married. eng_adverb:soon{}, // An unwise investor is soon impoverished. eng_adverb:irretrievably{}, // It is irretrievably lost. eng_adverb:morphologically{}, // These two plants are morphologically related. eng_adverb:distinctly{}, // Urbanization in Spain is distinctly correlated with a fall in reproductive rate. eng_adverb:colloidally{}, // Particles were colloidally dispersed in the medium. eng_adverb:unchangeably{}, // His views were unchangeably fixed. eng_adverb:widely{}, // Her work is widely known. eng_adverb:acutely{}, // The visor was acutely peaked. eng_adverb:fearfully{}, // They were fearfully attacked. eng_adverb:directly{}, // These two factors are directly related. eng_adverb:carefully{}, // The breakout was carefully planned. eng_adverb:tautly{}, // The rope was tautly stretched. eng_adverb:temperately{}, // These preferences are temperately stated. eng_adverb:barbarously{}, // They were barbarously murdered. eng_adverb:criminally{}, // The garden was criminally neglected. eng_adverb:becomingly{}, // She was becomingly dressed. eng_adverb:chaotically{}, // The room was chaotically disorganized. eng_adverb:crushingly{}, // The team was crushingly defeated. eng_adverb:dishonorably{}, // He was dishonorably discharged. eng_adverb:honorably{}, // He was honorably discharged after many years of service. eng_adverb:elegantly{}, // The room was elegantly decorated. eng_adverb:ecclesiastically{}, // The candidate was ecclesiastically endorsed. eng_adverb:stockily{}, // He was stockily built. eng_adverb:trimly{}, // He was trimly attired. eng_adverb:shockingly{}, // Teachers were shockingly underpaid. eng_adverb:seasonally{}, // Prices are seasonally adjusted. eng_adverb:romantically{}, // They were romantically linked. eng_adverb:robustly{}, // He was robustly built. eng_adverb:pungently{}, // The soup was pungently flavored. eng_adverb:spaciously{}, // The furniture was spaciously spread out. eng_adverb:spicily{}, // The soup was spicily flavored. eng_adverb:sumptuously{}, // This government building is sumptuously appointed. eng_adverb:amply{}, // These voices were amply represented. eng_adverb:slenderly{}, // The area is slenderly endowed with natural resources. eng_adverb:meagerly{}, // These voices are meagerly represented at the conference. eng_adverb:maniacally{}, // He was maniacally obsessed with jealousy. eng_adverb:lukewarmly{}, // He was lukewarmly received by his relatives. eng_adverb:sketchily{}, // The dishes were only sketchily washed. eng_adverb:quaintly{}, // The room was quaintly furnished. eng_adverb:meretriciously{}, // The boat is meretriciously decorated. eng_adverb:substantially{}, // The house was substantially built. eng_adverb:incomparably{}, // She is incomparably gifted. eng_adverb:inadequately{}, // The temporary camps were inadequately equipped. eng_adverb:adequately{}, // He was adequately prepared. eng_adverb:unhygienically{}, // The meat is unhygienically processed on wooden tables. eng_adverb:hermetically{}, // This bag is hermetically sealed. eng_adverb:heinously{}, // The child was heinously murdered. eng_adverb:gruesomely{}, // He was gruesomely wounded. eng_adverb:glossily{}, // The magazine was glossily printed. eng_adverb:garishly{}, // The temple was garishly decorated with bright plastic flowers. eng_adverb:fraudulently{}, // This money was fraudulently obtained. eng_adverb:foully{}, // Two policemen were foully murdered. eng_adverb:flimsily{}, // This car is so flimsily constructed! eng_adverb:faultily{}, // These statements were faultily attributed to me. eng_adverb:fancifully{}, // The Christmas tree was fancifully decorated. eng_adverb:necessarily{}, // Such expenses are necessarily incurred. eng_adverb:totally{} // The car was totally destroyed in the crash }
Judicially controlled process
eng_adverb:Judicially{},
12,917,206
[ 1, 46, 1100, 335, 6261, 25934, 1207, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 24691, 67, 361, 16629, 30, 46, 1100, 335, 6261, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]