file_name
stringlengths 71
779k
| comments
stringlengths 20
182k
| code_string
stringlengths 20
36.9M
| __index_level_0__
int64 0
17.2M
| input_ids
list | attention_mask
list | labels
list |
---|---|---|---|---|---|---|
pragma solidity ^0.5.0;
/// @author Praveen B Shenoy
/// @title Marketplace - setting up an online marketplace
import './zeppelin/lifecycle/Killable.sol';
contract Marketplace is Killable {
/* set owner */
address private owner;
/* variable to handle emergencies, and impose circuit breakers */
bool private emergency;
/* stores user id temporarily */
uint private id;
/* capture all users */
mapping (address => User) private users;
/* capture group of admins */
mapping (address => bool) public isAdmin; // allow contracts to see if user is an Admin
uint public adminCount; // stores a running count of the admins
/* capture store owners */
mapping (address => bool) public isStoreOwner; // allow contracts to see if user is a store owner
uint public storeOwnerCount; // stores a running count of store owners
//mapping (address => uint) public storeOwnerId;
/* capture online shoppers */
mapping (address => bool) public isOnlineShopper; // allow contracts to see if user is an online shoppers
uint public onlineShopperCount; // stores a running count of online shoppers
//mapping (address => User) private onlineShoppers;
/* capture store fronts */
mapping (uint => StoreFront) public storeFronts; // all store fronts
mapping (address => StoreFront[]) public filteredStoreFronts; // all store fronts for a particular store owner
mapping (bytes32 => bool) public isExistingStoreFront; // allow contracts to check if store front name is unique
uint public storeFrontCount; // stores a running count of the store fronts created
bytes32[] allStoreFronts; // an array of all store front names
//mapping (uint => StoreFront[]) public allStoreFronts;
//mapping (address => uint) public storeFrontId;
/* capture store products */
mapping (uint => Product) public products; // all products
mapping (address => mapping (uint => Product[])) public storeOwnerStoreFrontProducts; // mapping of owner to store front to products
mapping (uint => Product[]) public storeFrontProducts; //mapping of store front to products
uint public productCount; // running count of all products
/* structure pertaining to a User */
struct User {
bytes32 name; // user name
bytes32 userRole; // user role can be admin, store owner or online shopper
}
/* structure pertaining to a store front */
struct StoreFront {
uint storeFrontNumber; // a unique number assigned to each store front
bytes32 storeFrontName; // store front name
address storeOwner; // address of the store owner
}
/* structure pertaining to a product */
struct Product {
uint productNumber; // a unique number assigned to each product
bytes32 productName; // product name
uint quantity; // product quantity currnetly available in the store
uint unitPrice; // unit price (selling price) of the product
uint storeFrontNumber; // store front number of the store where the product belongs
address storeOwner; // address of the store owner
}
/* events */
event AdminAdded(address indexed admin); // emitted each time a new admin is added
event StoreOwnerAdded(address indexed storeOwner); // emitted each time a new store owner is added
event OnlineShopperAdded(address indexed onlineShopper); // emitted each time a new online shopper signs-up
event StoreFrontAdded(uint indexed storeFrontNumber,
bytes32 indexed storeFrontName,
address indexed storeOwner); // emitted each time a new store front is created
event StoreFrontProductAdded(uint indexed productNumber,
bytes32 productName,
uint quantity,
uint unitPrice,
uint indexed storeFrontNumber,
address indexed storeOwner); // emitted each time a new product is added
event LogEmergencyStatus(bool emergencyStatus); // emitted each time emergency is set or released for circuit breaker
/* modifiers */
/* check there is no emergency currently */
modifier noEmergency() {
require(!(emergency));
_;
}
/* check input name is not blank */
modifier onlyValidName(bytes32 name) {
require(!(name == 0x0));
_;
}
/* check input number is greater than or equal to 0 */
modifier onlyValidNumber(uint number) {
require(!(number >= 0));
_;
}
/* check if user already exists during login */
modifier onlyExistingUser(address _entrant) {
require(!(users[_entrant].name == 0x0));
_;
}
/* check input address is not blank */
modifier onlyValidAddress(address inputAddress) {
require(inputAddress != address(0x0));
_;
}
/* check new store front name is not a duplicate */
modifier onlyValidStoreFront(bytes32 name) {
require(!(isExistingStoreFront[name]));
_;
}
/* set the owner to the creator of this contract
owner will also be the default admin */
constructor() public {
owner = msg.sender;
users[msg.sender].name = "Admin";
users[msg.sender].userRole = "Admin";
isAdmin[msg.sender] = true;
adminCount += 1;
emit AdminAdded(msg.sender);
}
/// @notice function to set or release an emergency by setting the emergency flag
/// setting the emergency flag stop key business functions performed by store owners or online onlineShoppers
/// like adding stores fronts, or making purchases
/// Only admins can set or release the emergency flag
///@return emergency flag will be returned with the right status
function toggleEmergency()
public
payable
returns (bool emergencyStatus) {
require(isAdmin[msg.sender]);
emergency = !emergency;
emit LogEmergencyStatus(emergency);
return emergency;
}
/// @notice check is user exists and return user role
/// @return the name of the person logged in
function login() view
public
onlyExistingUser(msg.sender)
returns (bytes32) {
return (users[msg.sender].name);
}
/// @notice sign up as online shopper only:
/// check if user exists, if yes, return user name;
/// if no, check if name was sent, if yes, create and return user
/// @param name of the person signing up
/// @return the name of the person signed up
function signup(bytes32 name)
public
payable
onlyValidName(name)
returns (bytes32) {
if (users[msg.sender].name == 0x0) {
users[msg.sender].name = name;
users[msg.sender].userRole = "OnlineShopper";
isOnlineShopper[msg.sender] = true;
onlineShopperCount += 1;
emit OnlineShopperAdded(msg.sender);
return (users[msg.sender].name);
}
return (users[msg.sender].name);
}
/// @notice function to update user name only
/// requires new user name is not blank
/// requester to be an existing user and can only change his/her name
/// @param name to be updated as
/// @return updated name of the user
function update(bytes32 name)
public
payable
onlyValidName(name)
onlyExistingUser(msg.sender)
returns (bytes32) {
if (users[msg.sender].name != 0x0) {
users[msg.sender].name = name;
return (users[msg.sender].name);
}
}
/// @notice function to set up a new admin
/// requires new admin name and address are not blank
/// requester needs to be an existing admin
/// @param newAdminName newAdminAddress
/// @return userName of the newly added admin
function addAdmin(bytes32 newAdminName, address newAdminAddress)
public
payable
onlyValidName(newAdminName)
onlyValidAddress(newAdminAddress)
returns(bytes32 userName) {
if (users[newAdminAddress].name == 0x0) {
/* only admins should be able to add other admins */
require(isAdmin[msg.sender]);
users[newAdminAddress].name = newAdminName;
users[newAdminAddress].userRole = "Admin";
isAdmin[newAdminAddress] = true;
adminCount += 1;
emit AdminAdded(newAdminAddress);
return (users[newAdminAddress].name);
}
return (users[newAdminAddress].name);
}
/// @notice function to set up a new store owner
/// requires new store owner name and address are not blank
/// requester needs to be an existing admin
/// @param newStoreOwner newStoreOwnerAddress
/// @return userName of the newly added store owner
function addStoreOwner(bytes32 newStoreOwner, address newStoreOwnerAddress)
public
payable
onlyValidName(newStoreOwner)
onlyValidAddress (newStoreOwnerAddress)
returns(bytes32 userName) {
if (users[newStoreOwnerAddress].name == 0x0) {
/* only admins should be able to add store owners */
require(isAdmin[msg.sender]);
users[newStoreOwnerAddress].name = newStoreOwner;
users[newStoreOwnerAddress].userRole = "StoreOwner";
isStoreOwner[newStoreOwnerAddress] = true;
//storeOwnerId[newStoreOwnerAddress] = storeOwnerCount;
storeOwnerCount += 1;
emit StoreOwnerAdded(newStoreOwnerAddress);
return (users[newStoreOwnerAddress].name);
}
return users[newStoreOwnerAddress].name;
}
/// @notice function to set up a new store front
/// requires new store front name is not blank
/// requester needs to be an existing store owner
/// @param newStoreFrontName for the store front to be added
/// @return newStoreFrontName of the newly added store front
function addStoreFront(bytes32 newStoreFrontName)
public
payable
onlyValidName(newStoreFrontName)
onlyValidStoreFront(newStoreFrontName)
noEmergency()
returns(bytes32 storeFrontName) {
require(isStoreOwner[msg.sender]);
storeFronts[storeFrontCount].storeFrontNumber = storeFrontCount;
storeFronts[storeFrontCount].storeFrontName = newStoreFrontName;
storeFronts[storeFrontCount].storeOwner = msg.sender;
filteredStoreFronts[msg.sender].push(storeFronts[storeFrontCount]);
allStoreFronts.push(newStoreFrontName);
isExistingStoreFront[newStoreFrontName] = true;
emit StoreFrontAdded(storeFrontCount, newStoreFrontName, msg.sender);
storeFrontCount += 1;
return newStoreFrontName;
}
/// @notice function to retrieve store front names of the requester
/// @return storeFrontNames belonging to the requester
function getMyStoreFronts()
public
view
returns (bytes32[] memory storeFrontNames) {
for (uint i=0; i < filteredStoreFronts[msg.sender].length; i++) {
storeFrontNames[i] = filteredStoreFronts[msg.sender][i].storeFrontName;
}
return storeFrontNames;
}
/// @notice function to retrieve all available store fronts
/// @return allStoreFrontNames
function getAllStoreFronts()
public
view
returns (bytes32[] memory storeFrontNames) {
return allStoreFronts;
}
/// @notice function to add a product to a store front
/// requires new product name is not blank; quantity and unit price >= 0
/// requester needs to be owner of the store front where the product is being added
/// @param storeFrontNumber productName quantity unitPrice
/// @return storeProductName of the newly added product
function addStoreProducts(uint storeFrontNumber, bytes32 productName, uint quantity, uint unitPrice)
public
payable
onlyValidName(productName)
onlyValidNumber(quantity)
onlyValidNumber(unitPrice)
noEmergency()
returns (bytes32 storeProductName) {
require(storeFronts[storeFrontNumber].storeOwner == msg.sender,"Only store front owners can add products to their store front");
products[productCount] = Product({
productNumber: productCount,
productName: productName,
quantity: quantity,
unitPrice: unitPrice,
storeFrontNumber: storeFrontNumber,
storeOwner: msg.sender
});
storeOwnerStoreFrontProducts[msg.sender][storeFrontNumber].push(products[productCount]);
storeFrontProducts[storeFrontNumber].push(products[productCount]);
emit StoreFrontProductAdded(productCount, productName, quantity, unitPrice, storeFrontNumber, msg.sender);
productCount += 1;
return productName;
}
/// @notice function to retrieve all products in a store front
/// @param storeFrontNumber for which products to be retrieved
/// @return storeFrontProductNames of all products in the store front
function getStoreFrontProducts(uint storeFrontNumber)
public
view
returns (bytes32[] memory storeFrontProductNames) {
for (uint i=0; i < storeFrontProducts[storeFrontNumber].length; i++) {
storeFrontProductNames[i] = storeFrontProducts[storeFrontNumber][i].productName;
}
return storeFrontProductNames;
}
}
|
a unique number assigned to each store front
|
uint storeFrontNumber;
| 5,425,509 |
[
1,
69,
3089,
1300,
6958,
358,
1517,
1707,
6641,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1377,
2254,
1707,
9580,
1854,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.4.24;
import "../../interfaces/FutureERC721.sol";
import "zeppelin-solidity/contracts/token/ERC721/ERC721Token.sol";
import "zeppelin-solidity/contracts/ownership/Ownable.sol";
import "zeppelin-solidity/contracts/math/SafeMath.sol";
contract FutureERC721Token is ERC721Token, Ownable, FutureERC721 {
using SafeMath for uint256;
uint tokenIdCounter = 0;
int tokenPosition_;
// (tokenId > future data)
mapping(uint => uint) public tokenBuyingPrice; // The price when they buy the token
mapping(uint => uint) public tokenDeposit; // Their actual deposit
mapping(uint => bool) public tokenValid; // Is valid or not (A token can be invalidated on a check position or after clear)
constructor(string _name, string _symbol, int _tokenPosition) ERC721Token(_name, _symbol) public {
require(_tokenPosition == -1 || _tokenPosition == 1, "Position should be either short or long");
tokenPosition_ = _tokenPosition;
}
function _setFutureData(uint _tokenId, uint _deposit, uint _buyingPrice) internal {
tokenBuyingPrice[_tokenId] = _buyingPrice;
tokenDeposit[_tokenId] = _deposit;
tokenValid[_tokenId] = true;
}
function _mint(
address _to,
uint _deposit,
uint _buyingPrice
) internal {
require(_to != 0x0, "Can't mint to the empty address");
require(_deposit > 0 && _buyingPrice > 0, "Deposit and initial price can't be zero");
super._mint(_to, tokenIdCounter);
_setFutureData(tokenIdCounter, _deposit, _buyingPrice);
tokenIdCounter = tokenIdCounter.add(1);
}
function mint(
address _to,
uint _deposit,
uint _buyingPrice
) external onlyOwner returns (bool) {
_mint(_to,_deposit,_buyingPrice);
return true;
}
function mintMultiple(
address _to,
uint _deposit,
uint _buyingPrice,
uint _total
) external onlyOwner returns(bool) {
for(uint i = 0; i < _total; i++){
_mint(_to,_deposit,_buyingPrice);
}
return true;
}
function invalidateToken(uint _tokenId) external onlyOwner {
tokenValid[_tokenId] = false;
}
function invalidateTokens(uint[] _tokens) external onlyOwner {
for(uint i = 0; i < _tokens.length; i++){
tokenValid[_tokens[i]] = false;
}
}
function isTokenValid(uint _tokenId) external view returns (bool _tokenValid) {
return tokenValid[_tokenId];
}
function getBuyingPrice(uint _tokenId) external view returns (uint _buyingPrice){
return tokenBuyingPrice[_tokenId];
}
function getDeposit(uint _tokenId) external view returns (uint _deposit){
return tokenDeposit[_tokenId];
}
function tokenPosition() external view returns (int _tokenPosition){
return tokenPosition_;
}
function getTokenIdsByOwner(address _owner) external view returns (uint[] _tokenIds){
return ownedTokens[_owner];
}
function getValidTokenIdsByOwner(address _owner) external view returns (uint[] _tokenIds){
return getValidTokensList(ownedTokens[_owner]);
}
function getValidTokens() external view returns(uint[] memory) {
return getValidTokensList(allTokens);
}
function getValidTokensList(uint[] _tokens) internal view returns(uint[] memory _validTokens ) {
uint _length = 0;
uint i;
for(i = 0; i < _tokens.length; i++) {
if(tokenValid[_tokens[i]]) { _length++; }
}
_validTokens = new uint[](_length);
uint _counter = 0;
for(i = 0; i < _tokens.length; i++) {
if(tokenValid[_tokens[i]]) {
_validTokens[_counter] = _tokens[i];
_counter++;
}
}
return _validTokens;
}
}
|
Their actual deposit
|
mapping(uint => uint) public tokenDeposit;
| 5,407,400 |
[
1,
1986,
481,
3214,
443,
1724,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2874,
12,
11890,
516,
2254,
13,
1071,
1147,
758,
1724,
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
] |
./full_match/1/0xa5C23987673d45Eb4b3925581C7984bb1e8D9BE7/sources/browser/V2_Uniswap_Swap.sol
|
address[] memory path = getPath(_fromToken, _toToken); (uint[] memory returnedAmount, ) = this.getEstimatedTokens(_amount, _fromToken, _toToken); uint256 minOut = returnedAmount[1].mul(percentage_unit.sub(maxSlippage)).div(percentage_unit);uint[] memory output = IUniswapV2Router02(rout).swapExactTokensForTokens(in_amount, minOut, path, receiver, deadline);uint256 post = ;return output[output.length - 1];
|
function GetTokenFromAnotherToken(uint256 in_amount, uint256 out_amount, address[] memory path, address payable receiver) internal returns (uint256){
uint256 minOut = out_amount.mul(percentage_unit.sub(maxSlippage)).div(percentage_unit);
uint256 pre = IERC20(path[path.length - 1]).balanceOf(receiver);
IERC20(path[0]).safeApprove(rout, in_amount);
IUniswapV2Router02(rout).swapExactTokensForTokensSupportingFeeOnTransferTokens(in_amount, minOut, path, receiver, deadline);
IERC20(path[0]).safeDecreaseAllowance(rout, IERC20(path[0]).allowance(address(this), rout));
return (IERC20(path[path.length - 1]).balanceOf(receiver)).sub(pre);
}
| 16,498,279 |
[
1,
2867,
8526,
3778,
589,
273,
4339,
24899,
2080,
1345,
16,
389,
869,
1345,
1769,
261,
11890,
8526,
3778,
2106,
6275,
16,
262,
273,
333,
18,
588,
9122,
17275,
5157,
24899,
8949,
16,
389,
2080,
1345,
16,
389,
869,
1345,
1769,
2254,
5034,
1131,
1182,
273,
2106,
6275,
63,
21,
8009,
16411,
12,
18687,
67,
4873,
18,
1717,
12,
1896,
55,
3169,
2433,
13,
2934,
2892,
12,
18687,
67,
4873,
1769,
11890,
8526,
3778,
876,
273,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
12,
7028,
2934,
22270,
14332,
5157,
1290,
5157,
12,
267,
67,
8949,
16,
1131,
1182,
16,
589,
16,
5971,
16,
14096,
1769,
11890,
5034,
1603,
273,
274,
2463,
876,
63,
2844,
18,
2469,
300,
404,
15533,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
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,
968,
1345,
1265,
37,
24413,
1345,
12,
11890,
5034,
316,
67,
8949,
16,
2254,
5034,
596,
67,
8949,
16,
1758,
8526,
3778,
589,
16,
1758,
8843,
429,
5971,
13,
2713,
1135,
261,
11890,
5034,
15329,
203,
540,
203,
3639,
2254,
5034,
1131,
1182,
273,
596,
67,
8949,
18,
16411,
12,
18687,
67,
4873,
18,
1717,
12,
1896,
55,
3169,
2433,
13,
2934,
2892,
12,
18687,
67,
4873,
1769,
203,
203,
3639,
2254,
5034,
675,
273,
467,
654,
39,
3462,
12,
803,
63,
803,
18,
2469,
300,
404,
65,
2934,
12296,
951,
12,
24454,
1769,
203,
3639,
467,
654,
39,
3462,
12,
803,
63,
20,
65,
2934,
4626,
12053,
537,
12,
7028,
16,
316,
67,
8949,
1769,
203,
3639,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
12,
7028,
2934,
22270,
14332,
5157,
1290,
5157,
6289,
310,
14667,
1398,
5912,
5157,
12,
267,
67,
8949,
16,
1131,
1182,
16,
589,
16,
5971,
16,
14096,
1769,
203,
3639,
467,
654,
39,
3462,
12,
803,
63,
20,
65,
2934,
4626,
23326,
448,
7009,
1359,
12,
7028,
16,
467,
654,
39,
3462,
12,
803,
63,
20,
65,
2934,
5965,
1359,
12,
2867,
12,
2211,
3631,
3237,
10019,
203,
540,
203,
203,
3639,
327,
261,
45,
654,
39,
3462,
12,
803,
63,
803,
18,
2469,
300,
404,
65,
2934,
12296,
951,
12,
24454,
13,
2934,
1717,
12,
1484,
1769,
203,
202,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x8430Be7B8fd28Cc58EA70A25C9c7A624F26f5D09/sources/src/core/Decoder.sol
|
ROLLUP_HEADER_LENGTH - 0x20
|
uint256 internal constant ROLLUP_BENEFICIARY_OFFSET = 4512;
| 4,874,593 |
[
1,
14555,
3079,
67,
7557,
67,
7096,
300,
374,
92,
3462,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
2254,
5034,
2713,
5381,
534,
30922,
3079,
67,
38,
1157,
41,
1653,
7266,
6043,
67,
11271,
273,
12292,
2138,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
library SafeMath {
function ADD388(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB906(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB906(a, b, "SafeMath: subtraction overflow");
}
function SUB906(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 MUL601(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 DIV456(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV456(a, b, "SafeMath: division by zero");
}
function DIV456(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD78(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD78(a, b, "SafeMath: modulo by zero");
}
function MOD78(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
abstract contract Context {
function _MSGSENDER877() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA207() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
interface IERC20 {
function TOTALSUPPLY738() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF68(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER734(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE35(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE429(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM531(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER657(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL956(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
// File: contracts/utils/Address.sol
library Address {
function ISCONTRACT600(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
// 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;
}
function SENDVALUE944(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function FUNCTIONCALL15(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALL15(target, data, "Address: low-level call failed");
}
function FUNCTIONCALL15(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return _FUNCTIONCALLWITHVALUE358(target, data, 0, errorMessage);
}
function FUNCTIONCALLWITHVALUE499(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALLWITHVALUE499(target, data, value, "Address: low-level call with value failed");
}
function FUNCTIONCALLWITHVALUE499(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING
require(address(this).balance >= value, "Address: insufficient balance for call");
return _FUNCTIONCALLWITHVALUE358(target, data, value, errorMessage);
}
function _FUNCTIONCALLWITHVALUE358(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING
require(ISCONTRACT600(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: contracts/token/ERC20/ERC20.sol
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
function NAME254() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL669() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS84() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
function TOTALSUPPLY738() public view override returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF68(address account) public view override returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER734(address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER67(_MSGSENDER877(), recipient, amount);
return true;
}
function ALLOWANCE35(address owner, address spender) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE429(address spender, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_APPROVE455(_MSGSENDER877(), spender, amount);
return true;
}
function TRANSFERFROM531(address sender, address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER67(sender, recipient, amount);
_APPROVE455(sender, _MSGSENDER877(), _allowances[sender][_MSGSENDER877()].SUB906(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE275(address spender, uint256 addedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE455(_MSGSENDER877(), spender, _allowances[_MSGSENDER877()][spender].ADD388(addedValue));
return true;
}
function DECREASEALLOWANCE402(address spender, uint256 subtractedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE455(_MSGSENDER877(), spender, _allowances[_MSGSENDER877()][spender].SUB906(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER67(address sender, address recipient, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_BEFORETOKENTRANSFER81(sender, recipient, amount);
_balances[sender] = _balances[sender].SUB906(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD388(amount);
emit TRANSFER657(sender, recipient, amount);
}
function _MINT823(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_BEFORETOKENTRANSFER81(address(0), account, amount);
_totalSupply = _totalSupply.ADD388(amount);
_balances[account] = _balances[account].ADD388(amount);
emit TRANSFER657(address(0), account, amount);
}
function _BURN465(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_BEFORETOKENTRANSFER81(account, address(0), amount);
_balances[account] = _balances[account].SUB906(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB906(amount);
emit TRANSFER657(account, address(0), amount);
}
function _APPROVE455(address owner, address spender, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit APPROVAL956(owner, spender, amount);
}
function _SETUPDECIMALS854(uint8 decimals_) internal { //inject NONSTANDARD NAMING
_decimals = decimals_;
}
function _BEFORETOKENTRANSFER81(address from, address to, uint256 amount) internal virtual { } //inject NONSTANDARD NAMING
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function SAFETRANSFER331(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN31(token, abi.encodeWithSelector(token.TRANSFER734.selector, to, value));
}
function SAFETRANSFERFROM748(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN31(token, abi.encodeWithSelector(token.TRANSFERFROM531.selector, from, to, value));
}
function SAFEAPPROVE284(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.ALLOWANCE35(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_CALLOPTIONALRETURN31(token, abi.encodeWithSelector(token.APPROVE429.selector, spender, value));
}
function SAFEINCREASEALLOWANCE243(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE35(address(this), spender).ADD388(value);
_CALLOPTIONALRETURN31(token, abi.encodeWithSelector(token.APPROVE429.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE653(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE35(address(this), spender).SUB906(value, "SafeERC20: decreased allowance below zero");
_CALLOPTIONALRETURN31(token, abi.encodeWithSelector(token.APPROVE429.selector, spender, newAllowance));
}
function _CALLOPTIONALRETURN31(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).FUNCTIONCALL15(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 IVault is IERC20 {
function TOKEN190() external view returns (address); //inject NONSTANDARD NAMING
function DECIMALS84() external view returns (uint8); //inject NONSTANDARD NAMING
function EARN763() external; //inject NONSTANDARD NAMING
function DEPOSIT115(uint256) external; //inject NONSTANDARD NAMING
function DEPOSITALL187() external; //inject NONSTANDARD NAMING
function WITHDRAW593(uint256) external; //inject NONSTANDARD NAMING
function WITHDRAWALL63() external; //inject NONSTANDARD NAMING
function DISTRIBUTE67() external; //inject NONSTANDARD NAMING
function SALVAGE929(address, uint256) external; //inject NONSTANDARD NAMING
function GETRATIO675() external view returns (uint256); //inject NONSTANDARD NAMING
}
interface ICurveFi_2 {
function GET_VIRTUAL_PRICE809() external view returns (uint256); //inject NONSTANDARD NAMING
function ADD_LIQUIDITY50(uint256[2] calldata amounts, uint256 min_mint_amount) //inject NONSTANDARD NAMING
external;
function REMOVE_LIQUIDITY_IMBALANCE11( //inject NONSTANDARD NAMING
uint256[2] calldata amounts,
uint256 max_burn_amount
) external;
function REMOVE_LIQUIDITY517(uint256 _amount, uint256[2] calldata amounts) //inject NONSTANDARD NAMING
external;
function EXCHANGE792( //inject NONSTANDARD NAMING
int128 from,
int128 to,
uint256 _from_amount,
uint256 _min_to_amount
) external;
function BALANCES2(int128) external view returns (uint256); //inject NONSTANDARD NAMING
}
interface ICurve3Pool {
function GET_VIRTUAL_PRICE809() external view returns (uint256); //inject NONSTANDARD NAMING
function ADD_LIQUIDITY50(uint256[3] calldata amounts, uint256 min_mint_amount) //inject NONSTANDARD NAMING
external;
function REMOVE_LIQUIDITY_IMBALANCE11( //inject NONSTANDARD NAMING
uint256[3] calldata amounts,
uint256 max_burn_amount
) external;
function REMOVE_LIQUIDITY517(uint256 _amount, uint256[3] calldata amounts) //inject NONSTANDARD NAMING
external;
function EXCHANGE792( //inject NONSTANDARD NAMING
int128 from,
int128 to,
uint256 _from_amount,
uint256 _min_to_amount
) external;
function BALANCES2(uint256) external view returns (uint256); //inject NONSTANDARD NAMING
}
interface ICurveFi_4 {
function GET_VIRTUAL_PRICE809() external view returns (uint256); //inject NONSTANDARD NAMING
function ADD_LIQUIDITY50(uint256[4] calldata amounts, uint256 min_mint_amount) //inject NONSTANDARD NAMING
external;
function REMOVE_LIQUIDITY_IMBALANCE11( //inject NONSTANDARD NAMING
uint256[4] calldata amounts,
uint256 max_burn_amount
) external;
function REMOVE_LIQUIDITY517(uint256 _amount, uint256[4] calldata amounts) //inject NONSTANDARD NAMING
external;
function EXCHANGE792( //inject NONSTANDARD NAMING
int128 from,
int128 to,
uint256 _from_amount,
uint256 _min_to_amount
) external;
function BALANCES2(int128) external view returns (uint256); //inject NONSTANDARD NAMING
}
interface ICurveZap_4 {
function ADD_LIQUIDITY50( //inject NONSTANDARD NAMING
uint256[4] calldata uamounts,
uint256 min_mint_amount
) external;
function REMOVE_LIQUIDITY517(uint256 _amount, uint256[4] calldata min_uamounts) //inject NONSTANDARD NAMING
external;
function REMOVE_LIQUIDITY_IMBALANCE11( //inject NONSTANDARD NAMING
uint256[4] calldata uamounts,
uint256 max_burn_amount
) external;
function CALC_WITHDRAW_ONE_COIN560(uint256 _token_amount, int128 i) //inject NONSTANDARD NAMING
external
returns (uint256);
function REMOVE_LIQUIDITY_ONE_COIN125( //inject NONSTANDARD NAMING
uint256 _token_amount,
int128 i,
uint256 min_uamount
) external;
function REMOVE_LIQUIDITY_ONE_COIN125( //inject NONSTANDARD NAMING
uint256 _token_amount,
int128 i,
uint256 min_uamount,
bool donate_dust
) external;
function WITHDRAW_DONATED_DUST417() external; //inject NONSTANDARD NAMING
function COINS352(int128 arg0) external returns (address); //inject NONSTANDARD NAMING
function UNDERLYING_COINS1(int128 arg0) external returns (address); //inject NONSTANDARD NAMING
function CURVE335() external returns (address); //inject NONSTANDARD NAMING
function TOKEN190() external returns (address); //inject NONSTANDARD NAMING
}
interface ICurveZap {
function REMOVE_LIQUIDITY_ONE_COIN125( //inject NONSTANDARD NAMING
uint256 _token_amount,
int128 i,
uint256 min_uamount
) external;
}
interface ICurveGauge {
function DEPOSIT115(uint256 _value) external; //inject NONSTANDARD NAMING
function DEPOSIT115(uint256 _value, address addr) external; //inject NONSTANDARD NAMING
function BALANCEOF68(address arg0) external view returns (uint256); //inject NONSTANDARD NAMING
function WITHDRAW593(uint256 _value) external; //inject NONSTANDARD NAMING
function WITHDRAW593(uint256 _value, bool claim_rewards) external; //inject NONSTANDARD NAMING
function CLAIM_REWARDS536() external; //inject NONSTANDARD NAMING
function CLAIM_REWARDS536(address addr) external; //inject NONSTANDARD NAMING
function CLAIMABLE_TOKENS440(address addr) external returns (uint256); //inject NONSTANDARD NAMING
function CLAIMABLE_REWARD978(address addr) external view returns (uint256); //inject NONSTANDARD NAMING
function INTEGRATE_FRACTION797(address arg0) external view returns (uint256); //inject NONSTANDARD NAMING
}
interface ICurveMintr {
function MINT951(address) external; //inject NONSTANDARD NAMING
function MINTED257(address arg0, address arg1) external view returns (uint256); //inject NONSTANDARD NAMING
}
interface ICurveVotingEscrow {
function LOCKED178(address arg0) //inject NONSTANDARD NAMING
external
view
returns (int128 amount, uint256 end);
function LOCKED__END474(address _addr) external view returns (uint256); //inject NONSTANDARD NAMING
function CREATE_LOCK305(uint256, uint256) external; //inject NONSTANDARD NAMING
function INCREASE_AMOUNT922(uint256) external; //inject NONSTANDARD NAMING
function INCREASE_UNLOCK_TIME38(uint256 _unlock_time) external; //inject NONSTANDARD NAMING
function WITHDRAW593() external; //inject NONSTANDARD NAMING
function SMART_WALLET_CHECKER846() external returns (address); //inject NONSTANDARD NAMING
}
interface ICurveSmartContractChecker {
function WALLETS237(address) external returns (bool); //inject NONSTANDARD NAMING
function APPROVEWALLET249(address _wallet) external; //inject NONSTANDARD NAMING
}
interface UniswapRouterV2 {
function SWAPEXACTTOKENSFORTOKENS167( //inject NONSTANDARD NAMING
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function ADDLIQUIDITY947( //inject NONSTANDARD NAMING
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 ADDLIQUIDITYETH996( //inject NONSTANDARD NAMING
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function REMOVELIQUIDITY801( //inject NONSTANDARD NAMING
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function GETAMOUNTSOUT893(uint256 amountIn, address[] calldata path) //inject NONSTANDARD NAMING
external
view
returns (uint256[] memory amounts);
function GETAMOUNTSIN14(uint256 amountOut, address[] calldata path) //inject NONSTANDARD NAMING
external
view
returns (uint256[] memory amounts);
function SWAPETHFOREXACTTOKENS437( //inject NONSTANDARD NAMING
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function SWAPEXACTETHFORTOKENS898( //inject NONSTANDARD NAMING
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
}
interface IUniswapV2Pair {
event APPROVAL956( //inject NONSTANDARD NAMING
address indexed owner,
address indexed spender,
uint256 value
);
event TRANSFER657(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
function NAME254() external pure returns (string memory); //inject NONSTANDARD NAMING
function SYMBOL669() external pure returns (string memory); //inject NONSTANDARD NAMING
function DECIMALS84() external pure returns (uint8); //inject NONSTANDARD NAMING
function TOTALSUPPLY738() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF68(address owner) external view returns (uint256); //inject NONSTANDARD NAMING
function ALLOWANCE35(address owner, address spender) //inject NONSTANDARD NAMING
external
view
returns (uint256);
function APPROVE429(address spender, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFER734(address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM531( //inject NONSTANDARD NAMING
address from,
address to,
uint256 value
) external returns (bool);
function DOMAIN_SEPARATOR578() external view returns (bytes32); //inject NONSTANDARD NAMING
function PERMIT_TYPEHASH551() external pure returns (bytes32); //inject NONSTANDARD NAMING
function NONCES443(address owner) external view returns (uint256); //inject NONSTANDARD NAMING
function PERMIT326( //inject NONSTANDARD NAMING
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
event MINT405(address indexed sender, uint256 amount0, uint256 amount1); //inject NONSTANDARD NAMING
event BURN673( //inject NONSTANDARD NAMING
address indexed sender,
uint256 amount0,
uint256 amount1,
address indexed to
);
event SWAP227( //inject NONSTANDARD NAMING
address indexed sender,
uint256 amount0In,
uint256 amount1In,
uint256 amount0Out,
uint256 amount1Out,
address indexed to
);
event SYNC504(uint112 reserve0, uint112 reserve1); //inject NONSTANDARD NAMING
function MINIMUM_LIQUIDITY881() external pure returns (uint256); //inject NONSTANDARD NAMING
function FACTORY729() external view returns (address); //inject NONSTANDARD NAMING
function TOKEN0644() external view returns (address); //inject NONSTANDARD NAMING
function TOKEN1449() external view returns (address); //inject NONSTANDARD NAMING
function GETRESERVES964() //inject NONSTANDARD NAMING
external
view
returns (
uint112 reserve0,
uint112 reserve1,
uint32 blockTimestampLast
);
function PRICE0CUMULATIVELAST588() external view returns (uint256); //inject NONSTANDARD NAMING
function PRICE1CUMULATIVELAST951() external view returns (uint256); //inject NONSTANDARD NAMING
function KLAST390() external view returns (uint256); //inject NONSTANDARD NAMING
function MINT951(address to) external returns (uint256 liquidity); //inject NONSTANDARD NAMING
function BURN57(address to) //inject NONSTANDARD NAMING
external
returns (uint256 amount0, uint256 amount1);
function SWAP519( //inject NONSTANDARD NAMING
uint256 amount0Out,
uint256 amount1Out,
address to,
bytes calldata data
) external;
function SKIM366(address to) external; //inject NONSTANDARD NAMING
function SYNC84() external; //inject NONSTANDARD NAMING
}
interface IUniswapV2Factory {
event PAIRCREATED988( //inject NONSTANDARD NAMING
address indexed token0,
address indexed token1,
address pair,
uint256
);
function GETPAIR36(address tokenA, address tokenB) //inject NONSTANDARD NAMING
external
view
returns (address pair);
function ALLPAIRS303(uint256) external view returns (address pair); //inject NONSTANDARD NAMING
function ALLPAIRSLENGTH195() external view returns (uint256); //inject NONSTANDARD NAMING
function FEETO341() external view returns (address); //inject NONSTANDARD NAMING
function FEETOSETTER863() external view returns (address); //inject NONSTANDARD NAMING
function CREATEPAIR664(address tokenA, address tokenB) //inject NONSTANDARD NAMING
external
returns (address pair);
}
interface ICurveTBTC {
function ADD_LIQUIDITY50( //inject NONSTANDARD NAMING
uint256[4] calldata amounts,
uint256 min_mint_amount
) external returns (uint256);
}
interface IKeepRewardsClaimable {
function CLAIM_REWARDS536() external; //inject NONSTANDARD NAMING
}
// Base of all strategy contracts
abstract contract VoxStrategyBase {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
// Perfomance fees
uint256 public treasuryFee = 1000;
uint256 public constant treasuryfeemax584 = 2000; //inject NONSTANDARD NAMING
uint256 public constant treasuryfeebase971 = 10000; //inject NONSTANDARD NAMING
uint256 public strategyFee = 500;
uint256 public constant strategyfeemax620 = 5000; //inject NONSTANDARD NAMING
uint256 public constant strategyfeebase640 = 10000; //inject NONSTANDARD NAMING
uint256 public developerFee = 250;
uint256 public constant developerfeemax597 = 500; //inject NONSTANDARD NAMING
uint256 public constant developerfeebase561 = 10000; //inject NONSTANDARD NAMING
// Withdrawal fee
uint256 public withdrawalFee = 15;
uint256 public constant withdrawalfeemax274 = 15; //inject NONSTANDARD NAMING
uint256 public constant withdrawalfeebase605 = 10000; //inject NONSTANDARD NAMING
// Tokens
address public underlying;
address public constant weth339 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; //inject NONSTANDARD NAMING
address public constant wbtc162 = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599; //inject NONSTANDARD NAMING
// User accounts
address public governance;
address public strategist;
address public treasury;
address public devfund;
address public timelock;
address public vault;
// Dex
address public univ2Router2 = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(
address _underlying,
address _governance,
address _strategist,
address _treasury,
address _devfund,
address _timelock,
address _vault
) public {
require(_underlying != address(0));
require(_governance != address(0));
require(_strategist != address(0));
require(_treasury != address(0));
require(_devfund != address(0));
require(_timelock != address(0));
require(_vault != address(0));
underlying = _underlying;
governance = _governance;
strategist = _strategist;
treasury = _treasury;
devfund = _devfund;
timelock = _timelock;
vault = _vault;
}
// **** Modifiers **** //
modifier RESTRICTED912 { //inject NONSTANDARD NAMING
require(
msg.sender == tx.origin ||
msg.sender == governance ||
msg.sender == strategist
);
_;
}
// **** Views **** //
function BALANCEOFUNDERLYING222() public view returns (uint256) { //inject NONSTANDARD NAMING
return IERC20(underlying).BALANCEOF68(address(this));
}
function BALANCEOFPOOL881() public virtual view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF68() public view returns (uint256) { //inject NONSTANDARD NAMING
return BALANCEOFUNDERLYING222().ADD388(BALANCEOFPOOL881());
}
function GETNAME974() external virtual pure returns (string memory); //inject NONSTANDARD NAMING
// **** Setters **** //
function SETTREASURYFEE502(uint256 _treasuryFee) external { //inject NONSTANDARD NAMING
require(msg.sender == timelock, "!timelock");
treasuryFee = _treasuryFee;
}
function SETSTRATEGYFEE761(uint256 _strategyFee) external { //inject NONSTANDARD NAMING
require(msg.sender == timelock, "!timelock");
strategyFee = _strategyFee;
}
function SETDEVELOPERFEE113(uint256 _developerFee) external { //inject NONSTANDARD NAMING
require(msg.sender == timelock, "!timelock");
developerFee = _developerFee;
}
function SETWITHDRAWALFEE980(uint256 _withdrawalFee) external { //inject NONSTANDARD NAMING
require(msg.sender == timelock, "!timelock");
withdrawalFee = _withdrawalFee;
}
function SETSTRATEGIST654(address _strategist) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
strategist = _strategist;
}
function SETGOVERNANCE136(address _governance) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
governance = _governance;
}
function SETTREASURY187(address _treasury) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
treasury = _treasury;
}
function SETDEVFUND591(address _devfund) external { //inject NONSTANDARD NAMING
require(msg.sender == devfund, "!devfund");
devfund = _devfund;
}
function SETTIMELOCK277(address _timelock) external { //inject NONSTANDARD NAMING
require(msg.sender == timelock, "!timelock");
timelock = _timelock;
}
// **** State mutations **** //
function DEPOSIT115() public virtual; //inject NONSTANDARD NAMING
// Governance only function to salvage non-underlying assets
function SALVAGE929(IERC20 _asset) external returns (uint256 balance) { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
require(underlying != address(_asset), "underlying");
balance = _asset.BALANCEOF68(address(this));
_asset.SAFETRANSFER331(treasury, balance);
}
// Withdraw partial funds, normally used with a vault withdrawal
function WITHDRAW593(uint256 _amount) external { //inject NONSTANDARD NAMING
require(msg.sender == vault, "!vault");
uint256 _balance = IERC20(underlying).BALANCEOF68(address(this));
if (_balance < _amount) {
_amount = _WITHDRAWSOME235(_amount.SUB906(_balance));
_amount = _amount.ADD388(_balance);
}
uint256 _withdrawalFee = _amount.MUL601(withdrawalFee).DIV456(withdrawalfeebase605);
IERC20(underlying).SAFETRANSFER331(treasury, _withdrawalFee);
require(vault != address(0), "!vault"); // additional protection so we don't burn the funds
IERC20(underlying).SAFETRANSFER331(vault, _amount.SUB906(_withdrawalFee));
}
// Withdraw all funds, normally used when migrating strategies
function WITHDRAWALL63() external RESTRICTED912 returns (uint256 balance) { //inject NONSTANDARD NAMING
_WITHDRAWALL78();
balance = IERC20(underlying).BALANCEOF68(address(this));
require(vault != address(0), "!vault"); // additional protection so we don't burn the funds
IERC20(underlying).SAFETRANSFER331(vault, balance);
}
function _WITHDRAWALL78() internal { //inject NONSTANDARD NAMING
_WITHDRAWSOME235(BALANCEOFPOOL881());
}
function _WITHDRAWSOME235(uint256 _amount) internal virtual returns (uint256); //inject NONSTANDARD NAMING
function HARVEST372() public virtual; //inject NONSTANDARD NAMING
function _DISTRIBUTEANDDEPOSIT388() internal { //inject NONSTANDARD NAMING
uint256 _underlying = IERC20(underlying).BALANCEOF68(address(this));
if (_underlying > 0) {
// Treasury fees
IERC20(underlying).SAFETRANSFER331(
treasury,
_underlying.MUL601(treasuryFee).DIV456(treasuryfeebase971)
);
// Strategy fee
IERC20(underlying).SAFETRANSFER331(
strategist,
_underlying.MUL601(strategyFee).DIV456(strategyfeebase640)
);
// Developer fee
IERC20(underlying).SAFETRANSFER331(
devfund,
_underlying.MUL601(developerFee).DIV456(developerfeebase561)
);
DEPOSIT115();
}
}
// **** Emergency functions ****
function EXECUTE807(address _target, bytes memory _data) //inject NONSTANDARD NAMING
public
payable
returns (bytes memory response)
{
require(msg.sender == timelock, "!timelock");
require(_target != address(0), "!target");
// call contract in current context
assembly {
let succeeded := delegatecall(
sub(gas(), 5000),
_target,
add(_data, 0x20),
mload(_data),
0,
0
)
let size := returndatasize()
response := mload(0x40)
mstore(
0x40,
add(response, and(add(add(size, 0x20), 0x1f), not(0x1f)))
)
mstore(response, size)
returndatacopy(add(response, 0x20), 0, size)
switch iszero(succeeded)
case 1 {
// throw if delegatecall failed
revert(add(response, 0x20), size)
}
}
}
// **** Internal functions ****
function _SWAPUNISWAP503( //inject NONSTANDARD NAMING
address _from,
address _to,
uint256 _amount
) internal {
require(_to != address(0));
// Swap with uniswap
IERC20(_from).SAFEAPPROVE284(univ2Router2, 0);
IERC20(_from).SAFEAPPROVE284(univ2Router2, _amount);
address[] memory path;
if (_from == weth339 || _to == weth339) {
path = new address[](2);
path[0] = _from;
path[1] = _to;
} else {
path = new address[](3);
path[0] = _from;
path[1] = weth339;
path[2] = _to;
}
UniswapRouterV2(univ2Router2).SWAPEXACTTOKENSFORTOKENS167(
_amount,
0,
path,
address(this),
now.ADD388(60)
);
}
}
// Base contract for Curve based vault strategies
abstract contract VoxStrategyCurveBase is VoxStrategyBase {
// curve dao
address public curve;
address public gauge;
address public mintr = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0;
// stablecoins
address public dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
address public usdt = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
address public susd = 0x57Ab1ec28D129707052df4dF418D58a2D46d5f51;
// bitcoins
address public renbtc = 0xEB4C2781e4ebA804CE9a9803C67d0893436bB27D;
// rewards
address public crv = 0xD533a949740bb3306d119CC777fa900bA034cd52;
// keep
address public keep = 0x85Eee30c52B0b379b046Fb0F85F4f3Dc3009aFEC;
address public keep_rewards = 0x6828bcF74279eE32f2723eC536c22c51Eed383C6;
// How much CRV tokens to keep
uint256 public keepCRV = 0;
uint256 public keepCRVMax = 10000;
constructor(
address _curve,
address _gauge,
address _underlying,
address _governance,
address _strategist,
address _treasury,
address _devfund,
address _timelock,
address _vault
)
public
VoxStrategyBase(_underlying, _governance, _strategist, _treasury, _devfund, _timelock, _vault)
{
curve = _curve;
gauge = _gauge;
}
// **** Getters ****
function BALANCEOFPOOL881() public override view returns (uint256) { //inject NONSTANDARD NAMING
return ICurveGauge(gauge).BALANCEOF68(address(this));
}
function GETHARVESTABLE58() external returns (uint256) { //inject NONSTANDARD NAMING
return ICurveGauge(gauge).CLAIMABLE_TOKENS440(address(this));
}
function GETMOSTPREMIUM814() public virtual view returns (address, uint256); //inject NONSTANDARD NAMING
// **** Setters ****
function SETKEEPCRV171(uint256 _keepCRV) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
keepCRV = _keepCRV;
}
// **** State Mutation functions ****
function DEPOSIT115() public override { //inject NONSTANDARD NAMING
uint256 _underlying = IERC20(underlying).BALANCEOF68(address(this));
if (_underlying > 0) {
IERC20(underlying).SAFEAPPROVE284(gauge, 0);
IERC20(underlying).SAFEAPPROVE284(gauge, _underlying);
ICurveGauge(gauge).DEPOSIT115(_underlying);
}
}
function _WITHDRAWSOME235(uint256 _amount) //inject NONSTANDARD NAMING
internal
override
returns (uint256)
{
ICurveGauge(gauge).WITHDRAW593(_amount);
return _amount;
}
}
contract VoxStrategyCurveTBTC is VoxStrategyCurveBase {
// Curve stuff
address public tbtc_pool = 0xaa82ca713D94bBA7A89CEAB55314F9EfFEdDc78c;
address public tbtc_gauge = 0x6828bcF74279eE32f2723eC536c22c51Eed383C6;
address public tbtc_crv = 0x64eda51d3Ad40D56b9dFc5554E06F94e1Dd786Fd;
// EVENTS
event HARVESTED180(address indexed token, uint256 amount); //inject NONSTANDARD NAMING
constructor(
address _governance,
address _strategist,
address _treasury,
address _devfund,
address _timelock,
address _vault
)
public
VoxStrategyCurveBase(
tbtc_pool,
tbtc_gauge,
tbtc_crv,
_governance,
_strategist,
_treasury,
_devfund,
_timelock,
_vault
)
{}
// **** Views ****
function GETMOSTPREMIUM814() //inject NONSTANDARD NAMING
public
override
view
returns (address, uint256)
{
return (wbtc162, 2);
}
function GETNAME974() external override pure returns (string memory) { //inject NONSTANDARD NAMING
return "VoxStrategyCurveTBTC";
}
// **** State Mutations ****
function HARVEST372() public RESTRICTED912 override { //inject NONSTANDARD NAMING
// bitcoin we want to convert to
(address to, uint256 toIndex) = GETMOSTPREMIUM814();
// Collects crv tokens
// this also sends KEEP to keep_rewards contract
ICurveMintr(mintr).MINT951(gauge);
uint256 _crv = IERC20(crv).BALANCEOF68(address(this));
if (_crv > 0) {
// x% is sent back to the rewards holder
// to be used to lock up in as veCRV in a future date
uint256 _keepCRV = _crv.MUL601(keepCRV).DIV456(keepCRVMax);
if (_keepCRV > 0) {
IERC20(crv).SAFETRANSFER331(
treasury,
_keepCRV
);
}
_crv = _crv.SUB906(_keepCRV);
_SWAPUNISWAP503(crv, to, _crv);
}
// Collects keep tokens
IKeepRewardsClaimable(keep_rewards).CLAIM_REWARDS536();
uint256 _keep = IERC20(keep).BALANCEOF68(address(this));
if (_keep > 0) {
_SWAPUNISWAP503(keep, to, _keep);
}
// Adds liquidity to curve.fi's pool
// to get back underlying (tbtccrv)
uint256 _to = IERC20(to).BALANCEOF68(address(this));
if (_to > 0) {
IERC20(to).SAFEAPPROVE284(curve, 0);
IERC20(to).SAFEAPPROVE284(curve, _to);
uint256[4] memory liquidity;
liquidity[toIndex] = _to;
ICurveTBTC(curve).ADD_LIQUIDITY50(liquidity, 0);
}
// Distribute the collected funds and deposit underlying
// Emit harvested event
_DISTRIBUTEANDDEPOSIT388();
emit HARVESTED180(to, _to);
}
}
|
inject NONSTANDARD NAMING
|
uint256 public constant developerfeebase561 = 10000;
| 12,569,035 |
[
1,
22170,
18708,
882,
18264,
423,
2192,
1360,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
2254,
5034,
1071,
5381,
8751,
21386,
1969,
4313,
21,
273,
12619,
31,
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
] |
./partial_match/82/0x1D5d96645eA0c21176CaeeA893059b8ffb5e3705/sources/project_/contracts/EquipmentManager.sol
|
signifies no shield
|
uint8 shieldTrait = 4;
| 16,896,675 |
[
1,
2977,
5032,
1158,
699,
491,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
3639,
2254,
28,
699,
491,
15525,
273,
1059,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.2;
pragma experimental ABIEncoderV2;
import { SafeMath } from '@openzeppelin/contracts/math/SafeMath.sol';
import { IERC20 } from '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import { SafeERC20 } from '@openzeppelin/contracts/token/ERC20/SafeERC20.sol';
import { IAction } from '../interfaces/IAction.sol';
import { IController } from '../interfaces/IController.sol';
import { IOracle } from '../interfaces/IOracle.sol';
import { IOToken } from '../interfaces/IOToken.sol';
import { IWETH } from '../interfaces/IWETH.sol';
import { SwapTypes } from '../libraries/SwapTypes.sol';
import { AirswapBase } from '../utils/AirswapBase.sol';
import { RollOverBase } from '../utils/RollOverBase.sol';
/**
* Error Codes
* S1: msg.sender must be the vault
* S2: cannot currently close the vault position
* S3: seller for the order (_order.sender.wallet) must be this contract
* S4: token to sell (_order.sender.token) must be the currently activated oToken
* S5: token to sell for (_order.signer.token) must be the underlying
* S6: tokens being sold (_order.sender.amount) and tokens being minted (_otokenAmount) must be the same
* S7: amount of underlying being sold for (_order.signer.amount) does not meet the minimum option premium
* S8: strike price for the next oToken is too low
* S9: expiry timestamp for the next oToken is invalid
*/
/**
* @title ShortOTokenActionWithSwap
* @author Opyn Team
*/
contract ShortOTokenActionWithSwap is IAction, AirswapBase, RollOverBase {
using SafeERC20 for IERC20;
using SafeMath for uint256;
address public immutable vault;
/// @dev 100%
uint256 constant public BASE = 10000;
/// @dev the minimum strike price of the option chosen needs to be at least 105% of spot.
/// This is set expecting the contract to be a strategy selling calls. For puts should change this.
uint256 constant public MIN_STRIKE = 10500;
uint256 public MIN_PROFITS; // 100 being 1%
uint256 public lockedAsset;
uint256 public rolloverTime;
IController public controller;
IOracle public oracle;
IERC20 underlying;
event MintAndSellOToken(uint256 collateralAmount, uint256 otokenAmount, uint256 premium);
constructor(
address _vault,
address _swap,
address _opynWhitelist,
address _controller,
uint256 _vaultType,
address _underlying,
uint256 _min_profits
) {
MIN_PROFITS = _min_profits;
vault = _vault;
underlying = IERC20(_underlying);
controller = IController(_controller);
oracle = IOracle(controller.oracle());
// enable vault to take all the underlying back and re-distribute.
underlying.safeApprove(_vault, uint256(-1));
// enable pool contract to pull underlying from this contract to mint options.
underlying.safeApprove(controller.pool(), uint256(-1));
_initSwapContract(_swap);
_initRollOverBase(_opynWhitelist);
_openVault(_vaultType);
}
function onlyVault() private view {
require(msg.sender == vault, "S1");
}
/**
* @dev return the net worth of this strategy, in terms of underlying.
* if the action has an opened gamma vault, see if there's any short position
*/
function currentValue() external view override returns (uint256) {
return underlying.balanceOf(address(this)).add(lockedAsset);
// todo: caclulate cash value to avoid not early withdraw to avoid loss.
}
/**
* @dev return the amount of locked asset in the action.
*/
function currentLockedAsset() external view override returns (uint256) {
return lockedAsset;
}
/**
* @dev the function that the vault will call when the round is over
*/
function closePosition() external override {
onlyVault();
require(canClosePosition(), 'S2');
if(_canSettleVault()) {
_settleVault();
}
// this function can only be called when it's `Activated`
// go to the next step, which will enable owner to commit next oToken
_setActionIdle();
lockedAsset = 0;
}
/**
* @dev the function that the vault will call when the new round is starting
*/
function rolloverPosition() external override {
onlyVault();
// this function can only be called when it's `Committed`
_rollOverNextOTokenAndActivate();
rolloverTime = block.timestamp;
}
/**
* @dev owner only function to mint options with underlying and sell otokens in this contract
* by filling an order on AirSwap.
* this can only be done in "activated" state. which is achievable by calling `rolloverPosition`
*/
function mintAndSellOToken(uint256 _collateralAmount, uint256 _otokenAmount, SwapTypes.Order memory _order) external onlyOwner {
onlyActivated();
require(_order.sender.wallet == address(this), 'S3');
require(_order.sender.token == otoken, 'S4');
require(_order.signer.token == address(underlying), 'S5');
require(_order.sender.amount == _otokenAmount, 'S6');
// mint options & lock asset
_mintOTokens(_collateralAmount, _otokenAmount);
lockedAsset = lockedAsset.add(_collateralAmount);
// underlying before minting
uint256 underlyingBalanceBefore = underlying.balanceOf(address(this));
// sell options on airswap for underlying
IERC20(otoken).safeIncreaseAllowance(address(airswap), _order.sender.amount);
_fillAirswapOrder(_order);
// check that minimum premium is received & that it is higher than min threshold
uint256 underlyingBalanceAfter = underlying.balanceOf(address(this));
uint256 underlyingTokenEarned = underlyingBalanceAfter.sub(underlyingBalanceBefore);
require(_collateralAmount.mul(MIN_PROFITS).div(BASE) <= underlyingTokenEarned, 'S7');
emit MintAndSellOToken(_collateralAmount, _otokenAmount, underlyingTokenEarned);
}
/**
* @notice the function will return when someone can close a position. 1 day after rollover,
* if the option wasn't sold, anyone can close the position.
*/
function canClosePosition() public view returns(bool) {
if (otoken != address(0) && lockedAsset != 0) {
return _canSettleVault();
}
return block.timestamp > rolloverTime + 1 days;
}
/**
* @dev open vault with vaultId 1. this should only be performed once when contract is initiated
*/
function _openVault(uint256 _vaultType) internal {
bytes memory data;
if (_vaultType != 0) {
data = abi.encode(_vaultType);
}
// this action will always use vault id 0
IController.ActionArgs[] memory actions = new IController.ActionArgs[](1);
actions[0] = IController.ActionArgs(
IController.ActionType.OpenVault,
address(this), // owner
address(0), // doesn't matter
address(0), // doesn't matter
1, // vaultId
0, // amount
0, // index
data // data
);
controller.operate(actions);
}
/**
* @dev mint otoken in vault 1
*/
function _mintOTokens(uint256 _collateralAmount, uint256 _otokenAmount) internal {
// this action will always use vault id 1
IController.ActionArgs[] memory actions = new IController.ActionArgs[](2);
actions[0] = IController.ActionArgs(
IController.ActionType.DepositCollateral,
address(this), // vault owner is this address
address(this), // deposit from this address
address(underlying), // collateral is the underlying
1, // vaultId is 1
_collateralAmount, // amount of underlying to deposit
0, // index
"" // data
);
actions[1] = IController.ActionArgs(
IController.ActionType.MintShortOption,
address(this), // vault owner is this address
address(this), // mint to this address
otoken, // otoken to mint
1, // vaultId is 1
_otokenAmount, // amount of otokens to mint
0, // index
"" // data
);
controller.operate(actions);
}
/**
* @dev settle vault 1 and withdraw all locked collateral
*/
function _settleVault() internal {
IController.ActionArgs[] memory actions = new IController.ActionArgs[](1);
// this action will always use vault id 1
actions[0] = IController.ActionArgs(
IController.ActionType.SettleVault,
address(this), // owner is this address
address(this), // recipient is this address
address(0), // doesn't mtter
1, // vaultId is 1
0, // amount doesn't matter
0, // index
"" // data
);
controller.operate(actions);
}
/**
* @dev checks if the current vault can be settled
*/
function _canSettleVault() internal view returns (bool) {
if (lockedAsset != 0 && otoken != address(0)) {
return controller.isSettlementAllowed(otoken);
}
return false;
}
/**
* @dev funtion to add some custom logic to check the next otoken is valid to this strategy
* this hook is triggered while action owner calls "commitNextOption"
* so accessing otoken will give u the current otoken.
*/
function _customOTokenCheck(address _nextOToken) internal override view {
// Can override or replace this.
require(_isValidStrike(IOToken(_nextOToken).strikePrice()), 'S8');
require (_isValidExpiry(IOToken(_nextOToken).expiryTimestamp()), 'S9');
/**
* e.g.
* check otoken strike price is lower than current spot price for put.
* check it's no more than x day til the current otoken expires. (can't commit too early)
* check there's no previously committed otoken.
* check otoken expiry is expected
*/
}
/**
* @dev funtion to check that the otoken being sold meets a minimum valid strike price
* this hook is triggered in the _customOtokenCheck function.
*/
function _isValidStrike(uint256 strikePrice) internal view returns (bool) {
uint256 spotPrice = oracle.getPrice(address(underlying));
// checks that the strike price set is > than 105% of current price
return strikePrice >= spotPrice.mul(MIN_STRIKE).div(BASE);
}
/**
* @dev funtion to check that the otoken being sold meets certain expiry conditions
* this hook is triggered in the _customOtokenCheck function.
*/
function _isValidExpiry(uint256 expiry) internal view returns (bool) {
// TODO: override with your filler code.
// Checks that the token committed to expires within 15 days of commitment.
return (block.timestamp).add(15 days) >= expiry;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.2;
interface IAction {
/**
* The function used to determin how much asset the current action is controlling.
* this will impact the withdraw and deposit amount calculated from the vault.
*/
function currentValue() external view returns (uint256);
/**
* The function for the vault to call at the end of each vault's round.
* after calling this function, the vault will try to pull assets back from the action and enable withdraw.
*/
function closePosition() external;
/**
* The function for the vault to call when the vault is ready to start the next round.
* the vault will push assets to action before calling this function, but the amount can change compare to
* the last round. So each action should check their asset balance instead of using any cached balance.
*
* Each action can also add additional checks and revert the `rolloverPosition` call if the action
* is not ready to go into the next round.
*/
function rolloverPosition() external;
/**
* The function used to determine how much asset is locked in the current action.
* this will impact the closeposition amount calculated from the vault.
*/
function currentLockedAsset() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.2;
pragma experimental ABIEncoderV2;
interface IController {
enum ActionType {
OpenVault,
MintShortOption,
BurnShortOption,
DepositLongOption,
WithdrawLongOption,
DepositCollateral,
WithdrawCollateral,
SettleVault,
Redeem,
Call
}
struct ActionArgs {
ActionType actionType;
address owner;
address secondAddress;
address asset;
uint256 vaultId;
uint256 amount;
uint256 index;
bytes data;
}
struct Vault {
address[] shortOtokens;
address[] longOtokens;
address[] collateralAssets;
uint256[] shortAmounts;
uint256[] longAmounts;
uint256[] collateralAmounts;
}
function pool() external view returns (address);
function getPayout(address _otoken, uint256 _amount) external view returns (uint256);
function operate(ActionArgs[] calldata _actions) external;
function getAccountVaultCounter(address owner) external view returns (uint256);
function oracle() external view returns (address);
function getVault(address _owner, uint256 _vaultId) external view returns (Vault memory);
function getProceed(address _owner, uint256 _vaultId) external view returns (uint256);
function isSettlementAllowed(
address otoken
) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.2;
interface IOracle {
function isDisputePeriodOver(address _asset, uint256 _expiryTimestamp) external view returns (bool);
function getExpiryPrice(address _asset, uint256 _expiryTimestamp) external view returns (uint256, bool);
function setAssetPricer(address _asset, address _pricer) external;
function setExpiryPrice(
address _asset,
uint256 _expiryTimestamp,
uint256 _price
) external;
function getPrice(address _asset) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.2;
interface IOToken {
function underlyingAsset() external view returns (address);
function strikeAsset() external view returns (address);
function collateralAsset() external view returns (address);
function strikePrice() external view returns (uint256);
function expiryTimestamp() external view returns (uint256);
function isPut() external view returns (bool);
function balanceOf(address account) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.2;
interface IWETH {
function deposit() external payable;
function withdraw(uint256) external;
function balanceOf(address account) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transfer(address recipient, uint256 amount) external returns (bool);
}
// SPDX-License-Identifier: Apache
/*
Copyright 2020 Swap Holdings 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.7.2;
pragma experimental ABIEncoderV2;
/**
* @title Types: Library of Swap Protocol Types and Hashes
*/
library SwapTypes {
struct Order {
uint256 nonce; // Unique per order and should be sequential
uint256 expiry; // Expiry in seconds since 1 January 1970
Party signer; // Party to the trade that sets terms
Party sender; // Party to the trade that accepts terms
Party affiliate; // Party compensated for facilitating (optional)
Signature signature; // Signature of the order
}
struct Party {
bytes4 kind; // Interface ID of the token
address wallet; // Wallet address of the party
address token; // Contract address of the token
uint256 amount; // Amount for ERC-20 or ERC-1155
uint256 id; // ID for ERC-721 or ERC-1155
}
struct Signature {
address signatory; // Address of the wallet used to sign
address validator; // Address of the intended swap contract
bytes1 version; // EIP-191 signature version
uint8 v; // `v` value of an ECDSA signature
bytes32 r; // `r` value of an ECDSA signature
bytes32 s; // `s` value of an ECDSA signature
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.2;
pragma experimental ABIEncoderV2;
import { ISwap } from "../interfaces/ISwap.sol";
import { SwapTypes } from "../libraries/SwapTypes.sol";
/**
* Error Codes
* A1: invalid airswap address, must not be a 0x address
*/
/**
* @title AirswapBase
*/
contract AirswapBase {
ISwap public airswap;
function _initSwapContract(address _airswap) internal {
require(_airswap != address(0), "A1");
airswap = ISwap(_airswap);
}
function _fillAirswapOrder(SwapTypes.Order memory _order) internal {
airswap.swap(_order);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.2;
pragma experimental ABIEncoderV2;
import '@openzeppelin/contracts/access/Ownable.sol';
import { IERC20 } from '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import { SafeERC20 } from '@openzeppelin/contracts/token/ERC20/SafeERC20.sol';
import { AirswapBase } from './AirswapBase.sol';
import { IWhitelist } from '../interfaces/IWhitelist.sol';
import { SwapTypes } from '../libraries/SwapTypes.sol';
/**
* Error Codes
* R1: next oToken has not been committed to yet
* R2: vault is not activated, cannot mint and sell oTokens or close an open position
* R3: vault is currently activated, cannot commit next oToken or recommit an oToken
* R4: cannot rollover next oToken and activate vault, commit phase period not over (MIN_COMMIT_PERIOD)
* R5: token is not a whitelisted oToken
*/
/**
* @title RolloverBase
* @author Opyn Team
*/
contract RollOverBase is Ownable {
address public otoken;
address public nextOToken;
uint256 constant public MIN_COMMIT_PERIOD = 0 hours; // was 4 but after request reduced it to 0
uint256 public commitStateStart;
/**
* Idle: action will go "idle" after the vault closes this position & before the next oToken is committed.
*
* Committed: owner has already set the next oToken this vault is trading. During this phase, all funds are
* already back in the vault and waiting for redistribution. Users who don't agree with the setting of the next
* round can withdraw.
*
* Activated: after vault calls "rollover", the owner can start minting / buying / selling according to each action.
*/
enum ActionState {
Activated,
Committed,
Idle
}
ActionState public state;
IWhitelist public opynWhitelist;
function onlyCommitted() private view {
require(state == ActionState.Committed, "R1");
}
function onlyActivated() internal view {
require(state == ActionState.Activated, "R2");
}
function _initRollOverBase(address _opynWhitelist) internal {
state = ActionState.Idle;
opynWhitelist = IWhitelist(_opynWhitelist);
}
/**
* owner can commit the next otoken, if it's in idle state.
* or re-commit it if needed during the commit phase.
*/
function commitOToken(address _nextOToken) external onlyOwner {
require(state != ActionState.Activated, "R3");
_checkOToken(_nextOToken);
nextOToken = _nextOToken;
state = ActionState.Committed;
commitStateStart = block.timestamp;
}
function _setActionIdle() internal {
onlyActivated();
// wait for the owner to set the next option
state = ActionState.Idle;
}
function _rollOverNextOTokenAndActivate() internal {
onlyCommitted();
require(block.timestamp - commitStateStart > MIN_COMMIT_PERIOD, "R4");
otoken = nextOToken;
nextOToken = address(0);
state = ActionState.Activated;
}
function _checkOToken(address _nextOToken) private view {
require(opynWhitelist.isWhitelistedOtoken(_nextOToken), 'R5');
_customOTokenCheck(_nextOToken);
}
/**
* @dev funtion to add some custom logic to check the next otoken is valid to this strategy
* this hook is triggered while action owner calls "commitNextOption"
* so accessing otoken will give u the current otoken.
*/
function _customOTokenCheck(address _nextOToken) internal virtual view {
}
}
// 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: Apache
/*
Copyright 2020 Swap Holdings 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.7.2;
pragma experimental ABIEncoderV2;
import {SwapTypes} from "../libraries/SwapTypes.sol";
interface ISwap {
/**
* @notice Atomic Token Swap
* @param order Types.Order
*/
function swap(SwapTypes.Order calldata order) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.2;
interface IWhitelist {
function isWhitelistedOtoken(address _otoken) external view returns (bool);
function whitelistCollateral(address _collateral) external;
function whitelistProduct(
address _underlying,
address _strike,
address _collateral,
bool _isPut
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
|
SPDX-License-Identifier: MIT
|
interface IOToken {
function underlyingAsset() external view returns (address);
function strikeAsset() external view returns (address);
function collateralAsset() external view returns (address);
function strikePrice() external view returns (uint256);
function expiryTimestamp() external view returns (uint256);
function isPut() external view returns (bool);
function balanceOf(address account) external view returns (uint256);
}
| 29,667 |
[
1,
3118,
28826,
17,
13211,
17,
3004,
30,
490,
1285,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5831,
1665,
1345,
288,
203,
565,
445,
6808,
6672,
1435,
3903,
1476,
1135,
261,
2867,
1769,
203,
203,
565,
445,
609,
2547,
6672,
1435,
3903,
1476,
1135,
261,
2867,
1769,
203,
203,
565,
445,
4508,
2045,
287,
6672,
1435,
3903,
1476,
1135,
261,
2867,
1769,
203,
203,
565,
445,
609,
2547,
5147,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
10839,
4921,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
353,
6426,
1435,
3903,
1476,
1135,
261,
6430,
1769,
203,
377,
203,
565,
445,
11013,
951,
12,
2867,
2236,
13,
3903,
1476,
1135,
261,
11890,
5034,
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
] |
./partial_match/1/0x2BAECb968D952b7c734974a0Fbe39b5a74f18f87/sources/DharmaTradeReserveV17ImplementationStaging.sol
|
* @notice Internal view function to check whether the given role is paused or not. @param role The role to check for. @return A boolean indicating if the specified role is paused or not./
|
function _isPaused(Role role) internal view returns (bool paused) {
paused = _roles[uint256(role)].paused;
}
| 3,655,756 |
[
1,
3061,
1476,
445,
358,
866,
2856,
326,
864,
2478,
353,
17781,
578,
486,
18,
225,
2478,
1021,
2478,
358,
866,
364,
18,
327,
432,
1250,
11193,
309,
326,
1269,
2478,
353,
17781,
578,
486,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
225,
445,
389,
291,
28590,
12,
2996,
2478,
13,
2713,
1476,
1135,
261,
6430,
17781,
13,
288,
203,
565,
17781,
273,
389,
7774,
63,
11890,
5034,
12,
4615,
13,
8009,
8774,
3668,
31,
203,
225,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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 "../../../../transfer-layer/transfer-module/interfaces/ITransferModule.sol";
import "../../../components-registry/instances/TransferModuleInstance.sol";
import "../_common/MultiChainToken.sol";
import "../_common/SecuritiesToken.sol";
import "../_services/Pausable.sol";
import "../_services/escrow/Escrow.sol";
import "../ERC-20/StandardToken.sol";
import "../../../../common/libraries/SafeMath.sol";
/**
* @title Securities Standart Token
*/
contract SecuritiesStandardToken is MultiChainToken, SecuritiesToken, StandardToken, Pausable, Escrow, TransferModuleInstance {
// define libraries
using SafeMath for uint256;
// Rollback status (Enabled/Disabled)
bool public rollbackEnabled = false;
/**
* @notice Write info to the log about rollbacks status changes
*/
event RollbacksStatusChanged(bool newStatus);
/**
* @notice Write details about clawback to the log
* @param from Address from which tokens will be removed
* @param to Recipient address
* @param tokens Tokens to transfer
* @param data Any additional info about transfer
*/
event Clawback(address indexed from, address indexed to, uint tokens, bytes32 data);
/**
* @notice Verify transfer
* @param from Address from which tokens will be removed
* @param to Recipient address
* @param sender Address of the transaction initiator
* @param tokens Tokens to transfer
*/
modifier allowedTx(
address from,
address to,
address sender,
uint tokens
) {
bool allowed = tmInstance().verifyTransfer(
from,
to,
sender,
tokens
);
require(allowed, "Transfer was declined.");
_;
}
/**
* @notice Verify balance with tokens on the escrow
* @param tokenHolder Address of the token holder to be verified
* @param tokens Number of the tokens
*/
modifier verifyBalance(address tokenHolder, uint tokens) {
require(balances[tokenHolder] >= tokensOnEscrow[tokenHolder].add(tokens), "Insufficient funds.");
_;
}
/**
* @notice Transfer tokens from chain
* @param value Tokens to be transfered
* @param chain Target chain name
* @param recipient Target address
*/
function crossChainTransfer(uint value, bytes32 chain, bytes32 recipient)
external
notPaused()
verifyBalance(msg.sender, value)
allowedTx(
msg.sender,
msg.sender,
msg.sender,
value
)
{
require(value > 0, "Invalid value.");
balances[msg.sender] = balances[msg.sender].sub(value);
totalSupply_ = totalSupply_.sub(value);
emit Transfer(msg.sender, address(0), value);
emit FromChain(chain, value, msg.sender, recipient);
tmInstance().sendTokensFromChain(
msg.sender,
chain,
recipient,
value
);
}
/**
* @notice Allows create rollback transaction for ERC-20 tokens
* @notice tokens will be send back to the old owner, will be emited "RollbackTransaction" event
* @param from Address from which we rollback tokens
* @param to Tokens owner
* @param sender Original transaction sender
* @param tokens Quantity of the tokens that will be rollbacked
* @param checkpointId Transaction checkpoint identifier
* @param originalTxHash Hash of the original transaction which maked a tokens transfer
*/
function createRollbackTransaction(
address from,
address to,
address sender,
uint tokens,
uint checkpointId,
string memory originalTxHash
)
public
verifyPermissionForCurrentToken(msg.sig)
txRollback(
from,
to,
tokens,
sender,
checkpointId,
originalTxHash
)
returns (bool)
{
updatedBalances(from, to, tokens);
return true;
}
/**
* @notice Redefinition of the ERC-20 standard transfer function.
* @notice Generate addiotional info for rollback
* @param to The address which you want to transfer to
* @param value the amount of tokens to be transferred
*/
function transfer(address to, uint256 value)
public
notPaused()
verifyBalance(msg.sender, value)
allowedTx(
msg.sender,
to,
msg.sender,
value
)
returns (bool)
{
bool result = super.transfer(to, value);
if (rollbackEnabled && result) {
createCheckpoint(msg.sender, to, value, msg.sender);
}
return result;
}
/**
* @notice Redefinition of the ERC-20 standard transferFrom function.
* @notice Generate addiotional info for rollback
* @param to The address which you want to transfer to
* @param value the amount of tokens to be transferred
* @param from The address from which will be transferred token
*/
function transferFrom(address from, address to, uint256 value)
public
notPaused()
verifyBalance(from, value)
allowedTx(
from,
to,
msg.sender,
value
)
returns (bool)
{
bool result = super.transferFrom(from, to, value);
if (rollbackEnabled && result) {
createCheckpoint(from, to, value, msg.sender);
}
return result;
}
/**
* @notice Batch tokens transfer
* @param investors Array of the investors
* @param values Array of the numbers of the tokens for distribution
*/
function batchTransfer(address[] calldata investors, uint[] calldata values) external {
for (uint i = 0; i < investors.length; i++) {
transfer(investors[i], values[i]);
}
}
/**
* @notice Receive tokens from other chaine
* @param value Tokens to receive
* @param chain From chain
* @param recipient Tokens recipient
* @param sender Sender address
*/
function acceptFromOtherChain(uint value, bytes32 chain, address recipient, bytes32 sender) public {
address transferModule = getTransferModuleAddress();
require(msg.sender == transferModule, "Only transfer module.");
balances[recipient] = balances[recipient].add(value);
totalSupply_ = totalSupply_.add(value);
emit Transfer(address(0), recipient, value);
emit ToChain(chain, value, recipient, sender);
}
/**
* @notice Clawback method which provides an allowance for the issuer
* @notice to move tokens between any accounts
* @param from Address from which tokens will be removed
* @param to Recipient address
* @param tokens Tokens to transfer
* @param data Any additional info about transfer
*/
function clawback(
address from,
address to,
uint tokens,
bytes32 data
)
external
verifyPermissionForCurrentToken(msg.sig)
allowedTx(
to,
to,
to,
tokens
)
{
require(to != address(0), "Invalid recipient address.");
updatedBalances(from, to, tokens);
emit Clawback(from, to, tokens, data);
}
/**
* @notice Process escrow. Provides possibility for move locked token.
* @notice Provide ability to transfer tokens to another token holder.
* @param externalId Escrow identifier
* @param recipient Tokens recipient
* @param callData Additional data for call
* @param data Additional data for log
* @dev If provided escrowAgent must execute external call "CATEscrowProcessed"
*/
function processEscrow(
bytes32 externalId,
address recipient,
bytes memory callData,
bytes memory data
)
public
{
require(externalId != bytes32(0x00));
require(recipient != address(0));
_processEscrow(
externalId,
recipient,
callData,
data
);
uint escrowId = idsExtIntRelations[externalId];
updatedBalances(
escrowList[escrowId].tokenHolder,
recipient,
escrowList[escrowId].value
);
}
/**
* @notice Create new escrow
* @param tokenHolder Token holder address
* @param escrowAgent Address (application) on which will be executed call "escrow created"
* @param value Number of the tokens to lock
* @param dataForCall Additional data for call
* @param data Additional data for log
* @param externalId Transaction initiator can specify external identifier
* @param canCancel Specifies the type of the lock
* @param executeCall If equal "true" CAT-20 token send request to the escrow agent
* @return escrowId Escrow identifier
*/
function createEscrow(
address tokenHolder,
address escrowAgent,
uint value,
bytes memory dataForCall,
bytes memory data,
bytes32 externalId,
bool canCancel,
bool executeCall
)
public
verifyBalance(tokenHolder, value)
returns (uint)
{
// Verify application
if (escrowAgent != address(0)) {
require(arInstance().isRegisteredApp(escrowAgent, address(this)), "Escrow agent in not registred in the application registry.");
}
return _createEscrow(
tokenHolder,
escrowAgent,
value,
dataForCall,
data,
externalId,
canCancel,
executeCall
);
}
/**
* @notice Enable/Disable rollbacks in the token
*/
function toggleRollbacksStatus()
external
verifyPermissionForCurrentToken(msg.sig)
{
rollbackEnabled = !rollbackEnabled;
emit RollbacksStatusChanged(rollbackEnabled);
}
/**
* @notice Update token holders balances with balance verification
* @param from Address from which we rollback tokens
* @param to Tokens owner
* @param tokens Quantity of the tokens that will be rollbacked
*/
function updatedBalances(address from, address to, uint tokens)
internal
verifyBalance(from, tokens)
{
_updatedBalances(from, to, tokens);
}
/**
* @notice Update token holders balances
* @param from Address from which we rollback tokens
* @param to Tokens owner
* @param tokens Quantity of the tokens that will be rollbacked
*/
function _updatedBalances(address from, address to, uint tokens) internal {
balances[from] = balances[from].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
}
}
|
* @notice Update token holders balances @param from Address from which we rollback tokens @param to Tokens owner @param tokens Quantity of the tokens that will be rollbacked/
|
function _updatedBalances(address from, address to, uint tokens) internal {
balances[from] = balances[from].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
}
| 14,022,482 |
[
1,
1891,
1147,
366,
4665,
324,
26488,
225,
628,
5267,
628,
1492,
732,
8006,
2430,
225,
358,
13899,
3410,
225,
2430,
18189,
434,
326,
2430,
716,
903,
506,
8006,
329,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
389,
7007,
38,
26488,
12,
2867,
628,
16,
1758,
358,
16,
2254,
2430,
13,
2713,
288,
203,
3639,
324,
26488,
63,
2080,
65,
273,
324,
26488,
63,
2080,
8009,
1717,
12,
7860,
1769,
203,
3639,
324,
26488,
63,
869,
65,
273,
324,
26488,
63,
869,
8009,
1289,
12,
7860,
1769,
203,
203,
3639,
3626,
12279,
12,
2080,
16,
358,
16,
2430,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0x585DBDfa76f4479BCF605fe5C87f6143784Ae6Cf/sources/NFTStaking.sol
|
Make Sure that the user at least has one token staked before withdraw Find the index of the token
|
function withdraw(uint256 _tokenId) external nonReentrant {
require(
stakers[msg.sender].amountStaked > 0,
"Must have token for withdraw"
);
require(
stakerAddress[_tokenId] == msg.sender,
"You didn't own this token"
);
uint256 index = 0;
for (uint256 i = 0; i < stakers[msg.sender].stakedToken.length; i++) {
if (stakers[msg.sender].stakedToken[i].tokenId == _tokenId) {
index = i;
break;
}
}
stakers[msg.sender].stakedToken[index].staker = address(0);
stakers[msg.sender].amountStaked--;
stakerAddress[_tokenId] = address(0);
nftCollection.transferFrom(address(this), msg.sender, _tokenId);
stakers[msg.sender].timeOfLastUpdate = block.timestamp;
}
| 7,062,361 |
[
1,
6464,
348,
594,
716,
326,
729,
622,
4520,
711,
1245,
1147,
384,
9477,
1865,
598,
9446,
4163,
326,
770,
434,
326,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
598,
9446,
12,
11890,
5034,
389,
2316,
548,
13,
3903,
1661,
426,
8230,
970,
288,
203,
203,
3639,
2583,
12,
203,
5411,
384,
581,
414,
63,
3576,
18,
15330,
8009,
8949,
510,
9477,
405,
374,
16,
203,
5411,
315,
10136,
1240,
1147,
364,
598,
9446,
6,
203,
3639,
11272,
203,
203,
3639,
2583,
12,
203,
5411,
384,
6388,
1887,
63,
67,
2316,
548,
65,
422,
1234,
18,
15330,
16,
203,
5411,
315,
6225,
10242,
1404,
4953,
333,
1147,
6,
203,
3639,
11272,
203,
203,
3639,
2254,
5034,
770,
273,
374,
31,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
384,
581,
414,
63,
3576,
18,
15330,
8009,
334,
9477,
1345,
18,
2469,
31,
277,
27245,
288,
203,
5411,
309,
261,
334,
581,
414,
63,
3576,
18,
15330,
8009,
334,
9477,
1345,
63,
77,
8009,
2316,
548,
422,
389,
2316,
548,
13,
288,
203,
7734,
770,
273,
277,
31,
203,
7734,
898,
31,
203,
5411,
289,
203,
3639,
289,
203,
203,
3639,
384,
581,
414,
63,
3576,
18,
15330,
8009,
334,
9477,
1345,
63,
1615,
8009,
334,
6388,
273,
1758,
12,
20,
1769,
203,
203,
3639,
384,
581,
414,
63,
3576,
18,
15330,
8009,
8949,
510,
9477,
413,
31,
203,
203,
3639,
384,
6388,
1887,
63,
67,
2316,
548,
65,
273,
1758,
12,
20,
1769,
203,
203,
3639,
290,
1222,
2532,
18,
13866,
1265,
12,
2867,
12,
2211,
3631,
1234,
18,
15330,
16,
389,
2316,
548,
1769,
203,
203,
3639,
384,
581,
414,
63,
3576,
18,
15330,
8009,
957,
2
] |
pragma solidity ^0.5.6;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath{
function mul(uint a, uint b) internal pure returns (uint){
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint a, uint b) internal pure returns (uint){
uint c = a / b;
return c;
}
function sub(uint a, uint b) internal pure returns (uint){
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal pure returns (uint){
uint c = a + b; assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public{
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner(){
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public{
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title ITCMoney token
* @dev ERC20 Token implementation, with mintable and its own specific
*/
contract ITCMoney is Ownable{
using SafeMath for uint;
string public constant name = "ITC Money";
string public constant symbol = "ITCM";
uint32 public constant decimals = 18;
address payable public companyAddr = address(0);
address public constant bonusAddr = 0xaEA6949B27C44562Dd446c2C44f403cF6D13a2fD;
address public constant teamAddr = 0xe0b70c54a1baa2847e210d019Bb8edc291AEA5c7;
address public constant sellerAddr = 0x95E1f32981F909ce39d45bF52C9108f47e0FCc50;
uint public totalSupply = 0;
uint public maxSupply = 17000000000 * 1 ether; // Maximum of tokens to be minted. 1 ether multiplier is decimal.
mapping(address => uint) balances;
mapping (address => mapping (address => uint)) internal allowed;
bool public transferAllowed = false;
mapping(address => bool) internal customTransferAllowed;
uint public tokenRate = 170 * 1 finney; // Start token rate * 10000 (0.017 CHF * 10000). 1 finney multiplier is for decimal.
uint private tokenRateDays = 0;
// growRate is the sequence of periods and percents of rate grow. First element is timestamp of period start. Second is grow percent * 10000.
uint[2][] private growRate = [
[1538784000, 100],
[1554422400, 19],
[1564617600, 17],
[1572566400, 0]
];
uint public rateETHCHF = 0;
mapping(address => uint) balancesCHF;
bool public amountBonusAllowed = true;
// amountBonus describes the token bonus that depends from CHF amount. First element is minimum accumulated CHF amount. Second one is bonus percent * 100.
uint[2][] private amountBonus = [
[uint32(2000), 500],
[uint32(8000), 700],
[uint32(17000), 1000],
[uint32(50000), 1500],
[uint32(100000), 1750],
[uint32(150000), 2000],
[uint32(500000), 2500]
];
// timeBonus describes the token bonus that depends from date. First element is the timestamp of start date. Second one is bonus percent * 100.
uint[2][] private timeBonus = [
[1535673600, 2000], // 2018-08-31
[1535760000, 1800], // 2018-09-01
[1538784000, 1500], // 2018-10-06
[1541462400, 1000], // 2018-11-06
[1544054400, 800], // 2018-12-06
[1546732800, 600], // 2019-01-06
[1549411200, 300], // 2019-02-06
[1551830400, 200] // 2019-03-06
];
uint private finalTimeBonusDate = 1554508800; // 2019-04-06. No bonus tokens after this date.
uint public constantBonus = 0;
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
event CompanyChanged(address indexed previousOwner, address indexed newOwner);
event TransfersAllowed();
event TransfersAllowedTo(address indexed to);
event CHFBonusStopped();
event AddedCHF(address indexed to, uint value);
event NewRateCHF(uint value);
event AddedGrowPeriod(uint startTime, uint rate);
event ConstantBonus(uint value);
event NewTokenRate(uint tokenRate);
/**
* @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 (uint){
return balances[_owner];
}
/**
* @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, uint _value) public returns (bool){
require(_to != address(0));
require(transferAllowed || _to == sellerAddr || customTransferAllowed[msg.sender]);
require(_value > 0 && _value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev 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, uint _value) public returns (bool){
require(_to != address(0));
require(transferAllowed || _to == sellerAddr || customTransferAllowed[_from]);
require(_value > 0 && _value <= balances[_from] && _value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint _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 (uint){
return allowed[_owner][_spender];
}
/**
* @dev Increase approved amount of tokents that could be spent on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to be spent.
*/
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 approved amount of tokents that could be spent on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to be spent.
*/
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;
}
/**
* @dev Function changes the company address. Ether moves to company address from contract.
* @param newCompany New company address.
*/
function changeCompany(address payable newCompany) onlyOwner public{
require(newCompany != address(0));
emit CompanyChanged(companyAddr, newCompany);
companyAddr = newCompany;
}
/**
* @dev Allow ITCM token transfer for each address.
*/
function allowTransfers() onlyOwner public{
transferAllowed = true;
emit TransfersAllowed();
}
/**
* @dev Allow ITCM token transfer for spcified address.
* @param _to Address to which token transfers become allowed.
*/
function allowCustomTransfers(address _to) onlyOwner public{
customTransferAllowed[_to] = true;
emit TransfersAllowedTo(_to);
}
/**
* @dev Stop adding token bonus that depends from accumulative CHF amount.
*/
function stopCHFBonus() onlyOwner public{
amountBonusAllowed = false;
emit CHFBonusStopped();
}
/**
* @dev Emit new tokens and transfer from 0 to client address. This function will generate tokens for bonus and team addresses.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function _mint(address _to, uint _value) private returns (bool){
// 3% of token amount to bonus address
uint bonusAmount = _value.mul(3).div(87);
// 10% of token amount to team address
uint teamAmount = _value.mul(10).div(87);
// Restore the total token amount
uint total = _value.add(bonusAmount).add(teamAmount);
require(total <= maxSupply);
maxSupply = maxSupply.sub(total);
totalSupply = totalSupply.add(total);
balances[_to] = balances[_to].add(_value);
balances[bonusAddr] = balances[bonusAddr].add(bonusAmount);
balances[teamAddr] = balances[teamAddr].add(teamAmount);
emit Transfer(address(0), _to, _value);
emit Transfer(address(0), bonusAddr, bonusAmount);
emit Transfer(address(0), teamAddr, teamAmount);
return true;
}
/**
* @dev This is wrapper for _mint.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function mint(address _to, uint _value) onlyOwner public returns (bool){
return _mint(_to, _value);
}
/**
* @dev Similar to mint function but take array of addresses and values.
* @param _to The addresses to transfer to.
* @param _value The amounts to be transferred.
*/
function mint(address[] memory _to, uint[] memory _value) onlyOwner public returns (bool){
require(_to.length == _value.length);
uint len = _to.length;
for(uint i = 0; i < len; i++){
if(!_mint(_to[i], _value[i])){
return false;
}
}
return true;
}
/**
* @dev Gets the accumulative CHF balance of the specified address.
* @param _owner The address to query the the CHF balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceCHFOf(address _owner) public view returns (uint){
return balancesCHF[_owner];
}
/**
* @dev Increase CHF amount for address to which the tokens were minted.
* @param _to Target address.
* @param _value The amount of CHF.
*/
function increaseCHF(address _to, uint _value) onlyOwner public{
balancesCHF[_to] = balancesCHF[_to].add(_value);
emit AddedCHF(_to, _value);
}
/**
* @dev Increase CHF amounts for addresses to which the tokens were minted.
* @param _to Target addresses.
* @param _value The amounts of CHF.
*/
function increaseCHF(address[] memory _to, uint[] memory _value) onlyOwner public{
require(_to.length == _value.length);
uint len = _to.length;
for(uint i = 0; i < len; i++){
balancesCHF[_to[i]] = balancesCHF[_to[i]].add(_value[i]);
emit AddedCHF(_to[i], _value[i]);
}
}
/**
* @dev Sets the rate ETH to CHF that represents UINT (rate * 10000).
* @param _rate ETH CHF rate * 10000.
*/
function setETHCHFRate(uint _rate) onlyOwner public{
rateETHCHF = _rate;
emit NewRateCHF(_rate);
}
/**
* @dev Set new period and grow percent at the day.
* @param _startTime timestamp when the rate will start grow.
* @param _rate Grow percent * 10000.
*/
function addNewGrowRate(uint _startTime, uint _rate) onlyOwner public{
growRate.push([_startTime, _rate]);
emit AddedGrowPeriod(_startTime, _rate);
}
/**
* @dev Set constant token bonus for each address that applies in fallback.
* @param _value Grow percent * 100.
*/
function setConstantBonus(uint _value) onlyOwner public{
constantBonus = _value;
emit ConstantBonus(_value);
}
/**
* @dev Calculate and store current token rate.
* The rate grows every day per percent that is shown in growRate starting from timestamp that was set for the rate.
*/
function getTokenRate() public returns (uint){
uint startTokenRate = tokenRate;
uint totalDays = 0;
uint len = growRate.length;
// For each period from growRate
for(uint i = 0; i < len; i++){
if(now > growRate[i][0] && growRate[i][1] > 0){
// The final date is minimum from now and next period date
uint end = now;
if(i + 1 < len && end > growRate[i + 1][0]){
end = growRate[i + 1][0];
}
uint dateDiff = (end - growRate[i][0]) / 1 days;
totalDays = totalDays + dateDiff;
// Check if the rate calculation required
if(dateDiff > 0 && totalDays > tokenRateDays){
// Calculate and store the rate.
// This is like rate * (100+percent)**days but memory safe.
for(uint ii = tokenRateDays; ii < totalDays; ii++){
tokenRate = tokenRate * (10000 + growRate[i][1]) / 10000;
}
tokenRateDays = totalDays;
}
}
}
if(startTokenRate != tokenRate){
emit NewTokenRate(tokenRate);
}
return tokenRate;
}
/**
* @dev Function that receives the ether, transfers it to company address and mints tokens to address that initiates payment. Company, bonus and team addresses gets the tokens as well.
*/
function () external payable { //inject DOS BY COMPLEX FALLBACK
// Revert if there are no basic parameters
require(msg.data.length == 0);
require(msg.value > 0);
require(rateETHCHF > 0);
// Calculate token amount (amount of CHF / current rate). Remember that token rate is multiplied by 1 finney, add the same multiplier for ether amount.
uint amount = (msg.value * rateETHCHF * 1 finney) / getTokenRate();
// Calculate CHF amount analogue, then store it for customer.
uint amountCHF = (msg.value * rateETHCHF) / 10000 / 1 ether;
uint totalCHF = balancesCHF[msg.sender].add(amountCHF);
emit AddedCHF(msg.sender, amountCHF);
// Get the bonus percent that depends from time or its constant.
uint len = 0;
uint i = 0;
uint percent = 0;
uint bonus = 0;
if(constantBonus > 0){
bonus = amount.mul(constantBonus).div(10000);
}else if(now < finalTimeBonusDate){
len = timeBonus.length;
percent = 0;
for(i = 0; i < len; i++){
if(now >= timeBonus[i][0]){
percent = timeBonus[i][1];
}else{
break;
}
}
if(percent > 0){
bonus = amount.mul(percent).div(10000);
}
}
// Add the bonus that depends from accumulated CHF amount
if(amountBonusAllowed){
len = amountBonus.length;
percent = 0;
for(i = 0; i < len; i++){
if(totalCHF >= amountBonus[i][0]){
percent = amountBonus[i][1];
}else{
break;
}
}
if(percent > 0){
bonus = bonus.add(amount.mul(percent).div(10000));
}
}
amount = amount.add(bonus);
// 3% of token amount to bonus address
uint bonusAmount = amount.mul(3).div(87);
// 10% of token amount to team address
uint teamAmount = amount.mul(10).div(87);
// Restore the total token amount
uint total = amount.add(bonusAmount).add(teamAmount);
require(total <= maxSupply);
maxSupply = maxSupply.sub(total);
totalSupply = totalSupply.add(total);
balances[msg.sender] = balances[msg.sender].add(amount);
balancesCHF[msg.sender] = totalCHF;
balances[bonusAddr] = balances[bonusAddr].add(bonusAmount);
balances[teamAddr] = balances[teamAddr].add(teamAmount);
companyAddr.call.gas(2301).value(msg.value)("");
emit Transfer(address(0), msg.sender, amount);
emit Transfer(address(0), bonusAddr, bonusAmount);
emit Transfer(address(0), teamAddr, teamAmount);
}
}
|
* @dev Emit new tokens and transfer from 0 to client address. This function will generate tokens for bonus and team addresses. @param _to The address to transfer to. @param _value The amount to be transferred./ 3% of token amount to bonus address 10% of token amount to team address Restore the total token amount
|
function _mint(address _to, uint _value) private returns (bool){
uint bonusAmount = _value.mul(3).div(87);
uint teamAmount = _value.mul(10).div(87);
uint total = _value.add(bonusAmount).add(teamAmount);
require(total <= maxSupply);
maxSupply = maxSupply.sub(total);
totalSupply = totalSupply.add(total);
balances[_to] = balances[_to].add(_value);
balances[bonusAddr] = balances[bonusAddr].add(bonusAmount);
balances[teamAddr] = balances[teamAddr].add(teamAmount);
emit Transfer(address(0), _to, _value);
emit Transfer(address(0), bonusAddr, bonusAmount);
emit Transfer(address(0), teamAddr, teamAmount);
return true;
}
| 12,538,369 |
[
1,
17982,
394,
2430,
471,
7412,
628,
374,
358,
1004,
1758,
18,
1220,
445,
903,
2103,
2430,
364,
324,
22889,
471,
5927,
6138,
18,
225,
389,
869,
1021,
1758,
358,
7412,
358,
18,
225,
389,
1132,
1021,
3844,
358,
506,
906,
4193,
18,
19,
890,
9,
434,
1147,
3844,
358,
324,
22889,
1758,
1728,
9,
434,
1147,
3844,
358,
5927,
1758,
11197,
326,
2078,
1147,
3844,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
389,
81,
474,
12,
2867,
389,
869,
16,
2254,
389,
1132,
13,
3238,
1135,
261,
6430,
15329,
203,
3639,
2254,
324,
22889,
6275,
273,
389,
1132,
18,
16411,
12,
23,
2934,
2892,
12,
11035,
1769,
203,
3639,
2254,
5927,
6275,
273,
389,
1132,
18,
16411,
12,
2163,
2934,
2892,
12,
11035,
1769,
203,
3639,
2254,
2078,
273,
389,
1132,
18,
1289,
12,
18688,
407,
6275,
2934,
1289,
12,
10035,
6275,
1769,
203,
540,
203,
3639,
2583,
12,
4963,
1648,
943,
3088,
1283,
1769,
203,
540,
203,
3639,
943,
3088,
1283,
273,
943,
3088,
1283,
18,
1717,
12,
4963,
1769,
203,
3639,
2078,
3088,
1283,
273,
2078,
3088,
1283,
18,
1289,
12,
4963,
1769,
203,
540,
203,
3639,
324,
26488,
63,
67,
869,
65,
273,
324,
26488,
63,
67,
869,
8009,
1289,
24899,
1132,
1769,
203,
3639,
324,
26488,
63,
18688,
407,
3178,
65,
273,
324,
26488,
63,
18688,
407,
3178,
8009,
1289,
12,
18688,
407,
6275,
1769,
203,
3639,
324,
26488,
63,
10035,
3178,
65,
273,
324,
26488,
63,
10035,
3178,
8009,
1289,
12,
10035,
6275,
1769,
203,
203,
3639,
3626,
12279,
12,
2867,
12,
20,
3631,
389,
869,
16,
389,
1132,
1769,
203,
3639,
3626,
12279,
12,
2867,
12,
20,
3631,
324,
22889,
3178,
16,
324,
22889,
6275,
1769,
203,
3639,
3626,
12279,
12,
2867,
12,
20,
3631,
5927,
3178,
16,
5927,
6275,
1769,
203,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.8.0;
pragma experimental ABIEncoderV2;
contract Manufacturing {
mapping (string => uint256) public materials;
struct Product {
string Name;
uint256 Quantity;
}
struct Door{
uint256 steel_panel;
uint256 rails;
uint256 sensor;
}
struct Frame{
uint256 steel_sheet; //10
uint256 pulley; //2
uint256 motor; //2
uint256 steelcable; //2
}
struct Button{
uint256 ledlight;
uint256 button;
}
struct Display{
uint256 screen;
}
struct Battery{
uint256 controller;
}
Product productStruct;
Product[] productList;
constructor() public {
//doors
materials["steel_panel"] = 36; //2 per doors
materials["rails"] = 36; //2 per doors
materials["sensor"] = 18; //1 per doors
//frames
materials["steel_sheet"] = 40; //10 per frame
materials["pulley"] = 16; //2 per frame
materials["motor"] = 16; //2 per frame
materials["steelcable"] = 16; //2 per frame
//buttons
materials["ledlight"] = 50; //1 per button
materials["button"] = 50; //1 per button
//display
materials["screen"] = 16; //1 per display
//battery
materials["controller"] = 1; //1 per battery
}
//create doors
function doors() public returns (uint256 numDoors) {
require(materials["steel_panel"] >= 2 && materials["rails"] >= 2 && materials["sensor"] >= 2);
// if (materials["steel_panel"] == 0 && materials["rails"] == 0 && materials["sensor"] == 0) {
// return 0;
// }
Door memory door1 = Door(2, 2, 1);
numDoors = materials["steel_panel"] /= door1.steel_panel;
productStruct.Name = "Door";
productStruct.Quantity = numDoors;
productList.push(productStruct);
return numDoors;
}
//create frames
function frames() public returns (uint256 numFrames) {
require (materials["steel_sheet"] >= 10 && materials["pulley"] >= 2 && materials["motor"] == 2 && materials["steelcable"] == 2);
// if (materials["steel_sheet"] == 0 && materials["pulley"] == 0 && materials["motor"] == 0 && materials["steelcable"] == 0) {
// return 0;
// }
Frame memory frame1 = Frame(10, 2, 2, 2);
numFrames = materials["steel_sheet"] /= frame1.steel_sheet;
productStruct.Name = "Frame";
productStruct.Quantity = numFrames;
productList.push(productStruct);
return numFrames;
}
//create buttons
function buttons() public returns (uint256 numButtons) {
require (materials["button"] >= 2 && materials["ledlight"] >= 2);
// if (materials["button"] == 0 && materials["ledlight"] == 0) {
// return 0;
// }
Button memory button1 = Button(1, 1);
numButtons = materials["button"] /= button1.button;
productStruct.Name = "Button";
productStruct.Quantity = numButtons;
productList.push(productStruct);
return numButtons;
}
// create display
function display() public returns (uint256 numDisplay){
require (materials["screen"] >= 1);
// if (materials["screen"] >= 1) {
// return 0;
// }
Display memory display1 = Display(1);
numDisplay = materials["screen"] /= display1.screen;
productStruct.Name = "Screen";
productStruct.Quantity = numDisplay;
productList.push(productStruct);
return numDisplay;
}
// create batteries
function batteries() public returns (uint256 numBattery){
require (materials["controller"] >= 1);
// if (materials["controller"] >= 1){
// return 0;
// }
Battery memory battery1 = Battery(1);
numBattery = materials["controller"] /= battery1.controller;
productStruct.Name = "Battery";
productStruct.Quantity = numBattery;
productList.push(productStruct);
return numBattery;
}
// gets all the doors
function getDoors() public {
doors();
}
// gets all the frames
function getFrames() public{
frames();
}
// gets all the buttons
function getButtons() public{
buttons();
}
// gets all the displays
function getDisplay() public {
display();
}
//gets all the batteries controllers
function getBatteries() public {
batteries();
}
// gets all the roducts regardless of their type
function getProducts() public returns(Product[] memory){
delete productList;
doors();
frames();
buttons();
display();
batteries();
}
}
|
create doors if (materials["steel_panel"] == 0 && materials["rails"] == 0 && materials["sensor"] == 0) { return 0; }
|
function doors() public returns (uint256 numDoors) {
require(materials["steel_panel"] >= 2 && materials["rails"] >= 2 && materials["sensor"] >= 2);
Door memory door1 = Door(2, 2, 1);
numDoors = materials["steel_panel"] /= door1.steel_panel;
productStruct.Name = "Door";
productStruct.Quantity = numDoors;
productList.push(productStruct);
return numDoors;
}
| 12,547,409 |
[
1,
2640,
741,
1383,
309,
261,
20542,
87,
9614,
334,
73,
292,
67,
13916,
11929,
422,
374,
597,
31824,
9614,
354,
14573,
11929,
422,
374,
597,
31824,
9614,
27426,
11929,
422,
374,
13,
288,
377,
327,
374,
31,
289,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
741,
1383,
1435,
1071,
1135,
261,
11890,
5034,
818,
3244,
1383,
13,
288,
203,
3639,
2583,
12,
20542,
87,
9614,
334,
73,
292,
67,
13916,
11929,
1545,
576,
597,
31824,
9614,
354,
14573,
11929,
1545,
576,
597,
31824,
9614,
27426,
11929,
1545,
576,
1769,
7010,
3639,
2256,
280,
3778,
741,
280,
21,
273,
2256,
280,
12,
22,
16,
576,
16,
404,
1769,
203,
3639,
818,
3244,
1383,
273,
31824,
9614,
334,
73,
292,
67,
13916,
11929,
9531,
741,
280,
21,
18,
334,
73,
292,
67,
13916,
31,
203,
3639,
3017,
3823,
18,
461,
273,
315,
3244,
280,
14432,
203,
3639,
3017,
3823,
18,
12035,
273,
818,
3244,
1383,
31,
203,
3639,
3017,
682,
18,
6206,
12,
5896,
3823,
1769,
203,
3639,
327,
818,
3244,
1383,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.7;
pragma experimental ABIEncoderV2;
import "./SafeMath.sol";
import "./MatryxPlatform.sol";
import "./MatryxForwarder.sol";
import "./MatryxTournament.sol";
library LibCommit {
using SafeMath for uint256;
event GroupMemberAdded(bytes32 indexed commitHash, address indexed user);
event CommitClaimed(bytes32 commitHash);
event CommitCreated(bytes32 indexed parentHash, bytes32 commitHash, address indexed creator, bool indexed isFork);
struct Commit {
address owner;
uint256 timestamp;
bytes32 groupHash;
bytes32 commitHash;
string content;
uint256 value;
uint256 ownerTotalValue;
uint256 totalValue;
uint256 height;
bytes32 parentHash;
}
struct CommitWithdrawalStats {
uint256 totalWithdrawn;
mapping(address=>uint256) amountWithdrawn;
}
struct Group {
address[] members;
mapping(address=>bool) hasMember;
}
/// @dev Returns commit data for the given hash
/// @param data Platform data struct
/// @param commitHash Hash of the commit to return
function getCommit(
address,
address,
MatryxPlatform.Data storage data,
bytes32 commitHash
)
public
view
returns (Commit memory commit)
{
return data.commits[commitHash];
}
/// @dev Returns commit data for the given hash
/// @param data Platform data struct
/// @param commitHash Commit hash
function getBalance(
address,
address,
MatryxPlatform.Data storage data,
bytes32 commitHash
)
public
view
returns (uint256)
{
return data.commitBalance[commitHash];
}
/// @dev Returns commit data for the given content hash
/// @param data Platform data struct
/// @param content Content hash commit was created from
function getCommitByContent(
address,
address,
MatryxPlatform.Data storage data,
string memory content
)
public
view
returns (Commit memory commit)
{
bytes32 lookupHash = keccak256(abi.encodePacked(content));
bytes32 commitHash = data.commitHashes[lookupHash];
return data.commits[commitHash];
}
/// @dev Returns all group members
/// @param data Platform data struct
/// @param commitHash Commit from line of work
function getGroupMembers(
address,
address,
MatryxPlatform.Data storage data,
bytes32 commitHash
)
public
view
returns (address[] memory)
{
bytes32 groupHash = data.commits[commitHash].groupHash;
return data.groups[groupHash].members;
}
/// @dev Returns hashes of all Submissions that were made from this commit
/// @param data Platform data struct
/// @param commitHash Commit hash used for the submissions
function getSubmissionsForCommit(
address,
address,
MatryxPlatform.Data storage data,
bytes32 commitHash
)
public
view
returns (bytes32[] memory)
{
return data.commitToSubmissions[commitHash];
}
/// @dev Returns true if the user is allowed to use Matryx
function _canUseMatryx(
MatryxPlatform.Info storage info,
MatryxPlatform.Data storage data,
address user
)
internal
returns (bool)
{
if (data.blacklist[user]) return false;
if (data.whitelist[user]) return true;
if (IToken(info.token).balanceOf(user) > 0) {
data.whitelist[user] = true;
return true;
}
return false;
}
/// @dev Creates a new group
/// @param data Platform data struct
/// @param commitHash Commit that group is made for
/// @param user First user in the group
function _createGroup(
MatryxPlatform.Data storage data,
bytes32 commitHash,
address user
)
internal
returns (bytes32)
{
bytes32 groupHash = keccak256(abi.encodePacked(commitHash));
data.groups[groupHash].hasMember[user] = true;
data.groups[groupHash].members.push(user);
emit GroupMemberAdded(commitHash, user);
return groupHash;
}
/// @dev Adds a user to a group
/// @param sender msg.sender to the Platform
/// @param data Platform data struct
/// @param commitHash Commit from line of work
/// @param user Member to add to the group
function addGroupMember(
address,
address sender,
MatryxPlatform.Info storage info,
MatryxPlatform.Data storage data,
bytes32 commitHash,
address user
)
public
{
require(_canUseMatryx(info, data, sender), "Must be allowed to use Matryx");
require(data.commits[commitHash].owner != address(0), "Invalid commit");
bytes32 groupHash = data.commits[commitHash].groupHash;
require(data.groups[groupHash].hasMember[sender], "Only group members can add a new member");
require(!data.groups[groupHash].hasMember[user], "User is already a group member");
data.groups[groupHash].hasMember[user] = true;
data.groups[groupHash].members.push(user);
emit GroupMemberAdded(commitHash, user);
}
/// @dev Adds multiple users to a group
/// @param sender msg.sender to the Platform
/// @param data Platform data struct
/// @param commitHash Commit from line of work
/// @param users Members to add to the group
function addGroupMembers(
address,
address sender,
MatryxPlatform.Info storage info,
MatryxPlatform.Data storage data,
bytes32 commitHash,
address[] memory users
)
public
{
require(_canUseMatryx(info, data, sender), "Must be allowed to use Matryx");
require(data.commits[commitHash].owner != address(0), "Invalid commit");
bytes32 groupHash = data.commits[commitHash].groupHash;
require(data.groups[groupHash].hasMember[sender], "Only group members can add a new member");
for(uint256 i = 0; i < users.length; i++) {
address user = users[i];
if (data.groups[groupHash].hasMember[user]) continue;
data.groups[groupHash].hasMember[user] = true;
data.groups[groupHash].members.push(user);
emit GroupMemberAdded(commitHash, user);
}
}
// commit.claimCommit(web3.utils.keccak(sender, salt, ipfsHash))
/// @dev Claims a hash for future use as a commit
/// @param sender msg.sender to the Platform
/// @param data Platform data struct
/// @param commitHash Hash of (sender + salt + content)
function claimCommit(
address,
address sender,
MatryxPlatform.Info storage info,
MatryxPlatform.Data storage data,
bytes32 commitHash
)
public
{
require(_canUseMatryx(info, data, sender), "Must be allowed to use Matryx");
require(data.commitClaims[commitHash] == uint256(0), "Commit hash already claimed");
data.commitClaims[commitHash] = now;
emit CommitClaimed(commitHash);
}
/// @dev Reveals the content hash and salt used in the claiming hash and creates the commit
/// @param sender msg.sender to the Platform
/// @param info Platform info struct
/// @param data Platform data struct
/// @param parentHash Parent commit hash
/// @param isFork If parent commit is being forked
/// @param salt Salt that was used in claiming hash
/// @param content Content hash
/// @param value Commit value
function createCommit(
address,
address sender,
MatryxPlatform.Info storage info,
MatryxPlatform.Data storage data,
bytes32 parentHash,
bool isFork,
bytes32 salt,
string memory content,
uint256 value
)
public
{
require(_canUseMatryx(info, data, sender), "Must be allowed to use Matryx");
bytes32 commitHash = keccak256(abi.encodePacked(sender, salt, content));
_createCommit(sender, info, data, parentHash, commitHash, isFork, content, value);
}
/// @dev Creates a commit and submits it to a Tournament
/// @param sender msg.sender to the Platform
/// @param info Platform info struct
/// @param data Platform data struct
/// @param tAddress Tournament address to submit to
/// @param subContent Submission title and description IPFS hash
/// @param parentHash Parent commit hash
/// @param isFork If fork
/// @param salt Salt that was used in claiming hash
/// @param commitContent Commit content IPFS hash
/// @param value Author-determined commit value
function createSubmission(
address,
address sender,
MatryxPlatform.Info storage info,
MatryxPlatform.Data storage data,
address tAddress,
string memory subContent,
bytes32 parentHash,
bool isFork,
bytes32 salt,
string memory commitContent,
uint256 value
)
public
{
require(_canUseMatryx(info, data, sender), "Must be allowed to use Matryx");
bytes32 commitHash = keccak256(abi.encodePacked(sender, salt, commitContent));
_createCommit(sender, info, data, parentHash, commitHash, isFork, commitContent, value);
LibTournament.createSubmission(tAddress, sender, info, data, subContent, commitHash);
}
/// @dev Initializes a new commit
/// @param owner Commit owner
/// @param data Platform data struct
/// @param parentHash Parent commit hash
/// @param commitHash Commit hash
/// @param isFork If commit is fork of parent
/// @param content Commit content IPFS hash
/// @param value Author-determined commit value
function _createCommit(
address owner,
MatryxPlatform.Info storage info,
MatryxPlatform.Data storage data,
bytes32 parentHash,
bytes32 commitHash,
bool isFork,
string memory content,
uint256 value
)
internal
{
require(value > 0, "Cannot create a zero-value commit");
require(data.commits[commitHash].owner == address(0), "Commit already exists");
require(parentHash == bytes32(0) || data.commits[parentHash].owner != address(0), "Parent must be null or real commit");
if (parentHash != bytes32(0)) {
require(data.commits[parentHash].height < 5000, "Commit chain limit reached");
}
uint256 claimTime = data.commitClaims[commitHash];
require(claimTime > 0 && claimTime < now, "Commit must be claimed in a previous block");
bytes32 lookupHash = keccak256(abi.encodePacked(content));
require(data.commitHashes[lookupHash] == bytes32(0), "Commit already created from content");
bytes32 groupHash;
if (isFork || parentHash == bytes32(0)) {
// if fork or new commit, create a new group
groupHash = _createGroup(data, commitHash, owner);
} else {
// otherwise use parent's group
groupHash = data.commits[parentHash].groupHash;
require(data.groups[groupHash].hasMember[owner], "Must be a part of the group");
}
// calculate owner total value
uint256 ownerTotalValue = value;
if (parentHash != bytes32(0)) {
bytes32 latest = _getLatestCommitForUser(data, parentHash, owner);
if (latest != bytes32(0)) {
ownerTotalValue = ownerTotalValue.add(data.commits[latest].ownerTotalValue);
}
}
// create commit
Commit storage commit = data.commits[commitHash];
commit.owner = owner;
commit.timestamp = claimTime;
commit.groupHash = groupHash;
commit.commitHash = commitHash;
commit.content = content;
commit.value = value;
commit.ownerTotalValue = ownerTotalValue;
commit.totalValue = data.commits[parentHash].totalValue.add(value);
commit.height = data.commits[parentHash].height + 1;
commit.parentHash = parentHash;
data.commitHashes[lookupHash] = commitHash;
// if fork, increase balance of parent
if (isFork) {
require(parentHash != bytes32(0), "Fork must have parent");
uint256 totalValue = data.commits[parentHash].totalValue;
data.totalBalance = data.totalBalance.add(totalValue);
data.commitBalance[parentHash] = data.commitBalance[parentHash].add(totalValue);
require(IToken(info.token).transferFrom(owner, address(this), totalValue), "Transfer failed");
}
emit CommitCreated(parentHash, commitHash, owner, isFork);
}
/// @dev Returns the available reward for a user for a given commit
/// @param data Platform data struct
/// @param commitHash Commit hash to look up the available reward
/// @param user User address
/// @return Amount of MTX the user can withdraw from the given commit
function getAvailableRewardForUser(
address,
address sender,
MatryxPlatform.Data storage data,
bytes32 commitHash,
address user
)
public
view
returns (uint256)
{
bytes32 latestUserCommit = _getLatestCommitForUser(data, commitHash, user);
if (latestUserCommit == bytes32(0)) return 0;
CommitWithdrawalStats storage stats = data.commitWithdrawalStats[commitHash];
uint256 userValue = data.commits[latestUserCommit].ownerTotalValue;
uint256 totalValue = data.commits[commitHash].totalValue;
uint256 balance = data.commitBalance[commitHash];
uint256 totalBalance = balance.add(stats.totalWithdrawn);
uint256 userShare = totalBalance.mul(userValue).div(totalValue).sub(stats.amountWithdrawn[user]);
return userShare;
}
/// @dev Withdraws the caller's available reward for a given commit
/// @param sender msg.sender to the Platform
/// @param info Platform info struct
/// @param data Platform data struct
/// @param commitHash Commit hash to look up the available reward
function withdrawAvailableReward(
address,
address sender,
MatryxPlatform.Info storage info,
MatryxPlatform.Data storage data,
bytes32 commitHash
)
public
{
require(_canUseMatryx(info, data, sender), "Must be allowed to use Matryx");
require(data.commits[commitHash].owner != address(0), "Commit does not exist");
uint256 userShare = getAvailableRewardForUser(sender, sender, data, commitHash, sender);
require(userShare > 0, "No reward available");
CommitWithdrawalStats storage stats = data.commitWithdrawalStats[commitHash];
data.totalBalance = data.totalBalance.sub(userShare);
data.commitBalance[commitHash] = data.commitBalance[commitHash].sub(userShare);
stats.totalWithdrawn = stats.totalWithdrawn.add(userShare);
stats.amountWithdrawn[sender] = stats.amountWithdrawn[sender].add(userShare);
require(IToken(info.token).transfer(sender, userShare), "Transfer failed");
}
/// @dev Returns the hash of the user's latest commit in the chain of ancestors of commitHash
/// @param data Platform data struct
/// @param commitHash Commit hash to look up the available reward
/// @param user User address
/// @return User's latest commit hash
function _getLatestCommitForUser(
MatryxPlatform.Data storage data,
bytes32 commitHash,
address user
)
internal
view
returns (bytes32)
{
Commit storage c = data.commits[commitHash];
// traverse up until root commit
while (true) {
if (c.owner == user) return c.commitHash;
if (c.parentHash == bytes32(0)) return bytes32(0);
c = data.commits[c.parentHash];
}
}
}
|
@dev Creates a commit and submits it to a Tournament @param sender msg.sender to the Platform @param info Platform info struct @param data Platform data struct @param tAddress Tournament address to submit to @param subContent Submission title and description IPFS hash @param parentHash Parent commit hash @param isFork If fork @param salt Salt that was used in claiming hash @param commitContent Commit content IPFS hash @param value Author-determined commit value
|
function createSubmission(
address,
address sender,
MatryxPlatform.Info storage info,
MatryxPlatform.Data storage data,
address tAddress,
string memory subContent,
bytes32 parentHash,
bool isFork,
bytes32 salt,
string memory commitContent,
uint256 value
)
public
{
require(_canUseMatryx(info, data, sender), "Must be allowed to use Matryx");
bytes32 commitHash = keccak256(abi.encodePacked(sender, salt, commitContent));
_createCommit(sender, info, data, parentHash, commitHash, isFork, commitContent, value);
LibTournament.createSubmission(tAddress, sender, info, data, subContent, commitHash);
}
| 12,962,276 |
[
1,
2729,
279,
3294,
471,
720,
22679,
518,
358,
279,
2974,
30751,
225,
5793,
4202,
1234,
18,
15330,
358,
326,
11810,
225,
1123,
540,
11810,
1123,
1958,
225,
501,
540,
11810,
501,
1958,
225,
268,
1887,
377,
2974,
30751,
1758,
358,
4879,
358,
225,
720,
1350,
282,
2592,
3951,
2077,
471,
2477,
2971,
4931,
1651,
225,
982,
2310,
282,
9520,
3294,
1651,
225,
17646,
778,
4202,
971,
12515,
225,
4286,
540,
10848,
716,
1703,
1399,
316,
7516,
310,
1651,
225,
3294,
1350,
225,
10269,
913,
2971,
4931,
1651,
225,
460,
3639,
6712,
17,
72,
4443,
329,
3294,
460,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
17865,
12,
203,
3639,
1758,
16,
203,
3639,
1758,
5793,
16,
203,
3639,
14493,
1176,
92,
8201,
18,
966,
2502,
1123,
16,
203,
3639,
14493,
1176,
92,
8201,
18,
751,
2502,
501,
16,
203,
3639,
1758,
268,
1887,
16,
203,
3639,
533,
3778,
720,
1350,
16,
203,
3639,
1731,
1578,
982,
2310,
16,
203,
3639,
1426,
17646,
778,
16,
203,
3639,
1731,
1578,
4286,
16,
203,
3639,
533,
3778,
3294,
1350,
16,
203,
3639,
2254,
5034,
460,
203,
565,
262,
203,
3639,
1071,
203,
565,
288,
203,
3639,
2583,
24899,
4169,
3727,
15947,
1176,
92,
12,
1376,
16,
501,
16,
5793,
3631,
315,
10136,
506,
2935,
358,
999,
14493,
1176,
92,
8863,
203,
3639,
1731,
1578,
3294,
2310,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
15330,
16,
4286,
16,
3294,
1350,
10019,
203,
203,
3639,
389,
2640,
5580,
12,
15330,
16,
1123,
16,
501,
16,
982,
2310,
16,
3294,
2310,
16,
17646,
778,
16,
3294,
1350,
16,
460,
1769,
203,
3639,
10560,
774,
30751,
18,
2640,
17865,
12,
88,
1887,
16,
5793,
16,
1123,
16,
501,
16,
720,
1350,
16,
3294,
2310,
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
] |
./partial_match/1313161554/0x44d1d32F7961677D16A97B319bb27B073f379FD1/sources/StrategyTriBstnNearLp.sol
|
If extra reward not part of pair, swap to TRI
|
function harvestTwo() public virtual onlyBenevolent {
uint256 _extraReward = IERC20(extraReward).balanceOf(address(this));
uint256 _tri = IERC20(tri).balanceOf(address(this));
if (extraReward == token0 || extraReward == token1) {
if (swapRoutes[extraReward].length > 1 && _tri > 0)
_swapSushiswapWithPath(swapRoutes[extraReward], _tri);
_extraReward = IERC20(extraReward).balanceOf(address(this));
uint256 _keepReward = _extraReward.mul(keepREWARD).div(
keepREWARDMax
);
IERC20(extraReward).safeTransfer(
IController(controller).treasury(),
_keepReward
);
_extraReward = IERC20(extraReward).balanceOf(address(this));
address toToken = extraReward == token0 ? token1 : token0;
if (swapRoutes[toToken].length > 1 && _extraReward > 0)
_swapSushiswapWithPath(
swapRoutes[toToken],
_extraReward.div(2)
);
}
else {
if (swapRoutes[tri].length > 1 && _extraReward > 0)
_swapSushiswapWithPath(swapRoutes[tri], _extraReward);
_tri = IERC20(tri).balanceOf(address(this));
uint256 _keepReward = _tri.mul(keepREWARD).div(keepREWARDMax);
IERC20(tri).safeTransfer(
IController(controller).treasury(),
_keepReward
);
_tri = _tri.sub(_keepReward);
uint256 toToken0 = _tri.div(2);
uint256 toToken1 = _tri.sub(toToken0);
if (swapRoutes[token0].length > 1) {
_swapSushiswapWithPath(swapRoutes[token0], toToken0);
}
if (swapRoutes[token1].length > 1) {
_swapSushiswapWithPath(swapRoutes[token1], toToken1);
}
}
}
| 16,941,181 |
[
1,
2047,
2870,
19890,
486,
1087,
434,
3082,
16,
7720,
358,
22800,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
17895,
26923,
11710,
1435,
1071,
5024,
1338,
38,
4009,
15416,
319,
288,
203,
3639,
2254,
5034,
389,
7763,
17631,
1060,
273,
467,
654,
39,
3462,
12,
7763,
17631,
1060,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
2254,
5034,
389,
16857,
273,
467,
654,
39,
3462,
12,
16857,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
203,
3639,
309,
261,
7763,
17631,
1060,
422,
1147,
20,
747,
2870,
17631,
1060,
422,
1147,
21,
13,
288,
203,
5411,
309,
261,
22270,
8110,
63,
7763,
17631,
1060,
8009,
2469,
405,
404,
597,
389,
16857,
405,
374,
13,
203,
7734,
389,
22270,
55,
1218,
291,
91,
438,
1190,
743,
12,
22270,
8110,
63,
7763,
17631,
1060,
6487,
389,
16857,
1769,
203,
203,
5411,
389,
7763,
17631,
1060,
273,
467,
654,
39,
3462,
12,
7763,
17631,
1060,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
5411,
2254,
5034,
389,
10102,
17631,
1060,
273,
389,
7763,
17631,
1060,
18,
16411,
12,
10102,
862,
21343,
2934,
2892,
12,
203,
7734,
3455,
862,
21343,
2747,
203,
5411,
11272,
203,
5411,
467,
654,
39,
3462,
12,
7763,
17631,
1060,
2934,
4626,
5912,
12,
203,
7734,
467,
2933,
12,
5723,
2934,
27427,
345,
22498,
9334,
203,
7734,
389,
10102,
17631,
1060,
203,
5411,
11272,
203,
203,
5411,
389,
7763,
17631,
1060,
273,
467,
654,
39,
3462,
12,
7763,
17631,
1060,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
5411,
1758,
358,
1345,
273,
2870,
17631,
1060,
422,
1147,
20,
692,
1147,
21,
294,
1147,
20,
31,
2
] |
/**
*Submitted for verification at Etherscan.io on 2020-09-30
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.6;
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);
event Burn(address indexed from, uint256 value);
}
interface ERC223 {
function transfer(address to, uint value, bytes calldata data) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value, bytes indexed data);
}
interface ERC223ReceivingContract {
function tokenFallback(address _from, uint _value, bytes calldata _data) external;
}
library SafeMath{
function mul(uint256 a, uint256 b) internal pure returns (uint256)
{
if (a == 0) {
return 0;}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256)
{
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;
}
}
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);
}
}
}
}
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
/**
* @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());
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
contract TokenContract is IERC20, Pausable,ERC223 {
using SafeMath for uint256;
string internal _name;
string internal _symbol;
uint8 internal _decimals;
uint256 internal _totalSupply;
address internal _admin;
uint256 private tokenSold;
uint256 internal lockedBalance;
event PayeeAdded(address account, uint256 shares);
event PaymentReleased(address to, uint256 amount);
event PaymentReceived(address from, uint256 amount);
event transferredOwnership (address indexed previousOwner,address indexed currentOwner);
uint256 private _totalShares;
uint256 private _totalReleased;
address[] internal _payees;
struct vestingDetails {
address user;
uint256 amount;
uint256 startTime;
uint256 endTime;
bool vestingStatus;
}
mapping(address => uint256) private _shares;
mapping(address => uint256) private _released;
mapping (address => uint256) internal balances;
mapping (address => mapping (address => uint256)) internal allowed;
mapping (address=> vestingDetails) internal vesting;
constructor() public {
_admin = msg.sender;
_symbol = "NBK";
_name = "Notebook";
_decimals = 18;
_totalSupply = 98054283* 10**uint(_decimals);
balances[msg.sender]=_totalSupply;
}
modifier ownership() {
require(msg.sender == _admin);
_;
}
function name() public view returns (string memory)
{
return _name; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function symbol() public view returns (string memory)
{
return _symbol; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function _tokenSold() public view returns(uint256) {
return tokenSold; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function decimals() public view returns (uint8)
{
return _decimals; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function totalSupply() public override view returns (uint256)
{
return _totalSupply; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function transfer(address _to, uint256 _value) public virtual override returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
balances[msg.sender] = balances[msg.sender].sub(_value); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
balances[_to] = (balances[_to]).add( _value); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit IERC20.Transfer(msg.sender, _to, _value);
tokenSold += _value; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
return true;
}
function balanceOf(address _owner) public override view returns (uint256 balance) {
return balances[_owner]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function transferFrom(address _from, address _to, uint256 _value) public virtual override returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
require(_value <= allowed[_from][msg.sender]); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
balances[_from] = (balances[_from]).sub( _value); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
balances[_to] = (balances[_to]).add(_value); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
allowed[_from][msg.sender] = (allowed[_from][msg.sender]).sub(_value); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
tokenSold += _value; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit IERC20.Transfer(_from, _to, _value);
return true;
}
function openVesting(address _user,uint256 _amount, uint256 _eTime) ownership public returns(bool) {
lockTokens(_amount);
vesting[_user].user = _user; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
vesting[_user].amount= _amount; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
vesting[_user].startTime = now; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
vesting[_user].endTime = _eTime; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
vesting[_user].vestingStatus = true; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
return true;
}
function releaseVesting(address _user) ownership public returns(bool) {
require(now > vesting[_user].endTime); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
vesting[_user].vestingStatus = false; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
unlockTokens(vesting[_user].amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
return true;
}
function approve(address _spender, uint256 _value) public override returns (bool) {
allowed[msg.sender][_spender] = _value; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit IERC20.Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public override view returns (uint256) {
return allowed[_owner][_spender]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function burn(uint256 _value) public ownership returns (bool success) {
require(balances[msg.sender] >= _value); // Check if the sender has enough //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
balances[msg.sender] -= _value; // Subtract from the sender //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
_totalSupply -= _value; // Updates totalSupply //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
//emit Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*/
function burnFrom(address _from, uint256 _value) public ownership returns (bool success) {
require(balances[_from] >= _value); // Check if the targeted balance is enough //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
require(_value <= allowed[_from][msg.sender]); // Check allowance //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
balances[_from] -= _value; // Subtract from the targeted balance //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
allowed[_from][msg.sender] -= _value; // Subtract from the sender's allowance //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
_totalSupply -= _value; // Update totalSupply //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
// emit Burn(_from, _value);
return true;
}
//Admin can transfer his ownership to new address
function transferownership(address _newaddress) ownership public returns(bool){
require(_newaddress != address(0));
emit transferredOwnership(_admin, _newaddress); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
_admin=_newaddress; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
return true;
}
function ownerAddress() public view returns(address) {
return _admin; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function totalShares() public view returns (uint256) {
return _totalShares; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
/**
* @dev Getter for the total amount of Ether already released.
*/
function totalReleased() public view returns (uint256) {
return _totalReleased; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
/**
* @dev Getter for the amount of shares held by an account.
*/
function shares(address account) public view returns (uint256) {
return _shares[account]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
/**
* @dev Getter for the amount of Ether already released to a payee.
*/
function released(address account) public view returns (uint256) {
return _released[account]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
/**
* @dev Getter for the address of the payee number `index`.
*/
function payee(uint256 index) public view returns (address) {
return _payees[index]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
receive () external payable virtual {
emit PaymentReceived(msg.sender, msg.value);
}
function distributeEthersToHolders (address[] memory payees, uint256[] memory amountOfEther) public payable {
// solhint-disable-next-line max-line-length
require(payees.length == amountOfEther.length, "PaymentSplitter: payees and shares length mismatch");
require(payees.length > 0, "PaymentSplitter: no payees");
for (uint256 i = 0; i < payees.length; i++) {
_addPayee(payees[i], amountOfEther[i]);
}
}
function _addPayee(address account, uint256 shares_) private {
require(account != address(0), "PaymentSplitter: account is the zero address");
require(shares_ > 0, "PaymentSplitter: shares are 0");
require(_shares[account] == 0, "PaymentSplitter: account already has shares");
_payees.push(account);
_shares[account] = shares_;
_totalShares = _totalShares.add(shares_);
emit PayeeAdded(account, shares_);
}
function releaseEthersToHolder(address payable account) public virtual {
require(_shares[account] > 0, "PaymentSplitter: account has no shares"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
uint256 totalReceived = address(this).balance.add(_totalReleased); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
uint256 payment = totalReceived.mul(_shares[account]).div(_totalShares).sub(_released[account]); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
require(payment != 0, "PaymentSplitter: account is not due payment");
_released[account] = _released[account].add(payment); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
_totalReleased = _totalReleased.add(payment); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
account.transfer(payment);
emit PaymentReleased(account, payment);
}
function pauseToken() public ownership whenNotPaused {
_pause();
}
function unPauseToken() public ownership whenPaused {
_unpause();
}
function transfer(address _to, uint _value, bytes memory _data) public virtual override returns (bool ){
require(_value > 0 );
if(isContract(_to)) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallback(msg.sender, _value, _data);
}
balances[msg.sender] = balances[msg.sender].sub(_value); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
balances[_to] = (balances[_to]).add( _value); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
function isContract(address _addr) private view returns (bool is_contract) {
uint length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_addr)
}
return (length>0);
}
function lockTokens(uint256 _amount) ownership public returns(bool){
require( balances[_admin]>=_amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
balances[_admin] = balances[_admin].sub(_amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
lockedBalance = lockedBalance.add(_amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
return true;
}
function unlockTokens(uint256 _amount) ownership public returns (bool) {
require(lockedBalance >= _amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
balances[_admin] = balances[_admin].add(_amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
lockedBalance = lockedBalance.sub(_amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
return true;
}
function viewLockedBalance() ownership public view returns(uint256) {
return lockedBalance; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
}
contract NBK is TokenContract {
constructor () public {
}
function transfer(address _to, uint256 _amount) public whenNotPaused override returns(bool) {
return super.transfer(_to,_amount);
}
function transferFrom(address _from, address _to, uint256 _amount) public whenNotPaused override returns(bool) {
return super.transferFrom(_from,_to,_amount);
}
}
|
* @dev Getter for the address of the payee number `index`./
|
function payee(uint256 index) public view returns (address) {
}
| 12,989,952 |
[
1,
8461,
364,
326,
1758,
434,
326,
8843,
1340,
1300,
1375,
1615,
8338,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
8843,
1340,
12,
11890,
5034,
770,
13,
1071,
1476,
1135,
261,
2867,
13,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0xfB2F42d40F1Bcbbc16060CFbaf9Cf3dc0077Ec65/sources/gist-f61d60d631fcc3556592f3c1593a45db/contracts/LightningShiba.sol
|
_origin is the wallet controlling the bot, it can never be a contract only a real person
|
_banSeller(_origin);
| 3,059,941 |
[
1,
67,
10012,
353,
326,
9230,
3325,
2456,
326,
2512,
16,
518,
848,
5903,
506,
279,
6835,
1338,
279,
2863,
6175,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
7734,
389,
21515,
22050,
24899,
10012,
1769,
4766,
11794,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/42/0xCcD42bFE3f316B6e9f95587159772dff49561582/sources/MasterchefDelegator.sol
|
Withdraw LP tokens from MasterChef.
|
function withdraw(uint256 _pid) public virtual {
if (block.number <= stageOneDepositEndBlock) {
(uint256 amount, , , ) = stageOne.getUserInfo(_pid, msg.sender);
stageOne.withdraw(_pid, msg.sender);
emit Withdraw(msg.sender, _pid, amount);
return;
}
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount > 0, "user is not existed");
require(user.endBlock < block.number, "token is still locked");
mintNTS(address(this), block.number);
updatePoolDividend(_pid);
uint256 originWeight = user.originWeight;
PoolInfo storage pool = poolInfo[_pid];
uint256 totalDividend = pool.accumulativeDividend;
uint256 usersTotalWeight = pool.usersTotalWeight;
uint256 userWeight = user.inviteeWeight.add(originWeight);
InvitationInfo storage userInvitation =
usersRelationshipInfo[msg.sender];
if(!userInvitation.isWithdrawn){
userWeight = userWeight.add(originWeight.div(INVITOR_WEIGHT));
}
if (totalDividend > 0) {
uint256 pending =
totalDividend.mul(userWeight).div(usersTotalWeight);
pool.accumulativeDividend = totalDividend.sub(pending);
uint256 devDividend =
pending.mul(devDividendWeight).div(
devDividendWeight.add(userDividendWeight)
);
safeNTSTransfer(devAddress, devDividend);
pending = pending.sub(devDividend);
safeNTSTransfer(msg.sender, pending);
}
pool.usersTotalWeight = usersTotalWeight.sub(userWeight);
uint256 amount = user.amount;
userInfo[_pid][msg.sender].amount = 0;
userInfo[_pid][msg.sender].originWeight = 0;
userInfo[_pid][msg.sender].endBlock = 0;
IERC20(pool.lpTokenSwap).safeTransfer(address(msg.sender), amount);
uint256 lpTokenAmount = pool.lpTokenAmount.sub(amount);
pool.lpTokenAmount = lpTokenAmount;
uint256 oracleWeight = 0;
if (lpTokenAmount == 0) oracleWeight = 0;
else {
oracleWeight = getOracleWeight(pool, lpTokenAmount, true);
}
pool.oracleWeight = oracleWeight;
resetInvitationRelationship(_pid, msg.sender, originWeight);
emit Withdraw(msg.sender, _pid, amount);
}
| 3,410,677 |
[
1,
1190,
9446,
511,
52,
2430,
628,
13453,
39,
580,
74,
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,
445,
598,
9446,
12,
11890,
5034,
389,
6610,
13,
1071,
5024,
288,
203,
3639,
309,
261,
2629,
18,
2696,
1648,
6009,
3335,
758,
1724,
1638,
1768,
13,
288,
203,
5411,
261,
11890,
5034,
3844,
16,
269,
269,
262,
273,
6009,
3335,
18,
588,
21015,
24899,
6610,
16,
1234,
18,
15330,
1769,
203,
5411,
6009,
3335,
18,
1918,
9446,
24899,
6610,
16,
1234,
18,
15330,
1769,
203,
5411,
3626,
3423,
9446,
12,
3576,
18,
15330,
16,
389,
6610,
16,
3844,
1769,
203,
5411,
327,
31,
203,
3639,
289,
203,
3639,
25003,
2502,
729,
273,
16753,
63,
67,
6610,
6362,
3576,
18,
15330,
15533,
203,
3639,
2583,
12,
1355,
18,
8949,
405,
374,
16,
315,
1355,
353,
486,
20419,
8863,
203,
3639,
2583,
12,
1355,
18,
409,
1768,
411,
1203,
18,
2696,
16,
315,
2316,
353,
4859,
8586,
8863,
203,
3639,
312,
474,
1784,
55,
12,
2867,
12,
2211,
3631,
1203,
18,
2696,
1769,
203,
3639,
1089,
2864,
7244,
26746,
24899,
6610,
1769,
203,
3639,
2254,
5034,
4026,
6544,
273,
729,
18,
10012,
6544,
31,
203,
3639,
8828,
966,
2502,
2845,
273,
2845,
966,
63,
67,
6610,
15533,
203,
3639,
2254,
5034,
2078,
7244,
26746,
273,
2845,
18,
8981,
11276,
7244,
26746,
31,
203,
3639,
2254,
5034,
3677,
5269,
6544,
273,
2845,
18,
5577,
5269,
6544,
31,
203,
3639,
2254,
5034,
729,
6544,
273,
729,
18,
27154,
73,
6544,
18,
1289,
12,
10012,
6544,
1769,
203,
3639,
5454,
8773,
966,
2502,
729,
19896,
273,
203,
5411,
3677,
8180,
966,
63,
3576,
18,
15330,
15533,
203,
2
] |
./partial_match/42/0x4B017C0E6Cde615915cA7B2aAA45E8220f98e8AA/sources/TokenMaster.sol
|
ALD tokens created per block.
|
uint256 public ALDPerBlock = 10;
| 8,872,176 |
[
1,
1013,
40,
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,
7981,
40,
2173,
1768,
273,
1728,
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/0x492B6F8A53D1c42cC2DD352788a6C02c557BE9F5/sources/contracts/integrations/curve/common/Stablz3CRVMetaPoolIntegration.sol
|
@notice Check if an address is an accepted deposit token @param _token Token address @return bool true if it is a supported deposit token, false if not
|
function isDepositToken(address _token) public override view returns (bool) {
return _token == META_TOKEN || _isBasePoolToken(_token);
}
| 3,190,060 |
[
1,
1564,
309,
392,
1758,
353,
392,
8494,
443,
1724,
1147,
225,
389,
2316,
3155,
1758,
327,
1426,
638,
309,
518,
353,
279,
3260,
443,
1724,
1147,
16,
629,
309,
486,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
353,
758,
1724,
1345,
12,
2867,
389,
2316,
13,
1071,
3849,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
327,
389,
2316,
422,
16970,
67,
8412,
747,
389,
291,
2171,
2864,
1345,
24899,
2316,
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
] |
./partial_match/1/0xcDdc0F6053432dE3dd0F8dB3786D696fffC3A860/sources/OriginEthStrategy.sol
|
* @dev returns potential rewards at the current moment if operator will withdraw all assets from strategy/
|
function getPotentialRewards() view public returns(int256){
return getPotentialRewards(depositedBase);
}
| 15,778,596 |
[
1,
6154,
8555,
283,
6397,
622,
326,
783,
10382,
1377,
309,
3726,
903,
598,
9446,
777,
7176,
628,
6252,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
1689,
352,
2001,
17631,
14727,
1435,
1476,
1071,
1135,
12,
474,
5034,
15329,
203,
3639,
327,
1689,
352,
2001,
17631,
14727,
12,
323,
1724,
329,
2171,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
// 0.6.12+commit.27d51765
import "./@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./@openzeppelin/contracts/utils/EnumerableSet.sol";
import "./@openzeppelin/contracts/math/SafeMath.sol";
import "./@openzeppelin/contracts/access/Ownable.sol";
// LP token (ERC20 reward) based staking for Rentible
//
// See:
// https://rentible.io/
// https://staking.rentible.io/
//
// Inspired by:
// https://github.com/SashimiProject/sashimiswap/blob/master/contracts/MasterChef.sol
// https://github.com/ltonetwork
contract RentibleStaking is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/* -------------------------------------------------------------------- */
/* --- main variables ------------------------------------------------ */
/* -------------------------------------------------------------------- */
// when staking starts, unix time
uint256 public immutable startTime;
// when staking ends, unix time
uint256 public immutable endTime;
// ------
// Uniswap V2 liquidity token (the staked token)
IERC20 public immutable lpToken;
// Rentible ERC20 token (in our case RNB, as reward)
IERC20 public immutable erc20;
// ------
// NOTE: in the last changes we made 4 real days into one "contract" day!
// in sec
uint256 public immutable dayLength;
// in sec
uint256 public immutable stakingProgramTimeLength;
// ------
// NOTE (!!!): if you modify the array size, please modify max in getCurrentStakingDayNumber() and updateDailyTotalLptAmount() too (to array size - 1)
// NOTE: in the last changes we made 4 real days into one "contract" day!
// how many liquidity tokens were in the staking (per day) (add/subtract happens upon deposit, withdraw) (every user combined)
uint256[93] public dailyTotalLptAmount;
// liquidity tokens in the staking as of now (every user combined) (add/subtract happens upon deposit, withdraw) (every user combined)
uint256 public currentTotalLptAmount;
// ------
// NOTE (!!!): if you modify the array size, please modify max in getCurrentStakingDayNumber() and updateDailyTotalLptAmount() too (to array size - 1)
// NOTE: in the last changes we made 4 real days into one "contract" day!
// total reward, has to equal the sum of the dailyPlannedErc20RewardAmounts (payed out rewards are not subtracted from this)
uint256 public immutable totalErc20RewardAmount;
// total reward per "contract" day, planned (practically treated as fixed/immutable, payed out rewards are not subtracted from this))
// has to be equal to totalErc20RewardAmount (and after full reward funding equal to fundedErc20RewardAmount)
// note: there is a starting 0 and a closing 0
uint256[93] public dailyPlannedErc20RewardAmounts = [0, 5753337571515390000000, 5710955710955710000000, 5668573850392040000000, 5626191989828360000000, 5583810129264680000000, 5541428268701000000000, 5499046408137330000000, 5456664547573650000000, 5414282687009970000000, 5371900826446290000000, 5329518965882620000000, 5287137105318940000000, 5244755244755260000000, 5202373384191580000000, 5159991523627910000000, 5117609663064230000000, 5075227802500550000000, 5032845941936870000000, 4990464081373200000000, 4948082220809520000000, 4905700360245840000000, 4863318499682160000000, 4820936639118490000000, 4778554778554810000000, 4736172917991130000000, 4693791057427450000000, 4651409196863780000000, 4609027336300100000000, 4566645475736420000000, 4524263615172740000000, 4481881754609070000000, 4439499894045390000000, 4397118033481710000000, 4354736172918030000000, 4312354312354360000000, 4269972451790680000000, 4227590591227000000000, 4185208730663320000000, 4142826870099650000000, 4100445009535970000000, 4058063148972290000000, 4015681288408610000000, 3973299427844940000000, 3930917567281260000000, 3888535706717580000000, 3846153846153900000000, 3803771985590230000000, 3761390125026550000000, 3719008264462870000000, 3676626403899190000000, 3634244543335510000000, 3591862682771830000000, 3549480822208150000000, 3507098961644470000000, 3464717101080790000000, 3422335240517110000000, 3379953379953430000000, 3337571519389750000000, 3295189658826080000000, 3252807798262400000000, 3210425937698720000000, 3168044077135040000000, 3125662216571360000000, 3083280356007680000000, 3040898495444000000000, 2998516634880320000000, 2956134774316640000000, 2913752913752960000000, 2871371053189280000000, 2828989192625600000000, 2786607332061920000000, 2744225471498250000000, 2701843610934570000000, 2659461750370890000000, 2617079889807210000000, 2574698029243530000000, 2532316168679850000000, 2489934308116170000000, 2447552447552490000000, 2405170586988810000000, 2362788726425130000000, 2320406865861450000000, 2278025005297770000000, 2235643144734100000000, 2193261284170420000000, 2150879423606740000000, 2108497563043060000000, 2066115702479380000000, 2023733841915700000000, 1981351981352020000000, 1938970120788340000000, 0];
// total reward funded (so far) (payed out rewards are not subtracted from this),
// eventually (after funding) has to be equal to totalErc20RewardAmount
uint256 public fundedErc20RewardAmount = 0;
// total reward, at start the same as dailyPlannedErc20RewardAmounts,
// daily counter,
// not yet tied to any UserInfo object,
// subtractions happen when reward is assigned to a UserInfo object
// (rewards are always payed out through UserInfo object, not directly from here!)
// note: there is a starting 0 and a closing 0
uint256[93] public dailyErc20RewardAmounts = [0, 5753337571515390000000, 5710955710955710000000, 5668573850392040000000, 5626191989828360000000, 5583810129264680000000, 5541428268701000000000, 5499046408137330000000, 5456664547573650000000, 5414282687009970000000, 5371900826446290000000, 5329518965882620000000, 5287137105318940000000, 5244755244755260000000, 5202373384191580000000, 5159991523627910000000, 5117609663064230000000, 5075227802500550000000, 5032845941936870000000, 4990464081373200000000, 4948082220809520000000, 4905700360245840000000, 4863318499682160000000, 4820936639118490000000, 4778554778554810000000, 4736172917991130000000, 4693791057427450000000, 4651409196863780000000, 4609027336300100000000, 4566645475736420000000, 4524263615172740000000, 4481881754609070000000, 4439499894045390000000, 4397118033481710000000, 4354736172918030000000, 4312354312354360000000, 4269972451790680000000, 4227590591227000000000, 4185208730663320000000, 4142826870099650000000, 4100445009535970000000, 4058063148972290000000, 4015681288408610000000, 3973299427844940000000, 3930917567281260000000, 3888535706717580000000, 3846153846153900000000, 3803771985590230000000, 3761390125026550000000, 3719008264462870000000, 3676626403899190000000, 3634244543335510000000, 3591862682771830000000, 3549480822208150000000, 3507098961644470000000, 3464717101080790000000, 3422335240517110000000, 3379953379953430000000, 3337571519389750000000, 3295189658826080000000, 3252807798262400000000, 3210425937698720000000, 3168044077135040000000, 3125662216571360000000, 3083280356007680000000, 3040898495444000000000, 2998516634880320000000, 2956134774316640000000, 2913752913752960000000, 2871371053189280000000, 2828989192625600000000, 2786607332061920000000, 2744225471498250000000, 2701843610934570000000, 2659461750370890000000, 2617079889807210000000, 2574698029243530000000, 2532316168679850000000, 2489934308116170000000, 2447552447552490000000, 2405170586988810000000, 2362788726425130000000, 2320406865861450000000, 2278025005297770000000, 2235643144734100000000, 2193261284170420000000, 2150879423606740000000, 2108497563043060000000, 2066115702479380000000, 2023733841915700000000, 1981351981352020000000, 1938970120788340000000, 0];
// has to be equal to the sum of the dailyErc20RewardAmounts array, payed out rewards are subtracted from this, this is the remaing unassigned reward, not tied to any UserInfo object
uint256 public currentTotalErc20RewardAmount = 0;
// ------
// info of each user (depositor)
struct UserInfo {
// NOTE: in the last changes we made 4 real days into one "contract" day!
uint256 currentlyAssignedRewardAmount; // reward (ERC20 Rentible token) amount, that was already clearly assigned to this UserInfo object (meaning subtracted from dailyErc20RewardAmounts and currentTotalErc20RewardAmount)
uint256 rewardCountedUptoDay; // the "contract" day (stakingDayNumber) up to which currentlyAssignedRewardAmount was already handled
uint256 lptAmount;
}
// user (UserInfo) mapping
mapping (address => UserInfo) public userInfo;
/* -------------------------------------------------------------------- */
/* --- events --------------------------------------------------------- */
/* -------------------------------------------------------------------- */
event Deposit(address indexed user, uint256 depositedLptAmount);
event WithdrawLptCore(address indexed user, uint256 withdrawnLptAmount);
event TakeOutSomeOfTheAccumulatedReward(address indexed user, uint256 rewardAmountTakenOut);
event Fund(address indexed ownerUser, uint256 addedErc20Amount);
/* -------------------------------------------------------------------- */
/* --- constructor ---------------------------------------------------- */
/* -------------------------------------------------------------------- */
// https://abi.hashex.org/#
// 0000000000000000000000005af3176021e2450850377d4b166364e5c52ae82f000000000000000000000000e764f66e9e165cd29116826b84e943176ac8e91c0000000000000000000000000000000000000000000000000000000000000000
// _startTime = 0: means start instantly upon deploy
constructor(IERC20 _erc20, IERC20 _lpToken, uint256 _startTime) public {
require(_startTime == 0 || _startTime > 1621041111, "constructor: _startTime is too small");
// ---
erc20 = _erc20; // RNB (for rewards)
lpToken = _lpToken; // RNB/ETH Uni V2 (the staked token)
// ---
// NOTE: in the last changes we made 4 real days into one contract day
// variables were parameterized already (for testing etc.) and were not renamed
uint256 dayLengthT = 345600; // 86400 sec = one day, 345600 sec = 4 days
// uint256 dayLengthT = 600; // scaled down, for testing, ratio 10 minutes = 4 day
dayLength = dayLengthT; // this way it can be immutable
// ---
uint256 startTimeT;
if (_startTime > 0) {
startTimeT = _startTime;
} else {
startTimeT = block.timestamp; // default is current time
}
startTime = SafeMath.sub(startTimeT, dayLengthT); // this way it can be immutable, we subtract 1 day to skip day 0
// ---
// NOTE: in the last changes we made 4 real days into one "contract" day
// 364 real days = 91 contract days = staking program length
uint256 stakingProgramTimeLengthT = SafeMath.mul(dayLengthT, 91);
stakingProgramTimeLength = stakingProgramTimeLengthT; // this way it can be immutable
// ---
uint256 endTimeT = SafeMath.add(startTimeT, stakingProgramTimeLengthT);
endTime = endTimeT; // this way it can be immutable
// ---
uint256 totalErc20RewardAmountT = 350000000000000000000000; // 350000 RNB
totalErc20RewardAmount = totalErc20RewardAmountT; // this way it can be immutable
}
/* -------------------------------------------------------------------- */
/* --- basic write operations for the depositors ---------------------- */
/* -------------------------------------------------------------------- */
// Deposit LP tokens (by the users/investors/depositors)
function deposit(uint256 _depositLptAmount) public {
require(_depositLptAmount > 0, "deposit: _depositLptAmount must be positive");
require(block.timestamp >= startTime, "deposit: cannot deposit yet, current time is before startTime");
require(block.timestamp < endTime, "deposit: cannot deposit anymore, current time is after endTime");
// require(fundedErc20RewardAmount == totalErc20RewardAmount, "deposit: please wait until owner funds the rewards");
// ---
UserInfo storage user = userInfo[msg.sender];
addToTheUsersAssignedReward();
// ---
user.lptAmount = SafeMath.add(user.lptAmount, _depositLptAmount);
lpToken.safeTransferFrom(msg.sender, address(this), _depositLptAmount);
currentTotalLptAmount = SafeMath.add(currentTotalLptAmount, _depositLptAmount);
updateDailyTotalLptAmount();
// ---
emit Deposit(msg.sender, _depositLptAmount);
}
function updateDailyTotalLptAmount() private {
// NOTE: in the last changes we made 4 real days into one "contract" day
uint256 currentStakingDayNumber = getCurrentStakingDayNumber();
for (uint256 i = currentStakingDayNumber; i <= 92; i++) {
dailyTotalLptAmount[i] = currentTotalLptAmount;
}
}
/*
Withdraw variants:
1) withdrawLptCore(uint256) = emergency withdraw, user receives the param amount of LPT, does not receive RNB, can unrecoverably loose some reward RNB
2) withdrawWithoutReward(uint256) = user receives the param amount of LPT, plus the method calculates and updates the reward amount in UserInfo object (but leaves it there)
3) withdrawAllWithoutReward() = same as 3, amount is fixed/all (user.lptAmount)
4) takeOutSomeOfTheAccumulatedReward(uint256) = leaves deposited LPT untouched, user receives the param amount of rewards
5) takeOutTheAccumulatedReward() = same as 4, reward amount is fixed/all (user.currentlyAssignedRewardAmount, it gets refreshed/recalculated before take out)
6) withdrawWithAllReward(uint256) = method 4, reward amount is fixed/all (user.currentlyAssignedRewardAmount); plus after that method 2
7) withdrawAllWithAllReward() = method 4, reward amount is fixed/all (user.currentlyAssignedRewardAmount), plus after that method 2, amount is fixed/all (user.lptAmount)
*/
// 1
// this works as the inner function of all LP token withdraws, but also on its own as a kind of emergency withdraw
function withdrawLptCore(uint256 _withdrawLptAmount) public {
require(_withdrawLptAmount > 0, "withdrawLptCore: _withdrawLptAmount must be positive");
UserInfo storage user = userInfo[msg.sender];
require(user.lptAmount >= _withdrawLptAmount, "withdrawLptCore: cannot withdraw more than the deposit, _withdrawLptAmount is too big");
lpToken.safeTransfer(msg.sender, _withdrawLptAmount); // send lpt to the user
user.lptAmount = SafeMath.sub(user.lptAmount, _withdrawLptAmount); // subtract from the user's lpt
currentTotalLptAmount = SafeMath.sub(currentTotalLptAmount, _withdrawLptAmount); // subtract from the global counter
updateDailyTotalLptAmount(); // update the global daily (array) counters
emit WithdrawLptCore(msg.sender, _withdrawLptAmount);
}
// 2
function withdrawWithoutReward(uint256 _withdrawLptAmount) public {
addToTheUsersAssignedReward(); // updates UserInfo object
withdrawLptCore(_withdrawLptAmount);
}
// 3
function withdrawAllWithoutReward() public {
addToTheUsersAssignedReward(); // updates UserInfo object
withdrawWithoutReward(depositedLptOfTheUser());
}
// 4
function takeOutSomeOfTheAccumulatedReward(uint256 _rewardAmountToBeTakenOut) public returns(uint256) {
require(_rewardAmountToBeTakenOut > 0, "takeOutSomeOfTheAccumulatedReward: _rewardAmountToBeTakenOut must be positive");
addToTheUsersAssignedReward(); // updates UserInfo object
UserInfo storage user = userInfo[msg.sender];
require(user.currentlyAssignedRewardAmount >= _rewardAmountToBeTakenOut, "withdraw: user.currentlyAssignedRewardAmount is too low for this operation, _rewardAmountToBeTakenOut is too big");
// note: will always send out only what is currently held inside the UserInfo object (never directly from the global dailyErc20RewardAmounts[] array)
// (so addToTheUsersAssignedReward() call is needed before transfer)
erc20.safeTransfer(msg.sender, _rewardAmountToBeTakenOut); // send erc20 reward to the user
user.currentlyAssignedRewardAmount = SafeMath.sub(user.currentlyAssignedRewardAmount, _rewardAmountToBeTakenOut);
emit TakeOutSomeOfTheAccumulatedReward(msg.sender, _rewardAmountToBeTakenOut);
return _rewardAmountToBeTakenOut;
}
// 5
function takeOutTheAccumulatedReward() public returns(uint256) {
addToTheUsersAssignedReward(); // updates UserInfo object
takeOutSomeOfTheAccumulatedReward(assignedRewardOfTheUser());
}
// 6
function withdrawWithAllReward(uint256 _withdrawLptAmount) public {
addToTheUsersAssignedReward(); // updates UserInfo object
uint256 a = assignedRewardOfTheUser();
if (a > 0) {
takeOutSomeOfTheAccumulatedReward(a);
}
withdrawWithoutReward(_withdrawLptAmount);
}
// 7
function withdrawAllWithAllReward() public {
addToTheUsersAssignedReward(); // updates UserInfo object
uint256 a = assignedRewardOfTheUser();
if (a > 0) {
takeOutSomeOfTheAccumulatedReward(a);
}
uint256 d = depositedLptOfTheUser();
if (d > 0) {
withdrawWithoutReward(d);
}
}
/* -------------------------------------------------------------------- */
/* --- reward related read/write operations for the depositors -------- */
/* -------------------------------------------------------------------- */
// Updates the current accumulated/assigned reward (RNB) of the user (depositor)
// (alters state in the user's UserInfo object and other places).
function addToTheUsersAssignedReward() public returns(uint256) {
uint256 currentStakingDayNumber = getCurrentStakingDayNumber();
uint256 currentStakingDayNumberMinusOne = SafeMath.sub(currentStakingDayNumber, 1);
if (currentStakingDayNumber == 0) {
return 0;
}
UserInfo storage user = userInfo[msg.sender];
if (user.lptAmount == 0) {
// when user.lptAmount was set to 0 we did the calculations and state changes, if lptAmount is still 0, it means no change since then
// note: important to always call addToTheUsersAssignedReward() before transfers!
user.rewardCountedUptoDay = currentStakingDayNumberMinusOne;
return user.currentlyAssignedRewardAmount;
}
// ---
// NOTE: in the last changes we made 4 real days into one contract day
uint256 rewardCountedUptoDay = user.rewardCountedUptoDay;
uint256 rewardCountedUptoDayNextDay = SafeMath.add(rewardCountedUptoDay, 1);
if (!(rewardCountedUptoDayNextDay <= currentStakingDayNumberMinusOne)) {
return user.currentlyAssignedRewardAmount;
}
// ---
uint256 usersRewardRecently = 0;
for (uint256 i = rewardCountedUptoDayNextDay; i <= currentStakingDayNumberMinusOne; i++) {
if (dailyTotalLptAmount[i] == 0) {
continue;
}
// logic used here is because of integer division, we improve precision (not perfect solution, good enough)
// (sample uses 10^4 instead of 10^19 units)
// 49.5k = users stake, 80k = total stake, 2k = daily reward)
// correct value would be = 1237.5
// (49 500 / 80 000 = 0.61875 = 0) * 2000 = 0;
// ((49 500 * 100) / 80 000 = 61,875 = 61) * 2000 = 122000) / 100 = 1220 = 1220
// ((49 500 * 1000) / 80 000 = 618,75 = 618) * 2000 = 1236000) / 1000 = 1236 = 1236
// ((49 500 * 10000) / 80 000 = 6187.5 = 6187) * 2000 = 12374000) / 10000 = 1237.4 = 1237
uint256 raiser = 10000000000000000000; // 10^19
// uint256 rew = (((user.lptAmount.mul(raiser)).div(dailyTotalLptAmount[i])).mul(dailyPlannedErc20RewardAmounts[i])).div(raiser);
// same with SafeMath:
uint256 rew = SafeMath.mul(user.lptAmount, raiser);
rew = SafeMath.div(rew, dailyTotalLptAmount[i]);
rew = SafeMath.mul(rew, dailyPlannedErc20RewardAmounts[i]);
rew = SafeMath.div(rew, raiser);
if (dailyErc20RewardAmounts[i] < rew) {
// the has to be added amount is less, than the remaining (global), can happen because of slight rounding issues at the very end
// not really... more likely the oposite (that some small residue gets left behind)
rew = dailyErc20RewardAmounts[i];
}
usersRewardRecently = SafeMath.add(usersRewardRecently, rew);
dailyErc20RewardAmounts[i] = SafeMath.sub(dailyErc20RewardAmounts[i], rew);
}
user.currentlyAssignedRewardAmount = SafeMath.add(user.currentlyAssignedRewardAmount, usersRewardRecently);
currentTotalErc20RewardAmount = SafeMath.sub(currentTotalErc20RewardAmount, usersRewardRecently);
user.rewardCountedUptoDay = currentStakingDayNumberMinusOne;
return user.currentlyAssignedRewardAmount;
}
// Current additionally assignable reward (RNB) of the user (depositor), meaning what wasn't added to UserInfo, but will be upon the next addToTheUsersAssignedReward() call
// (read only, does not save/alter state)
function calculateUsersAssignableReward() public view returns(uint256) {
// ---
// --- similar to addToTheUsersAssignedReward(), but without the writes, plus few other modifications
// ---
uint256 currentStakingDayNumber = getCurrentStakingDayNumber();
uint256 currentStakingDayNumberMinusOne = SafeMath.sub(currentStakingDayNumber, 1);
if (currentStakingDayNumber == 0) {
return 0;
}
UserInfo storage user = userInfo[msg.sender];
if (user.lptAmount == 0) {
// user.rewardCountedUptoDay = currentStakingDayNumberMinusOne; // different from addToTheUsersAssignedReward
return 0; // different from addToTheUsersAssignedReward
}
// ---
uint256 rewardCountedUptoDay = user.rewardCountedUptoDay;
uint256 rewardCountedUptoDayNextDay = SafeMath.add(rewardCountedUptoDay, 1);
if (!(rewardCountedUptoDayNextDay <= currentStakingDayNumberMinusOne)) {
return 0; // different from addToTheUsersAssignedReward
}
// ---
uint256 usersRewardRecently = 0;
for (uint256 i = rewardCountedUptoDayNextDay; i <= currentStakingDayNumberMinusOne; i++) {
if (dailyTotalLptAmount[i] == 0) {
continue;
}
// logic used here is because of integer division, we improve precision (not perfect solution, good enough)
// (sample use 10^4 instead of 10^19 units)
// 49.5k = users stake, 80k = total stake, 2k = daily reward)
// correct value would be = 1237.5
// (49 500 / 80 000 = 0.61875 = 0) * 2000 = 0;
// ((49 500 * 100) / 80 000 = 61,875 = 61) * 2000 = 122000) / 100 = 1220 = 1220
// ((49 500 * 1000) / 80 000 = 618,75 = 618) * 2000 = 1236000) / 1000 = 1236 = 1236
// ((49 500 * 10000) / 80 000 = 6187.5 = 6187) * 2000 = 12374000) / 10000 = 1237.4 = 1237
uint256 raiser = 10000000000000000000; // 10^19
// uint256 rew = (((user.lptAmount.mul(raiser)).div(dailyTotalLptAmount[i])).mul(dailyPlannedErc20RewardAmounts[i])).div(raiser);
// with SafeMath:
uint256 rew = SafeMath.mul(user.lptAmount, raiser);
rew = SafeMath.div(rew, dailyTotalLptAmount[i]);
rew = SafeMath.mul(rew, dailyPlannedErc20RewardAmounts[i]);
rew = SafeMath.div(rew, raiser);
if (dailyErc20RewardAmounts[i] < rew) {
// the has to be added amount is less, than the remaining (global), can happen because of slight rounding issues at the very end
// not really... more likely the oposite (that some small residue gets left behind)
rew = dailyErc20RewardAmounts[i];
}
usersRewardRecently = SafeMath.add(usersRewardRecently, rew);
// dailyErc20RewardAmounts[i] = SafeMath.sub(dailyErc20RewardAmounts[i], rew); // different from addToTheUsersAssignedReward
}
// different from addToTheUsersAssignedReward
// user.currentlyAssignedRewardAmount = SafeMath.add(user.currentlyAssignedRewardAmount, usersRewardRecently);
// currentTotalErc20RewardAmount = SafeMath.sub(currentTotalErc20RewardAmount, usersRewardRecently);
// user.rewardCountedUptoDay = currentStakingDayNumberMinusOne;
// ---
// ---
// ---
return usersRewardRecently;
}
// user.currentlyAssignedRewardAmount + calculateUsersAssignableReward()
// (read only, does not save/alter state)
function calculateCurrentTakeableRewardOfTheUser() public view returns(uint256) {
UserInfo storage user = userInfo[msg.sender];
return SafeMath.add(user.currentlyAssignedRewardAmount, calculateUsersAssignableReward());
}
// Current clearly accumulated and assigned RNB reward of the user (depositor), meaning what is already in UserInfo
function assignedRewardOfTheUser() public view returns(uint256) {
UserInfo storage user = userInfo[msg.sender];
return user.currentlyAssignedRewardAmount;
}
function rewardCountedUptoDayOfTheUser() public view returns(uint256) {
UserInfo storage user = userInfo[msg.sender];
return user.rewardCountedUptoDay;
}
/* -------------------------------------------------------------------- */
/* --- other read operations for the depositors ----------------------- */
/* -------------------------------------------------------------------- */
// Current Uniswap V2 liquidity token amount of the user (depositor)
function depositedLptOfTheUser() public view returns(uint256) {
UserInfo storage user = userInfo[msg.sender];
return user.lptAmount;
}
/* -------------------------------------------------------------------- */
/* --- write operations for the contract owner ------------------------ */
/* -------------------------------------------------------------------- */
// Fund rewards (erc20 RNB) (operation is for Rentible admins)
function fund(uint256 _fundErc20Amount) public onlyOwner {
require(_fundErc20Amount > 0, "fund: _fundErc20Amount must be positive");
require(fundedErc20RewardAmount < totalErc20RewardAmount, "fund: already fully funded");
require(SafeMath.add(fundedErc20RewardAmount, _fundErc20Amount) <= totalErc20RewardAmount, "fund: _fundErc20Amount too big, sum would exceed totalErc20RewardAmount");
// we do not check time here, optionally reward funding can be provided any time
// (in pratice it should happen before start, or very quickly)
erc20.safeTransferFrom(address(msg.sender), address(this), _fundErc20Amount);
fundedErc20RewardAmount = SafeMath.add(fundedErc20RewardAmount, _fundErc20Amount);
currentTotalErc20RewardAmount = SafeMath.add(currentTotalErc20RewardAmount, _fundErc20Amount);
emit Fund(msg.sender, _fundErc20Amount);
}
/* -------------------------------------------------------------------- */
/* --- misc utils ----------------------------------------------------- */
/* -------------------------------------------------------------------- */
function getCurrentStakingDayNumber() public view returns(uint256) {
uint256 elapsedTime = block.timestamp.sub(startTime);
uint256 dayNumber = SafeMath.div(elapsedTime, dayLength); // integer division, truncated
if (dayNumber > 92) {
return 92;
}
return dayNumber;
}
}
|
this way it can be immutable
|
dayLength = dayLengthT;
| 917,523 |
[
1,
2211,
4031,
518,
848,
506,
11732,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
3639,
2548,
1782,
273,
2548,
1782,
56,
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
] |
./full_match/1/0xf6fc9f12092DE4579370F17516f09e2235e43b89/sources/contracts/importManager/main.sol
|
call flashloan fallback function on avoSafe to execute import
|
IAvoWallet(msg.sender).executeOperation(new address[](0), new uint256[](0), new uint256[](0), msg.sender, importParams_.data);
| 4,849,050 |
[
1,
1991,
9563,
383,
304,
5922,
445,
603,
1712,
83,
9890,
358,
1836,
1930,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5411,
467,
3769,
83,
16936,
12,
3576,
18,
15330,
2934,
8837,
2988,
12,
2704,
1758,
8526,
12,
20,
3631,
394,
2254,
5034,
8526,
12,
20,
3631,
394,
2254,
5034,
8526,
12,
20,
3631,
1234,
18,
15330,
16,
1930,
1370,
27799,
892,
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
] |
pragma solidity ^0.4.0;
/**
* @title Eliptic curve signature operations
* @dev Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d.
*/
library ECRecovery {
/*
* Internal functions
*/
/**
* @dev Recover signer address from a message by using their signature.
* @param _hash Hash of the signed message
* @param _sig Signature over the signed message.
* @return Address that signed the hash.
*/
function recover(bytes32 _hash, bytes _sig) internal pure returns (address) {
bytes32 r;
bytes32 s;
uint8 v;
// Check the signature length.
if (_sig.length != 65) {
revert("Invalid signature length.");
}
// Divide the signature in v, r, and s variables.
assembly {
r := mload(add(_sig, 32))
s := mload(add(_sig, 64))
v := byte(0, mload(add(_sig, 96)))
}
// Version of signature should be 27 or 28, but 0 and 1 are also possible versions.
if (v < 27) {
v += 27;
}
// If the version is correct return the signer address.
if (v != 27 && v != 28) {
revert("Invalid signature version.");
} else {
return ecrecover(_hash, v, r, s);
}
}
}
|
* @title Eliptic curve signature operations/
|
library ECRecovery {
function recover(bytes32 _hash, bytes _sig) internal pure returns (address) {
bytes32 r;
bytes32 s;
uint8 v;
if (_sig.length != 65) {
revert("Invalid signature length.");
}
assembly {
r := mload(add(_sig, 32))
s := mload(add(_sig, 64))
v := byte(0, mload(add(_sig, 96)))
}
if (v < 27) {
v += 27;
}
if (v != 27 && v != 28) {
revert("Invalid signature version.");
return ecrecover(_hash, v, r, s);
}
}
function recover(bytes32 _hash, bytes _sig) internal pure returns (address) {
bytes32 r;
bytes32 s;
uint8 v;
if (_sig.length != 65) {
revert("Invalid signature length.");
}
assembly {
r := mload(add(_sig, 32))
s := mload(add(_sig, 64))
v := byte(0, mload(add(_sig, 96)))
}
if (v < 27) {
v += 27;
}
if (v != 27 && v != 28) {
revert("Invalid signature version.");
return ecrecover(_hash, v, r, s);
}
}
function recover(bytes32 _hash, bytes _sig) internal pure returns (address) {
bytes32 r;
bytes32 s;
uint8 v;
if (_sig.length != 65) {
revert("Invalid signature length.");
}
assembly {
r := mload(add(_sig, 32))
s := mload(add(_sig, 64))
v := byte(0, mload(add(_sig, 96)))
}
if (v < 27) {
v += 27;
}
if (v != 27 && v != 28) {
revert("Invalid signature version.");
return ecrecover(_hash, v, r, s);
}
}
function recover(bytes32 _hash, bytes _sig) internal pure returns (address) {
bytes32 r;
bytes32 s;
uint8 v;
if (_sig.length != 65) {
revert("Invalid signature length.");
}
assembly {
r := mload(add(_sig, 32))
s := mload(add(_sig, 64))
v := byte(0, mload(add(_sig, 96)))
}
if (v < 27) {
v += 27;
}
if (v != 27 && v != 28) {
revert("Invalid signature version.");
return ecrecover(_hash, v, r, s);
}
}
function recover(bytes32 _hash, bytes _sig) internal pure returns (address) {
bytes32 r;
bytes32 s;
uint8 v;
if (_sig.length != 65) {
revert("Invalid signature length.");
}
assembly {
r := mload(add(_sig, 32))
s := mload(add(_sig, 64))
v := byte(0, mload(add(_sig, 96)))
}
if (v < 27) {
v += 27;
}
if (v != 27 && v != 28) {
revert("Invalid signature version.");
return ecrecover(_hash, v, r, s);
}
}
} else {
}
| 5,547,028 |
[
1,
41,
549,
21507,
8882,
3372,
5295,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
12083,
7773,
11548,
288,
203,
203,
565,
445,
5910,
12,
3890,
1578,
389,
2816,
16,
1731,
389,
7340,
13,
2713,
16618,
1135,
261,
2867,
13,
288,
203,
3639,
1731,
1578,
436,
31,
203,
3639,
1731,
1578,
272,
31,
203,
3639,
2254,
28,
331,
31,
203,
203,
3639,
309,
261,
67,
7340,
18,
2469,
480,
15892,
13,
288,
203,
5411,
15226,
2932,
1941,
3372,
769,
1199,
1769,
203,
3639,
289,
203,
203,
3639,
19931,
288,
203,
5411,
436,
519,
312,
945,
12,
1289,
24899,
7340,
16,
3847,
3719,
203,
5411,
272,
519,
312,
945,
12,
1289,
24899,
7340,
16,
5178,
3719,
203,
5411,
331,
519,
1160,
12,
20,
16,
312,
945,
12,
1289,
24899,
7340,
16,
19332,
20349,
203,
3639,
289,
203,
203,
3639,
309,
261,
90,
411,
12732,
13,
288,
203,
5411,
331,
1011,
12732,
31,
203,
3639,
289,
203,
203,
3639,
309,
261,
90,
480,
12732,
597,
331,
480,
9131,
13,
288,
203,
5411,
15226,
2932,
1941,
3372,
1177,
1199,
1769,
203,
5411,
327,
425,
1793,
3165,
24899,
2816,
16,
331,
16,
436,
16,
272,
1769,
203,
3639,
289,
203,
565,
289,
203,
565,
445,
5910,
12,
3890,
1578,
389,
2816,
16,
1731,
389,
7340,
13,
2713,
16618,
1135,
261,
2867,
13,
288,
203,
3639,
1731,
1578,
436,
31,
203,
3639,
1731,
1578,
272,
31,
203,
3639,
2254,
28,
331,
31,
203,
203,
3639,
309,
261,
67,
7340,
18,
2469,
480,
15892,
13,
288,
203,
5411,
15226,
2932,
1941,
3372,
769,
1199,
1769,
203,
3639,
289,
203,
203,
3639,
19931,
288,
203,
5411,
2
] |
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "./SnapshotDelegatorPCVDeposit.sol";
import "./utils/VoteEscrowTokenManager.sol";
import "./utils/LiquidityGaugeManager.sol";
import "./utils/OZGovernorVoter.sol";
/// @title ANGLE Token PCV Deposit
/// @author Fei Protocol
contract AngleDelegatorPCVDeposit is SnapshotDelegatorPCVDeposit, VoteEscrowTokenManager, LiquidityGaugeManager, OZGovernorVoter {
address private constant ANGLE_TOKEN = 0x31429d1856aD1377A8A0079410B297e1a9e214c2;
address private constant ANGLE_VE_TOKEN = 0x0C462Dbb9EC8cD1630f1728B2CFD2769d09f0dd5;
address private constant ANGLE_GAUGE_MANAGER = 0x9aD7e7b0877582E14c17702EecF49018DD6f2367;
bytes32 private constant ANGLE_SNAPSHOT_SPACE = keccak256("anglegovernance.eth");
/// @notice ANGLE token manager
/// @param _core Fei Core for reference
/// @param _initialDelegate initial delegate for snapshot votes
constructor(
address _core,
address _initialDelegate
) SnapshotDelegatorPCVDeposit(
_core,
IERC20(ANGLE_TOKEN), // token used in reporting
ANGLE_SNAPSHOT_SPACE, // snapshot spaceId
_initialDelegate
) VoteEscrowTokenManager(
IERC20(ANGLE_TOKEN), // liquid token
IVeToken(ANGLE_VE_TOKEN), // vote-escrowed token
4 * 365 * 86400 // vote-escrow time = 4 years
) LiquidityGaugeManager(ANGLE_GAUGE_MANAGER) OZGovernorVoter() {}
/// @notice returns total balance of PCV in the Deposit
function balance() public view override returns (uint256) {
return _totalTokensManaged(); // liquid and vote-escrowed tokens
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "../core/TribeRoles.sol";
import "../pcv/PCVDeposit.sol";
interface DelegateRegistry {
function setDelegate(bytes32 id, address delegate) external;
function clearDelegate(bytes32 id) external;
function delegation(address delegator, bytes32 id) external view returns(address delegatee);
}
/// @title Snapshot Delegator PCV Deposit
/// @author Fei Protocol
contract SnapshotDelegatorPCVDeposit is PCVDeposit {
event DelegateUpdate(address indexed oldDelegate, address indexed newDelegate);
/// @notice the Gnosis delegate registry used by snapshot
DelegateRegistry public constant DELEGATE_REGISTRY = DelegateRegistry(0x469788fE6E9E9681C6ebF3bF78e7Fd26Fc015446);
/// @notice the token that is being used for snapshot
IERC20 public immutable token;
/// @notice the keccak encoded spaceId of the snapshot space
bytes32 public spaceId;
/// @notice the snapshot delegate for the deposit
address public delegate;
/// @notice Snapshot Delegator PCV Deposit constructor
/// @param _core Fei Core for reference
/// @param _token snapshot token
/// @param _spaceId the id (or ENS name) of the snapshot space
constructor(
address _core,
IERC20 _token,
bytes32 _spaceId,
address _initialDelegate
) CoreRef(_core) {
token = _token;
spaceId = _spaceId;
_delegate(_initialDelegate);
}
/// @notice withdraw tokens from the PCV allocation
/// @param amountUnderlying of tokens withdrawn
/// @param to the address to send PCV to
function withdraw(address to, uint256 amountUnderlying)
external
override
onlyPCVController
{
_withdrawERC20(address(token), to, amountUnderlying);
}
/// @notice no-op
function deposit() external override {}
/// @notice returns total balance of PCV in the Deposit
function balance() public view virtual override returns (uint256) {
return token.balanceOf(address(this));
}
/// @notice display the related token of the balance reported
function balanceReportedIn() public view override returns (address) {
return address(token);
}
/// @notice sets the snapshot space ID
function setSpaceId(bytes32 _spaceId) external onlyTribeRole(TribeRoles.METAGOVERNANCE_VOTE_ADMIN) {
spaceId = _spaceId;
}
/// @notice sets the snapshot delegate
function setDelegate(address newDelegate) external onlyTribeRole(TribeRoles.METAGOVERNANCE_VOTE_ADMIN) {
_delegate(newDelegate);
}
/// @notice clears the delegate from snapshot
function clearDelegate() external onlyTribeRole(TribeRoles.METAGOVERNANCE_VOTE_ADMIN) {
address oldDelegate = delegate;
DELEGATE_REGISTRY.clearDelegate(spaceId);
emit DelegateUpdate(oldDelegate, address(0));
}
function _delegate(address newDelegate) internal {
address oldDelegate = delegate;
DELEGATE_REGISTRY.setDelegate(spaceId, newDelegate);
delegate = newDelegate;
emit DelegateUpdate(oldDelegate, newDelegate);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
/**
@title Tribe DAO ACL Roles
@notice Holds a complete list of all roles which can be held by contracts inside Tribe DAO.
Roles are broken up into 3 categories:
* Major Roles - the most powerful roles in the Tribe DAO which should be carefully managed.
* Admin Roles - roles with management capability over critical functionality. Should only be held by automated or optimistic mechanisms
* Minor Roles - operational roles. May be held or managed by shorter optimistic timelocks or trusted multisigs.
*/
library TribeRoles {
/*///////////////////////////////////////////////////////////////
Major Roles
//////////////////////////////////////////////////////////////*/
/// @notice the ultimate role of Tribe. Controls all other roles and protocol functionality.
bytes32 internal constant GOVERNOR = keccak256("GOVERN_ROLE");
/// @notice the protector role of Tribe. Admin of pause, veto, revoke, and minor roles
bytes32 internal constant GUARDIAN = keccak256("GUARDIAN_ROLE");
/// @notice the role which can arbitrarily move PCV in any size from any contract
bytes32 internal constant PCV_CONTROLLER = keccak256("PCV_CONTROLLER_ROLE");
/// @notice can mint FEI arbitrarily
bytes32 internal constant MINTER = keccak256("MINTER_ROLE");
/*///////////////////////////////////////////////////////////////
Admin Roles
//////////////////////////////////////////////////////////////*/
/// @notice can manage the majority of Tribe protocol parameters. Sets boundaries for MINOR_PARAM_ROLE.
bytes32 internal constant PARAMETER_ADMIN = keccak256("PARAMETER_ADMIN");
/// @notice manages the Collateralization Oracle as well as other protocol oracles.
bytes32 internal constant ORACLE_ADMIN = keccak256("ORACLE_ADMIN_ROLE");
/// @notice manages TribalChief incentives and related functionality.
bytes32 internal constant TRIBAL_CHIEF_ADMIN = keccak256("TRIBAL_CHIEF_ADMIN_ROLE");
/// @notice admin of PCVGuardian
bytes32 internal constant PCV_GUARDIAN_ADMIN = keccak256("PCV_GUARDIAN_ADMIN_ROLE");
/// @notice admin of all Minor Roles
bytes32 internal constant MINOR_ROLE_ADMIN = keccak256("MINOR_ROLE_ADMIN");
/// @notice admin of the Fuse protocol
bytes32 internal constant FUSE_ADMIN = keccak256("FUSE_ADMIN");
/// @notice capable of vetoing DAO votes or optimistic timelocks
bytes32 internal constant VETO_ADMIN = keccak256("VETO_ADMIN");
/// @notice capable of setting FEI Minters within global rate limits and caps
bytes32 internal constant MINTER_ADMIN = keccak256("MINTER_ADMIN");
/// @notice manages the constituents of Optimistic Timelocks, including Proposers and Executors
bytes32 internal constant OPTIMISTIC_ADMIN = keccak256("OPTIMISTIC_ADMIN");
/// @notice manages meta-governance actions, like voting & delegating.
/// Also used to vote for gauge weights & similar liquid governance things.
bytes32 internal constant METAGOVERNANCE_VOTE_ADMIN = keccak256("METAGOVERNANCE_VOTE_ADMIN");
/// @notice allows to manage locking of vote-escrowed tokens, and staking/unstaking
/// governance tokens from a pre-defined contract in order to eventually allow voting.
/// Examples: ANGLE <> veANGLE, AAVE <> stkAAVE, CVX <> vlCVX, CRV > cvxCRV.
bytes32 internal constant METAGOVERNANCE_TOKEN_STAKING = keccak256("METAGOVERNANCE_TOKEN_STAKING");
/// @notice manages whitelisting of gauges where the protocol's tokens can be staked
bytes32 internal constant METAGOVERNANCE_GAUGE_ADMIN = keccak256("METAGOVERNANCE_GAUGE_ADMIN");
/// @notice manages staking to & unstaking from gauges of the protocol's tokens
bytes32 internal constant METAGOVERNANCE_GAUGE_STAKING = keccak256("METAGOVERNANCE_GAUGE_STAKING");
/*///////////////////////////////////////////////////////////////
Minor Roles
//////////////////////////////////////////////////////////////*/
/// @notice capable of poking existing LBP auctions to exchange tokens.
bytes32 internal constant LBP_SWAP_ROLE = keccak256("SWAP_ADMIN_ROLE");
/// @notice capable of engaging with Votium for voting incentives.
bytes32 internal constant VOTIUM_ROLE = keccak256("VOTIUM_ADMIN_ROLE");
/// @notice capable of changing parameters within non-critical ranges
bytes32 internal constant MINOR_PARAM_ROLE = keccak256("MINOR_PARAM_ROLE");
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "../refs/CoreRef.sol";
import "./IPCVDeposit.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/// @title abstract contract for withdrawing ERC-20 tokens using a PCV Controller
/// @author Fei Protocol
abstract contract PCVDeposit is IPCVDeposit, CoreRef {
using SafeERC20 for IERC20;
/// @notice withdraw ERC20 from the contract
/// @param token address of the ERC20 to send
/// @param to address destination of the ERC20
/// @param amount quantity of ERC20 to send
function withdrawERC20(
address token,
address to,
uint256 amount
) public virtual override onlyPCVController {
_withdrawERC20(token, to, amount);
}
function _withdrawERC20(
address token,
address to,
uint256 amount
) internal {
IERC20(token).safeTransfer(to, amount);
emit WithdrawERC20(msg.sender, token, to, amount);
}
/// @notice withdraw ETH from the contract
/// @param to address to send ETH
/// @param amountOut amount of ETH to send
function withdrawETH(address payable to, uint256 amountOut) external virtual override onlyPCVController {
Address.sendValue(to, amountOut);
emit WithdrawETH(msg.sender, to, amountOut);
}
function balance() public view virtual override returns(uint256);
function resistantBalanceAndFei() public view virtual override returns(uint256, uint256) {
return (balance(), 0);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "./ICoreRef.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
/// @title A Reference to Core
/// @author Fei Protocol
/// @notice defines some modifiers and utilities around interacting with Core
abstract contract CoreRef is ICoreRef, Pausable {
ICore private immutable _core;
IFei private immutable _fei;
IERC20 private immutable _tribe;
/// @notice a role used with a subset of governor permissions for this contract only
bytes32 public override CONTRACT_ADMIN_ROLE;
constructor(address coreAddress) {
_core = ICore(coreAddress);
_fei = ICore(coreAddress).fei();
_tribe = ICore(coreAddress).tribe();
_setContractAdminRole(ICore(coreAddress).GOVERN_ROLE());
}
function _initialize(address) internal {} // no-op for backward compatibility
modifier ifMinterSelf() {
if (_core.isMinter(address(this))) {
_;
}
}
modifier onlyMinter() {
require(_core.isMinter(msg.sender), "CoreRef: Caller is not a minter");
_;
}
modifier onlyBurner() {
require(_core.isBurner(msg.sender), "CoreRef: Caller is not a burner");
_;
}
modifier onlyPCVController() {
require(
_core.isPCVController(msg.sender),
"CoreRef: Caller is not a PCV controller"
);
_;
}
modifier onlyGovernorOrAdmin() {
require(
_core.isGovernor(msg.sender) ||
isContractAdmin(msg.sender),
"CoreRef: Caller is not a governor or contract admin"
);
_;
}
modifier onlyGovernor() {
require(
_core.isGovernor(msg.sender),
"CoreRef: Caller is not a governor"
);
_;
}
modifier onlyGuardianOrGovernor() {
require(
_core.isGovernor(msg.sender) ||
_core.isGuardian(msg.sender),
"CoreRef: Caller is not a guardian or governor"
);
_;
}
modifier isGovernorOrGuardianOrAdmin() {
require(
_core.isGovernor(msg.sender) ||
_core.isGuardian(msg.sender) ||
isContractAdmin(msg.sender),
"CoreRef: Caller is not governor or guardian or admin");
_;
}
// Named onlyTribeRole to prevent collision with OZ onlyRole modifier
modifier onlyTribeRole(bytes32 role) {
require(_core.hasRole(role, msg.sender), "UNAUTHORIZED");
_;
}
// Modifiers to allow any combination of roles
modifier hasAnyOfTwoRoles(bytes32 role1, bytes32 role2) {
require(_core.hasRole(role1, msg.sender) || _core.hasRole(role2, msg.sender), "UNAUTHORIZED");
_;
}
modifier hasAnyOfThreeRoles(bytes32 role1, bytes32 role2, bytes32 role3) {
require(_core.hasRole(role1, msg.sender) || _core.hasRole(role2, msg.sender) || _core.hasRole(role3, msg.sender), "UNAUTHORIZED");
_;
}
modifier hasAnyOfFourRoles(bytes32 role1, bytes32 role2, bytes32 role3, bytes32 role4) {
require(_core.hasRole(role1, msg.sender) || _core.hasRole(role2, msg.sender) || _core.hasRole(role3, msg.sender) || _core.hasRole(role4, msg.sender), "UNAUTHORIZED");
_;
}
modifier hasAnyOfFiveRoles(bytes32 role1, bytes32 role2, bytes32 role3, bytes32 role4, bytes32 role5) {
require(_core.hasRole(role1, msg.sender) || _core.hasRole(role2, msg.sender) || _core.hasRole(role3, msg.sender) || _core.hasRole(role4, msg.sender) || _core.hasRole(role5, msg.sender), "UNAUTHORIZED");
_;
}
modifier onlyFei() {
require(msg.sender == address(_fei), "CoreRef: Caller is not FEI");
_;
}
/// @notice sets a new admin role for this contract
function setContractAdminRole(bytes32 newContractAdminRole) external override onlyGovernor {
_setContractAdminRole(newContractAdminRole);
}
/// @notice returns whether a given address has the admin role for this contract
function isContractAdmin(address _admin) public view override returns (bool) {
return _core.hasRole(CONTRACT_ADMIN_ROLE, _admin);
}
/// @notice set pausable methods to paused
function pause() public override onlyGuardianOrGovernor {
_pause();
}
/// @notice set pausable methods to unpaused
function unpause() public override onlyGuardianOrGovernor {
_unpause();
}
/// @notice address of the Core contract referenced
/// @return ICore implementation address
function core() public view override returns (ICore) {
return _core;
}
/// @notice address of the Fei contract referenced by Core
/// @return IFei implementation address
function fei() public view override returns (IFei) {
return _fei;
}
/// @notice address of the Tribe contract referenced by Core
/// @return IERC20 implementation address
function tribe() public view override returns (IERC20) {
return _tribe;
}
/// @notice fei balance of contract
/// @return fei amount held
function feiBalance() public view override returns (uint256) {
return _fei.balanceOf(address(this));
}
/// @notice tribe balance of contract
/// @return tribe amount held
function tribeBalance() public view override returns (uint256) {
return _tribe.balanceOf(address(this));
}
function _burnFeiHeld() internal {
_fei.burn(feiBalance());
}
function _mintFei(address to, uint256 amount) internal virtual {
if (amount != 0) {
_fei.mint(to, amount);
}
}
function _setContractAdminRole(bytes32 newContractAdminRole) internal {
bytes32 oldContractAdminRole = CONTRACT_ADMIN_ROLE;
CONTRACT_ADMIN_ROLE = newContractAdminRole;
emit ContractAdminRoleUpdate(oldContractAdminRole, newContractAdminRole);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "../core/ICore.sol";
/// @title CoreRef interface
/// @author Fei Protocol
interface ICoreRef {
// ----------- Events -----------
event CoreUpdate(address indexed oldCore, address indexed newCore);
event ContractAdminRoleUpdate(bytes32 indexed oldContractAdminRole, bytes32 indexed newContractAdminRole);
// ----------- Governor only state changing api -----------
function setContractAdminRole(bytes32 newContractAdminRole) external;
// ----------- Governor or Guardian only state changing api -----------
function pause() external;
function unpause() external;
// ----------- Getters -----------
function core() external view returns (ICore);
function fei() external view returns (IFei);
function tribe() external view returns (IERC20);
function feiBalance() external view returns (uint256);
function tribeBalance() external view returns (uint256);
function CONTRACT_ADMIN_ROLE() external view returns (bytes32);
function isContractAdmin(address admin) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "./IPermissions.sol";
import "../fei/IFei.sol";
/// @title Core Interface
/// @author Fei Protocol
interface ICore is IPermissions {
// ----------- Events -----------
event FeiUpdate(address indexed _fei);
event TribeUpdate(address indexed _tribe);
event GenesisGroupUpdate(address indexed _genesisGroup);
event TribeAllocation(address indexed _to, uint256 _amount);
event GenesisPeriodComplete(uint256 _timestamp);
// ----------- Governor only state changing api -----------
function init() external;
// ----------- Governor only state changing api -----------
function setFei(address token) external;
function setTribe(address token) external;
function allocateTribe(address to, uint256 amount) external;
// ----------- Getters -----------
function fei() external view returns (IFei);
function tribe() external view returns (IERC20);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "./IPermissionsRead.sol";
/// @title Permissions interface
/// @author Fei Protocol
interface IPermissions is IAccessControl, IPermissionsRead {
// ----------- Governor only state changing api -----------
function createRole(bytes32 role, bytes32 adminRole) external;
function grantMinter(address minter) external;
function grantBurner(address burner) external;
function grantPCVController(address pcvController) external;
function grantGovernor(address governor) external;
function grantGuardian(address guardian) external;
function revokeMinter(address minter) external;
function revokeBurner(address burner) external;
function revokePCVController(address pcvController) external;
function revokeGovernor(address governor) external;
function revokeGuardian(address guardian) external;
// ----------- Revoker only state changing api -----------
function revokeOverride(bytes32 role, address account) external;
// ----------- Getters -----------
function GUARDIAN_ROLE() external view returns (bytes32);
function GOVERN_ROLE() external view returns (bytes32);
function BURNER_ROLE() external view returns (bytes32);
function MINTER_ROLE() external view returns (bytes32);
function PCV_CONTROLLER_ROLE() external view returns (bytes32);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
/// @title Permissions Read interface
/// @author Fei Protocol
interface IPermissionsRead {
// ----------- Getters -----------
function isBurner(address _address) external view returns (bool);
function isMinter(address _address) external view returns (bool);
function isGovernor(address _address) external view returns (bool);
function isGuardian(address _address) external view returns (bool);
function isPCVController(address _address) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title FEI stablecoin interface
/// @author Fei Protocol
interface IFei is IERC20 {
// ----------- Events -----------
event Minting(
address indexed _to,
address indexed _minter,
uint256 _amount
);
event Burning(
address indexed _to,
address indexed _burner,
uint256 _amount
);
event IncentiveContractUpdate(
address indexed _incentivized,
address indexed _incentiveContract
);
// ----------- State changing api -----------
function burn(uint256 amount) external;
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
// ----------- Burner only state changing api -----------
function burnFrom(address account, uint256 amount) external;
// ----------- Minter only state changing api -----------
function mint(address account, uint256 amount) external;
// ----------- Governor only state changing api -----------
function setIncentiveContract(address account, address incentive) external;
// ----------- Getters -----------
function incentiveContract(address account) external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "./IPCVDepositBalances.sol";
/// @title a PCV Deposit interface
/// @author Fei Protocol
interface IPCVDeposit is IPCVDepositBalances {
// ----------- Events -----------
event Deposit(address indexed _from, uint256 _amount);
event Withdrawal(
address indexed _caller,
address indexed _to,
uint256 _amount
);
event WithdrawERC20(
address indexed _caller,
address indexed _token,
address indexed _to,
uint256 _amount
);
event WithdrawETH(
address indexed _caller,
address indexed _to,
uint256 _amount
);
// ----------- State changing api -----------
function deposit() external;
// ----------- PCV Controller only state changing api -----------
function withdraw(address to, uint256 amount) external;
function withdrawERC20(address token, address to, uint256 amount) external;
function withdrawETH(address payable to, uint256 amount) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
/// @title a PCV Deposit interface for only balance getters
/// @author Fei Protocol
interface IPCVDepositBalances {
// ----------- Getters -----------
/// @notice gets the effective balance of "balanceReportedIn" token if the deposit were fully withdrawn
function balance() external view returns (uint256);
/// @notice gets the token address in which this deposit returns its balance
function balanceReportedIn() external view returns (address);
/// @notice gets the resistant token balance and protocol owned fei of this deposit
function resistantBalanceAndFei() external view returns (uint256, uint256);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "../../refs/CoreRef.sol";
import "../../core/TribeRoles.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IVeToken {
function balanceOf(address) external view returns (uint256);
function locked(address) external view returns (uint256);
function create_lock(uint256 value, uint256 unlock_time) external;
function increase_amount(uint256 value) external;
function increase_unlock_time(uint256 unlock_time) external;
function withdraw() external;
function locked__end(address) external view returns (uint256);
function checkpoint() external;
}
/// @title Vote-escrowed Token Manager
/// Used to permanently lock tokens in a vote-escrow contract, and refresh
/// the lock duration as needed.
/// @author Fei Protocol
abstract contract VoteEscrowTokenManager is CoreRef {
// Events
event Lock(uint256 cummulativeTokensLocked, uint256 lockHorizon);
event Unlock(uint256 tokensUnlocked);
/// @notice One week, in seconds. Vote-locking is rounded down to weeks.
uint256 private constant WEEK = 7 * 86400; // 1 week, in seconds
/// @notice The lock duration of veTokens
uint256 public lockDuration;
/// @notice The vote-escrowed token address
IVeToken public immutable veToken;
/// @notice The token address
IERC20 public immutable liquidToken;
/// @notice VoteEscrowTokenManager token Snapshot Delegator PCV Deposit constructor
/// @param _liquidToken the token to lock for vote-escrow
/// @param _veToken the vote-escrowed token used in governance
/// @param _lockDuration amount of time (in seconds) tokens will be vote-escrowed for
constructor(
IERC20 _liquidToken,
IVeToken _veToken,
uint256 _lockDuration
) {
liquidToken = _liquidToken;
veToken = _veToken;
lockDuration = _lockDuration;
}
/// @notice Set the amount of time tokens will be vote-escrowed for in lock() calls
function setLockDuration(uint256 newLockDuration) external onlyTribeRole(TribeRoles.METAGOVERNANCE_TOKEN_STAKING) {
lockDuration = newLockDuration;
}
/// @notice Deposit tokens to get veTokens. Set lock duration to lockDuration.
/// The only way to withdraw tokens will be to pause this contract
/// for lockDuration and then call exitLock().
function lock() external whenNotPaused onlyTribeRole(TribeRoles.METAGOVERNANCE_TOKEN_STAKING) {
uint256 tokenBalance = liquidToken.balanceOf(address(this));
uint256 locked = veToken.locked(address(this));
uint256 lockHorizon = ((block.timestamp + lockDuration) / WEEK) * WEEK;
// First lock
if (tokenBalance != 0 && locked == 0) {
liquidToken.approve(address(veToken), tokenBalance);
veToken.create_lock(tokenBalance, lockHorizon);
}
// Increase amount of tokens locked & refresh duration to lockDuration
else if (tokenBalance != 0 && locked != 0) {
liquidToken.approve(address(veToken), tokenBalance);
veToken.increase_amount(tokenBalance);
if (veToken.locked__end(address(this)) != lockHorizon) {
veToken.increase_unlock_time(lockHorizon);
}
}
// No additional tokens to lock, just refresh duration to lockDuration
else if (tokenBalance == 0 && locked != 0) {
veToken.increase_unlock_time(lockHorizon);
}
// If tokenBalance == 0 and locked == 0, there is nothing to do.
emit Lock(tokenBalance + locked, lockHorizon);
}
/// @notice Exit the veToken lock. For this function to be called and not
/// revert, tokens had to be locked previously, and the contract must have
/// been paused for lockDuration in order to prevent lock extensions
/// by calling lock(). This function will recover tokens on the contract,
/// which can then be moved by calling withdraw() as a PCVController if the
/// contract is also a PCVDeposit, for instance.
function exitLock() external onlyTribeRole(TribeRoles.METAGOVERNANCE_TOKEN_STAKING) {
veToken.withdraw();
emit Unlock(liquidToken.balanceOf(address(this)));
}
/// @notice returns total balance of tokens, vote-escrowed or liquid.
function _totalTokensManaged() internal view returns (uint256) {
return liquidToken.balanceOf(address(this)) + veToken.locked(address(this));
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "../../refs/CoreRef.sol";
import "../../core/TribeRoles.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface ILiquidityGauge {
function deposit(uint256 value) external;
function withdraw(uint256 value, bool claim_rewards) external;
function claim_rewards() external;
function balanceOf(address) external view returns(uint256);
function staking_token() external view returns(address);
function reward_tokens(uint256 i) external view returns (address token);
function reward_count() external view returns (uint256 nTokens);
}
interface ILiquidityGaugeController {
function vote_for_gauge_weights(address gauge_addr, uint256 user_weight) external;
function last_user_vote(address user, address gauge) external view returns(uint256);
function vote_user_power(address user) external view returns(uint256);
function gauge_types(address gauge) external view returns(int128);
}
/// @title Liquidity gauge manager, used to stake tokens in liquidity gauges.
/// @author Fei Protocol
abstract contract LiquidityGaugeManager is CoreRef {
// Events
event GaugeControllerChanged(address indexed oldController, address indexed newController);
event GaugeSetForToken(address indexed token, address indexed gauge);
event GaugeVote(address indexed gauge, uint256 amount);
event GaugeStake(address indexed gauge, uint256 amount);
event GaugeUnstake(address indexed gauge, uint256 amount);
event GaugeRewardsClaimed(address indexed gauge, address indexed token, uint256 amount);
/// @notice address of the gauge controller used for voting
address public gaugeController;
/// @notice mapping of token staked to gauge address
mapping(address=>address) public tokenToGauge;
constructor(address _gaugeController) {
gaugeController = _gaugeController;
}
/// @notice Set the gauge controller used for gauge weight voting
/// @param _gaugeController the gauge controller address
function setGaugeController(address _gaugeController) public onlyTribeRole(TribeRoles.METAGOVERNANCE_GAUGE_ADMIN) {
require(gaugeController != _gaugeController, "LiquidityGaugeManager: same controller");
address oldController = gaugeController;
gaugeController = _gaugeController;
emit GaugeControllerChanged(oldController, gaugeController);
}
/// @notice Set gauge for a given token.
/// @param token the token address to stake in gauge
/// @param gaugeAddress the address of the gauge where to stake token
function setTokenToGauge(
address token,
address gaugeAddress
) public onlyTribeRole(TribeRoles.METAGOVERNANCE_GAUGE_ADMIN) {
require(ILiquidityGauge(gaugeAddress).staking_token() == token, "LiquidityGaugeManager: wrong gauge for token");
require(ILiquidityGaugeController(gaugeController).gauge_types(gaugeAddress) >= 0, "LiquidityGaugeManager: wrong gauge address");
tokenToGauge[token] = gaugeAddress;
emit GaugeSetForToken(token, gaugeAddress);
}
/// @notice Vote for a gauge's weight
/// @param token the address of the token to vote for
/// @param gaugeWeight the weight of gaugeAddress in basis points [0, 10_000]
function voteForGaugeWeight(
address token,
uint256 gaugeWeight
) public whenNotPaused onlyTribeRole(TribeRoles.METAGOVERNANCE_VOTE_ADMIN) {
address gaugeAddress = tokenToGauge[token];
require(gaugeAddress != address(0), "LiquidityGaugeManager: token has no gauge configured");
ILiquidityGaugeController(gaugeController).vote_for_gauge_weights(gaugeAddress, gaugeWeight);
emit GaugeVote(gaugeAddress, gaugeWeight);
}
/// @notice Stake tokens in a gauge
/// @param token the address of the token to stake in the gauge
/// @param amount the amount of tokens to stake in the gauge
function stakeInGauge(
address token,
uint256 amount
) public whenNotPaused onlyTribeRole(TribeRoles.METAGOVERNANCE_GAUGE_ADMIN) {
address gaugeAddress = tokenToGauge[token];
require(gaugeAddress != address(0), "LiquidityGaugeManager: token has no gauge configured");
IERC20(token).approve(gaugeAddress, amount);
ILiquidityGauge(gaugeAddress).deposit(amount);
emit GaugeStake(gaugeAddress, amount);
}
/// @notice Stake all tokens held in a gauge
/// @param token the address of the token to stake in the gauge
function stakeAllInGauge(address token) public whenNotPaused onlyTribeRole(TribeRoles.METAGOVERNANCE_GAUGE_ADMIN) {
address gaugeAddress = tokenToGauge[token];
require(gaugeAddress != address(0), "LiquidityGaugeManager: token has no gauge configured");
uint256 amount = IERC20(token).balanceOf(address(this));
IERC20(token).approve(gaugeAddress, amount);
ILiquidityGauge(gaugeAddress).deposit(amount);
emit GaugeStake(gaugeAddress, amount);
}
/// @notice Unstake tokens from a gauge
/// @param token the address of the token to unstake from the gauge
/// @param amount the amount of tokens to unstake from the gauge
function unstakeFromGauge(
address token,
uint256 amount
) public whenNotPaused onlyTribeRole(TribeRoles.METAGOVERNANCE_GAUGE_ADMIN) {
address gaugeAddress = tokenToGauge[token];
require(gaugeAddress != address(0), "LiquidityGaugeManager: token has no gauge configured");
ILiquidityGauge(gaugeAddress).withdraw(amount, false);
emit GaugeUnstake(gaugeAddress, amount);
}
/// @notice Claim rewards associated to a gauge where this contract stakes
/// tokens.
function claimGaugeRewards(address gaugeAddress) public whenNotPaused {
uint256 nTokens = ILiquidityGauge(gaugeAddress).reward_count();
address[] memory tokens = new address[](nTokens);
uint256[] memory amounts = new uint256[](nTokens);
for (uint256 i = 0; i < nTokens; i++) {
tokens[i] = ILiquidityGauge(gaugeAddress).reward_tokens(i);
amounts[i] = IERC20(tokens[i]).balanceOf(address(this));
}
ILiquidityGauge(gaugeAddress).claim_rewards();
for (uint256 i = 0; i < nTokens; i++) {
amounts[i] = IERC20(tokens[i]).balanceOf(address(this)) - amounts[i];
emit GaugeRewardsClaimed(gaugeAddress, tokens[i], amounts[i]);
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "../../refs/CoreRef.sol";
import "../../core/TribeRoles.sol";
interface IOZGovernor {
function propose(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
string memory description
) external returns (uint256 proposalId);
function castVote(uint256 proposalId, uint8 support) external returns (uint256 weight);
function state(uint256 proposalId) external view returns (uint256);
}
/// @title Abstract class to interact with an OZ governor.
/// @author Fei Protocol
abstract contract OZGovernorVoter is CoreRef {
// Events
event Proposed(IOZGovernor indexed governor, uint256 proposalId);
event Voted(IOZGovernor indexed governor, uint256 proposalId, uint256 weight, uint8 support);
/// @notice propose a new proposal on the target governor.
function propose(
IOZGovernor governor,
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
string memory description
) external onlyTribeRole(TribeRoles.METAGOVERNANCE_VOTE_ADMIN) returns (uint256) {
uint256 proposalId = governor.propose(targets, values, calldatas, description);
emit Proposed(governor, proposalId);
return proposalId;
}
/// @notice cast a vote on a given proposal on the target governor.
function castVote(
IOZGovernor governor,
uint256 proposalId,
uint8 support
) external onlyTribeRole(TribeRoles.METAGOVERNANCE_VOTE_ADMIN) returns (uint256) {
uint256 weight = governor.castVote(proposalId, support);
emit Voted(governor, proposalId, weight, support);
return weight;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.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);
}
// 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 Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
|
Major Roles - the most powerful roles in the Tribe DAO which should be carefully managed. Admin Roles - roles with management capability over critical functionality. Should only be held by automated or optimistic mechanisms Minor Roles - operational roles. May be held or managed by shorter optimistic timelocks or trusted multisigs./
|
library TribeRoles {
Major Roles
bytes32 internal constant GOVERNOR = keccak256("GOVERN_ROLE");
bytes32 internal constant GUARDIAN = keccak256("GUARDIAN_ROLE");
bytes32 internal constant PCV_CONTROLLER = keccak256("PCV_CONTROLLER_ROLE");
bytes32 internal constant MINTER = keccak256("MINTER_ROLE");
Admin Roles
bytes32 internal constant PARAMETER_ADMIN = keccak256("PARAMETER_ADMIN");
bytes32 internal constant ORACLE_ADMIN = keccak256("ORACLE_ADMIN_ROLE");
bytes32 internal constant TRIBAL_CHIEF_ADMIN = keccak256("TRIBAL_CHIEF_ADMIN_ROLE");
bytes32 internal constant PCV_GUARDIAN_ADMIN = keccak256("PCV_GUARDIAN_ADMIN_ROLE");
bytes32 internal constant MINOR_ROLE_ADMIN = keccak256("MINOR_ROLE_ADMIN");
bytes32 internal constant FUSE_ADMIN = keccak256("FUSE_ADMIN");
bytes32 internal constant VETO_ADMIN = keccak256("VETO_ADMIN");
bytes32 internal constant MINTER_ADMIN = keccak256("MINTER_ADMIN");
bytes32 internal constant OPTIMISTIC_ADMIN = keccak256("OPTIMISTIC_ADMIN");
bytes32 internal constant METAGOVERNANCE_VOTE_ADMIN = keccak256("METAGOVERNANCE_VOTE_ADMIN");
bytes32 internal constant METAGOVERNANCE_TOKEN_STAKING = keccak256("METAGOVERNANCE_TOKEN_STAKING");
bytes32 internal constant METAGOVERNANCE_GAUGE_ADMIN = keccak256("METAGOVERNANCE_GAUGE_ADMIN");
bytes32 internal constant METAGOVERNANCE_GAUGE_STAKING = keccak256("METAGOVERNANCE_GAUGE_STAKING");
Minor Roles
bytes32 internal constant LBP_SWAP_ROLE = keccak256("SWAP_ADMIN_ROLE");
bytes32 internal constant VOTIUM_ROLE = keccak256("VOTIUM_ADMIN_ROLE");
bytes32 internal constant MINOR_PARAM_ROLE = keccak256("MINOR_PARAM_ROLE");
pragma solidity ^0.8.4;
@title Tribe DAO ACL Roles
}
| 602,816 |
[
1,
17581,
19576,
300,
326,
4486,
7212,
2706,
4900,
316,
326,
840,
495,
73,
463,
20463,
1492,
1410,
506,
7671,
4095,
7016,
18,
7807,
19576,
300,
4900,
598,
11803,
12593,
1879,
11239,
14176,
18,
9363,
1338,
506,
15770,
635,
18472,
690,
578,
5213,
5846,
1791,
28757,
29007,
19576,
300,
1674,
287,
4900,
18,
16734,
506,
15770,
578,
7016,
635,
19623,
5213,
5846,
1658,
292,
20641,
578,
13179,
22945,
360,
87,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
12083,
840,
495,
73,
6898,
288,
203,
203,
4766,
25977,
19576,
203,
203,
565,
1731,
1578,
2713,
5381,
12389,
2204,
50,
916,
273,
417,
24410,
581,
5034,
2932,
43,
12959,
50,
67,
16256,
8863,
203,
203,
565,
1731,
1578,
2713,
5381,
611,
57,
985,
2565,
1258,
273,
417,
24410,
581,
5034,
2932,
30673,
985,
2565,
1258,
67,
16256,
8863,
203,
203,
565,
1731,
1578,
2713,
5381,
453,
22007,
67,
6067,
25353,
273,
417,
24410,
581,
5034,
2932,
3513,
58,
67,
6067,
25353,
67,
16256,
8863,
203,
203,
565,
1731,
1578,
2713,
5381,
6989,
2560,
273,
417,
24410,
581,
5034,
2932,
6236,
2560,
67,
16256,
8863,
203,
203,
4766,
7807,
19576,
203,
203,
565,
1731,
1578,
2713,
5381,
18120,
67,
15468,
273,
417,
24410,
581,
5034,
2932,
9819,
67,
15468,
8863,
203,
203,
565,
1731,
1578,
2713,
5381,
4869,
2226,
900,
67,
15468,
273,
417,
24410,
581,
5034,
2932,
916,
2226,
900,
67,
15468,
67,
16256,
8863,
203,
203,
565,
1731,
1578,
2713,
5381,
22800,
38,
1013,
67,
1792,
8732,
42,
67,
15468,
273,
417,
24410,
581,
5034,
2932,
6566,
38,
1013,
67,
1792,
8732,
42,
67,
15468,
67,
16256,
8863,
203,
203,
565,
1731,
1578,
2713,
5381,
453,
22007,
67,
30673,
985,
2565,
1258,
67,
15468,
273,
417,
24410,
581,
5034,
2932,
3513,
58,
67,
30673,
985,
2565,
1258,
67,
15468,
67,
16256,
8863,
203,
203,
565,
1731,
1578,
2713,
5381,
6989,
916,
67,
16256,
67,
15468,
273,
417,
24410,
581,
5034,
2932,
6236,
916,
67,
16256,
67,
15468,
8863,
203,
203,
565,
1731,
2
] |
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.0;
import { IERC20, ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import { ICERC20 } from "../strategies/ICompound.sol";
import { StableMath } from "../utils/StableMath.sol";
contract MockCToken is ICERC20, ERC20 {
using StableMath for uint256;
IERC20 public underlyingToken;
// underlying = cToken * exchangeRate
// cToken = underlying / exchangeRate
uint256 exchangeRate;
address public override comptroller;
constructor(ERC20 _underlyingToken, address _comptroller)
ERC20("cMock", "cMK")
{
uint8 underlyingDecimals = _underlyingToken.decimals();
// if has 18 dp, exchange rate should be 1e26
// if has 8 dp, exchange rate should be 1e18
if (underlyingDecimals > 8) {
exchangeRate = 10**uint256(18 + underlyingDecimals - 10);
} else if (underlyingDecimals < 8) {
// e.g. 18-8+6 = 16
exchangeRate = 10**uint256(18 - 8 + underlyingDecimals);
} else {
exchangeRate = 1e18;
}
underlyingToken = _underlyingToken;
comptroller = _comptroller;
}
function decimals() public pure override returns (uint8) {
return 8;
}
function mint(uint256 mintAmount) public override returns (uint256) {
// Credit them with cToken
_mint(msg.sender, mintAmount.divPrecisely(exchangeRate));
// Take their reserve
underlyingToken.transferFrom(msg.sender, address(this), mintAmount);
return 0;
}
function redeem(uint256 redeemAmount) external override returns (uint256) {
uint256 tokenAmount = redeemAmount.mulTruncate(exchangeRate);
// Burn the cToken
_burn(msg.sender, redeemAmount);
// Transfer underlying to caller
underlyingToken.transfer(msg.sender, tokenAmount);
return 0;
}
function redeemUnderlying(uint256 redeemAmount)
external
override
returns (uint256)
{
uint256 cTokens = redeemAmount.divPrecisely(exchangeRate);
// Burn the cToken
_burn(msg.sender, cTokens);
// Transfer underlying to caller
underlyingToken.transfer(msg.sender, redeemAmount);
return 0;
}
function balanceOfUnderlying(address owner)
external
view
override
returns (uint256)
{
uint256 cTokenBal = this.balanceOf(owner);
return cTokenBal.mulTruncate(exchangeRate);
}
function balanceOf(address owner)
public
view
override(ICERC20, ERC20)
returns (uint256)
{
return ERC20.balanceOf(owner);
}
function updateExchangeRate()
internal
view
returns (uint256 newExchangeRate)
{
uint256 factor = 100002 * (10**13); // 0.002%
newExchangeRate = exchangeRate.mulTruncate(factor);
}
function exchangeRateStored() external view override returns (uint256) {
return exchangeRate;
}
function supplyRatePerBlock() external pure override returns (uint256) {
return 141 * (10**8);
}
}
|
Credit them with cToken Take their reserve
|
function mint(uint256 mintAmount) public override returns (uint256) {
_mint(msg.sender, mintAmount.divPrecisely(exchangeRate));
underlyingToken.transferFrom(msg.sender, address(this), mintAmount);
return 0;
}
| 1,006,276 |
[
1,
16520,
2182,
598,
276,
1345,
17129,
3675,
20501,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
312,
474,
12,
11890,
5034,
312,
474,
6275,
13,
1071,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
389,
81,
474,
12,
3576,
18,
15330,
16,
312,
474,
6275,
18,
2892,
1386,
71,
291,
2357,
12,
16641,
4727,
10019,
203,
3639,
6808,
1345,
18,
13866,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
312,
474,
6275,
1769,
203,
3639,
327,
374,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xF13e21653AEB763595D5E4baA1dC115689Da49b9/sources/contracts/core/iface/IBlockVerifier.sol
|
-- Events -- -- Public functions --
|
{
event CircuitRegistered(
uint8 indexed blockType,
uint16 blockSize,
uint8 blockVersion
);
event CircuitDisabled(
uint8 indexed blockType,
uint16 blockSize,
uint8 blockVersion
);
function verifyProofs(
uint8 blockType,
uint16 blockSize,
uint8 blockVersion,
uint[] calldata publicInputs,
uint[] calldata proofs
)
external
virtual
view
returns (bool);
function isCircuitRegistered(
uint8 blockType,
uint16 blockSize,
uint8 blockVersion
)
external
virtual
view
returns (bool);
function isCircuitEnabled(
uint8 blockType,
uint16 blockSize,
uint8 blockVersion
)
external
virtual
view
returns (bool);
pragma solidity ^0.7.0;
abstract contract IBlockVerifier is Claimable
}
| 4,025,269 |
[
1,
413,
9043,
1493,
1493,
7224,
4186,
1493,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
95,
203,
203,
565,
871,
20797,
10868,
12,
203,
3639,
2254,
28,
225,
8808,
26355,
16,
203,
3639,
2254,
2313,
540,
13766,
16,
203,
3639,
2254,
28,
1850,
1203,
1444,
203,
565,
11272,
203,
203,
565,
871,
20797,
8853,
12,
203,
3639,
2254,
28,
225,
8808,
26355,
16,
203,
3639,
2254,
2313,
540,
13766,
16,
203,
3639,
2254,
28,
1850,
1203,
1444,
203,
565,
11272,
203,
203,
203,
565,
445,
3929,
20439,
87,
12,
203,
3639,
2254,
28,
225,
26355,
16,
203,
3639,
2254,
2313,
13766,
16,
203,
3639,
2254,
28,
225,
1203,
1444,
16,
203,
3639,
2254,
8526,
745,
892,
1071,
10059,
16,
203,
3639,
2254,
8526,
745,
892,
14601,
87,
203,
3639,
262,
203,
3639,
3903,
203,
3639,
5024,
203,
3639,
1476,
203,
3639,
1135,
261,
6430,
1769,
203,
203,
565,
445,
353,
21719,
10868,
12,
203,
3639,
2254,
28,
225,
26355,
16,
203,
3639,
2254,
2313,
13766,
16,
203,
3639,
2254,
28,
225,
1203,
1444,
203,
3639,
262,
203,
3639,
3903,
203,
3639,
5024,
203,
3639,
1476,
203,
3639,
1135,
261,
6430,
1769,
203,
203,
565,
445,
353,
21719,
1526,
12,
203,
3639,
2254,
28,
225,
26355,
16,
203,
3639,
2254,
2313,
13766,
16,
203,
3639,
2254,
28,
225,
1203,
1444,
203,
3639,
262,
203,
3639,
3903,
203,
3639,
5024,
203,
3639,
1476,
203,
3639,
1135,
261,
6430,
1769,
203,
683,
9454,
18035,
560,
3602,
20,
18,
27,
18,
20,
31,
203,
17801,
6835,
467,
1768,
17758,
353,
18381,
429,
203,
97,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// Сочетаемость глаголов (и отглагольных частей речи) с предложным
// паттерном.
// LC->07.08.2018
facts гл_предл language=Russian
{
arity=3
//violation_score=-5
generic
return=boolean
}
#define ГЛ_ИНФ(v) инфинитив:v{}, глагол:v{}
#region Предлог_В
// ------------------- С ПРЕДЛОГОМ 'В' ---------------------------
#region Предложный
// Глаголы и отглагольные части речи, присоединяющие
// предложное дополнение с предлогом В и сущ. в предложном падеже.
wordentry_set Гл_В_Предл =
{
rus_verbs:взорваться{}, // В Дагестане взорвался автомобиль
// вернуть после перекомпиляции rus_verbs:подорожать{}, // В Дагестане подорожал хлеб
rus_verbs:воевать{}, // Воевал во Франции.
rus_verbs:устать{}, // Устали в дороге?
rus_verbs:изнывать{}, // В Лондоне Черчилль изнывал от нетерпения.
rus_verbs:решить{}, // Что решат в правительстве?
rus_verbs:выскакивать{}, // Один из бойцов на улицу выскакивает.
rus_verbs:обстоять{}, // В действительности же дело обстояло не так.
rus_verbs:подыматься{},
rus_verbs:поехать{}, // поедем в такси!
rus_verbs:уехать{}, // он уехал в такси
rus_verbs:прибыть{}, // они прибыли в качестве независимых наблюдателей
rus_verbs:ОБЛАЧИТЬ{},
rus_verbs:ОБЛАЧАТЬ{},
rus_verbs:ОБЛАЧИТЬСЯ{},
rus_verbs:ОБЛАЧАТЬСЯ{},
rus_verbs:НАРЯДИТЬСЯ{},
rus_verbs:НАРЯЖАТЬСЯ{},
rus_verbs:ПОВАЛЯТЬСЯ{}, // повалявшись в снегу, бежать обратно в тепло.
rus_verbs:ПОКРЫВАТЬ{}, // Во многих местах ее покрывали трещины, наросты и довольно плоские выступы. (ПОКРЫВАТЬ)
rus_verbs:ПРОЖИГАТЬ{}, // Синий луч искрился белыми пятнами и прожигал в земле дымящуюся борозду. (ПРОЖИГАТЬ)
rus_verbs:МЫЧАТЬ{}, // В огромной куче тел жалобно мычали задавленные трупами и раненые бизоны. (МЫЧАТЬ)
rus_verbs:РАЗБОЙНИЧАТЬ{}, // Эти существа обычно разбойничали в трехстах милях отсюда (РАЗБОЙНИЧАТЬ)
rus_verbs:МАЯЧИТЬ{}, // В отдалении маячили огромные серые туши мастодонтов и мамонтов с изогнутыми бивнями. (МАЯЧИТЬ/ЗАМАЯЧИТЬ)
rus_verbs:ЗАМАЯЧИТЬ{},
rus_verbs:НЕСТИСЬ{}, // Кони неслись вперед в свободном и легком галопе (НЕСТИСЬ)
rus_verbs:ДОБЫТЬ{}, // Они надеялись застать "медвежий народ" врасплох и добыть в бою голову величайшего из воинов. (ДОБЫТЬ)
rus_verbs:СПУСТИТЬ{}, // Время от времени грохот или вопль объявляли о спущенной где-то во дворце ловушке. (СПУСТИТЬ)
rus_verbs:ОБРАЗОВЫВАТЬСЯ{}, // Она сузила глаза, на лице ее стала образовываться маска безумия. (ОБРАЗОВЫВАТЬСЯ)
rus_verbs:КИШЕТЬ{}, // в этом районе кишмя кишели разбойники и драконы. (КИШЕТЬ)
rus_verbs:ДЫШАТЬ{}, // Она тяжело дышала в тисках гнева (ДЫШАТЬ)
rus_verbs:ЗАДЕВАТЬ{}, // тот задевал в нем какую-то струну (ЗАДЕВАТЬ)
rus_verbs:УСТУПИТЬ{}, // Так что теперь уступи мне в этом. (УСТУПИТЬ)
rus_verbs:ТЕРЯТЬ{}, // Хотя он хорошо питался, он терял в весе (ТЕРЯТЬ/ПОТЕРЯТЬ)
rus_verbs:ПоТЕРЯТЬ{},
rus_verbs:УТЕРЯТЬ{},
rus_verbs:РАСТЕРЯТЬ{},
rus_verbs:СМЫКАТЬСЯ{}, // Словно медленно смыкающийся во сне глаз, отверстие медленно закрывалось. (СМЫКАТЬСЯ/СОМКНУТЬСЯ, + оборот с СЛОВНО/БУДТО + вин.п.)
rus_verbs:СОМКНУТЬСЯ{},
rus_verbs:РАЗВОРОШИТЬ{}, // Вольф не узнал никаких отдельных слов, но звуки и взаимодействующая высота тонов разворошили что-то в его памяти. (РАЗВОРОШИТЬ)
rus_verbs:ПРОСТОЯТЬ{}, // Он поднялся и некоторое время простоял в задумчивости. (ПРОСТОЯТЬ,ВЫСТОЯТЬ,ПОСТОЯТЬ)
rus_verbs:ВЫСТОЯТЬ{},
rus_verbs:ПОСТОЯТЬ{},
rus_verbs:ВЗВЕСИТЬ{}, // Он поднял и взвесил в руке один из рогов изобилия. (ВЗВЕСИТЬ/ВЗВЕШИВАТЬ)
rus_verbs:ВЗВЕШИВАТЬ{},
rus_verbs:ДРЕЙФОВАТЬ{}, // Он и тогда не упадет, а будет дрейфовать в отбрасываемой диском тени. (ДРЕЙФОВАТЬ)
прилагательное:быстрый{}, // Кисель быстр в приготовлении
rus_verbs:призвать{}, // В День Воли белорусов призвали побороть страх и лень
rus_verbs:призывать{},
rus_verbs:ВОСПОЛЬЗОВАТЬСЯ{}, // этими деньгами смогу воспользоваться в отпуске (ВОСПОЛЬЗОВАТЬСЯ)
rus_verbs:КОНКУРИРОВАТЬ{}, // Наши клубы могли бы в Англии конкурировать с лидерами (КОНКУРИРОВАТЬ)
rus_verbs:ПОЗВАТЬ{}, // Американскую телеведущую позвали замуж в прямом эфире (ПОЗВАТЬ)
rus_verbs:ВЫХОДИТЬ{}, // Районные газеты Вологодчины будут выходить в цвете и новом формате (ВЫХОДИТЬ)
rus_verbs:РАЗВОРАЧИВАТЬСЯ{}, // Сюжет фэнтези разворачивается в двух мирах (РАЗВОРАЧИВАТЬСЯ)
rus_verbs:ОБСУДИТЬ{}, // В Самаре обсудили перспективы информатизации ветеринарии (ОБСУДИТЬ)
rus_verbs:ВЗДРОГНУТЬ{}, // она сильно вздрогнула во сне (ВЗДРОГНУТЬ)
rus_verbs:ПРЕДСТАВЛЯТЬ{}, // Сенаторы, представляющие в Комитете по разведке обе партии, поддержали эту просьбу (ПРЕДСТАВЛЯТЬ)
rus_verbs:ДОМИНИРОВАТЬ{}, // в химическом составе одной из планет доминирует метан (ДОМИНИРОВАТЬ)
rus_verbs:ОТКРЫТЬ{}, // Крым открыл в Москве собственный туристический офис (ОТКРЫТЬ)
rus_verbs:ПОКАЗАТЬ{}, // В Пушкинском музее показали золото инков (ПОКАЗАТЬ)
rus_verbs:наблюдать{}, // Наблюдаемый в отражении цвет излучения
rus_verbs:ПРОЛЕТЕТЬ{}, // Крупный астероид пролетел в непосредственной близости от Земли (ПРОЛЕТЕТЬ)
rus_verbs:РАССЛЕДОВАТЬ{}, // В Дагестане расследуют убийство федерального судьи (РАССЛЕДОВАТЬ)
rus_verbs:ВОЗОБНОВИТЬСЯ{}, // В Кемеровской области возобновилось движение по трассам международного значения (ВОЗОБНОВИТЬСЯ)
rus_verbs:ИЗМЕНИТЬСЯ{}, // изменилась она во всем (ИЗМЕНИТЬСЯ)
rus_verbs:СВЕРКАТЬ{}, // за широким окном комнаты город сверкал во тьме разноцветными огнями (СВЕРКАТЬ)
rus_verbs:СКОНЧАТЬСЯ{}, // В Риме скончался режиссёр знаменитого сериала «Спрут» (СКОНЧАТЬСЯ)
rus_verbs:ПРЯТАТЬСЯ{}, // Cкрытые спутники прячутся в кольцах Сатурна (ПРЯТАТЬСЯ)
rus_verbs:ВЫЗЫВАТЬ{}, // этот человек всегда вызывал во мне восхищение (ВЫЗЫВАТЬ)
rus_verbs:ВЫПУСТИТЬ{}, // Избирательные бюллетени могут выпустить в форме брошюры (ВЫПУСТИТЬ)
rus_verbs:НАЧИНАТЬСЯ{}, // В Москве начинается «марш в защиту детей» (НАЧИНАТЬСЯ)
rus_verbs:ЗАСТРЕЛИТЬ{}, // В Дагестане застрелили преподавателя медресе (ЗАСТРЕЛИТЬ)
rus_verbs:УРАВНЯТЬ{}, // Госзаказчиков уравняют в правах с поставщиками (УРАВНЯТЬ)
rus_verbs:промахнуться{}, // в первой половине невероятным образом промахнулся экс-форвард московского ЦСКА
rus_verbs:ОБЫГРАТЬ{}, // "Рубин" сенсационно обыграл в Мадриде вторую команду Испании (ОБЫГРАТЬ)
rus_verbs:ВКЛЮЧИТЬ{}, // В Челябинской области включен аварийный роуминг (ВКЛЮЧИТЬ)
rus_verbs:УЧАСТИТЬСЯ{}, // В селах Балаковского района участились случаи поджогов стогов сена (УЧАСТИТЬСЯ)
rus_verbs:СПАСТИ{}, // В Австралии спасли повисшего на проводе коршуна (СПАСТИ)
rus_verbs:ВЫПАСТЬ{}, // Отдельные фрагменты достигли земли, выпав в виде метеоритного дождя (ВЫПАСТЬ)
rus_verbs:НАГРАДИТЬ{}, // В Лондоне наградили лауреатов премии Brit Awards (НАГРАДИТЬ)
rus_verbs:ОТКРЫТЬСЯ{}, // в Москве открылся первый международный кинофестиваль
rus_verbs:ПОДНИМАТЬСЯ{}, // во мне поднималось раздражение
rus_verbs:ЗАВЕРШИТЬСЯ{}, // В Италии завершился традиционный Венецианский карнавал (ЗАВЕРШИТЬСЯ)
инфинитив:проводить{ вид:несоверш }, // Кузбасские депутаты проводят в Кемерове прием граждан
глагол:проводить{ вид:несоверш },
деепричастие:проводя{},
rus_verbs:отсутствовать{}, // Хозяйка квартиры в этот момент отсутствовала
rus_verbs:доложить{}, // об итогах своего визита он намерен доложить в американском сенате и Белом доме (ДОЛОЖИТЬ ОБ, В предл)
rus_verbs:ИЗДЕВАТЬСЯ{}, // В Эйлате издеваются над туристами (ИЗДЕВАТЬСЯ В предл)
rus_verbs:НАРУШИТЬ{}, // В нескольких регионах нарушено наземное транспортное сообщение (НАРУШИТЬ В предл)
rus_verbs:БЕЖАТЬ{}, // далеко внизу во тьме бежала невидимая река (БЕЖАТЬ В предл)
rus_verbs:СОБРАТЬСЯ{}, // Дмитрий оглядел собравшихся во дворе мальчишек (СОБРАТЬСЯ В предл)
rus_verbs:ПОСЛЫШАТЬСЯ{}, // далеко вверху во тьме послышался ответ (ПОСЛЫШАТЬСЯ В предл)
rus_verbs:ПОКАЗАТЬСЯ{}, // во дворе показалась высокая фигура (ПОКАЗАТЬСЯ В предл)
rus_verbs:УЛЫБНУТЬСЯ{}, // Дмитрий горько улыбнулся во тьме (УЛЫБНУТЬСЯ В предл)
rus_verbs:ТЯНУТЬСЯ{}, // убежища тянулись во всех направлениях (ТЯНУТЬСЯ В предл)
rus_verbs:РАНИТЬ{}, // В американском университете ранили человека (РАНИТЬ В предл)
rus_verbs:ЗАХВАТИТЬ{}, // Пираты освободили корабль, захваченный в Гвинейском заливе (ЗАХВАТИТЬ В предл)
rus_verbs:РАЗБЕГАТЬСЯ{}, // люди разбегались во всех направлениях (РАЗБЕГАТЬСЯ В предл)
rus_verbs:ПОГАСНУТЬ{}, // во всем доме погас свет (ПОГАСНУТЬ В предл)
rus_verbs:ПОШЕВЕЛИТЬСЯ{}, // Дмитрий пошевелился во сне (ПОШЕВЕЛИТЬСЯ В предл)
rus_verbs:ЗАСТОНАТЬ{}, // раненый застонал во сне (ЗАСТОНАТЬ В предл)
прилагательное:ВИНОВАТЫЙ{}, // во всем виновато вино (ВИНОВАТЫЙ В)
rus_verbs:ОСТАВЛЯТЬ{}, // США оставляют в районе Персидского залива только один авианосец (ОСТАВЛЯТЬ В предл)
rus_verbs:ОТКАЗЫВАТЬСЯ{}, // В России отказываются от планов авиагруппы в Арктике (ОТКАЗЫВАТЬСЯ В предл)
rus_verbs:ЛИКВИДИРОВАТЬ{}, // В Кабардино-Балкарии ликвидирован подпольный завод по переработке нефти (ЛИКВИДИРОВАТЬ В предл)
rus_verbs:РАЗОБЛАЧИТЬ{}, // В США разоблачили крупнейшую махинацию с кредитками (РАЗОБЛАЧИТЬ В предл)
rus_verbs:СХВАТИТЬ{}, // их схватили во сне (СХВАТИТЬ В предл)
rus_verbs:НАЧАТЬ{}, // В Белгороде начали сбор подписей за отставку мэра (НАЧАТЬ В предл)
rus_verbs:РАСТИ{}, // Cамая маленькая муха растёт в голове муравья (РАСТИ В предл)
rus_verbs:похитить{}, // Двое россиян, похищенных террористами в Сирии, освобождены (похитить в предл)
rus_verbs:УЧАСТВОВАТЬ{}, // были застрелены два испанских гражданских гвардейца , участвовавших в слежке (УЧАСТВОВАТЬ В)
rus_verbs:УСЫНОВИТЬ{}, // Американцы забирают усыновленных в России детей (УСЫНОВИТЬ В)
rus_verbs:ПРОИЗВЕСТИ{}, // вы не увидите мясо или молоко , произведенное в районе (ПРОИЗВЕСТИ В предл)
rus_verbs:ОРИЕНТИРОВАТЬСЯ{}, // призван помочь госслужащему правильно ориентироваться в сложных нравственных коллизиях (ОРИЕНТИРОВАТЬСЯ В)
rus_verbs:ПОВРЕДИТЬ{}, // В зале игровых автоматов повреждены стены и потолок (ПОВРЕДИТЬ В предл)
rus_verbs:ИЗЪЯТЬ{}, // В настоящее время в детском учреждении изъяты суточные пробы пищи (ИЗЪЯТЬ В предл)
rus_verbs:СОДЕРЖАТЬСЯ{}, // осужденных , содержащихся в помещениях штрафного изолятора (СОДЕРЖАТЬСЯ В)
rus_verbs:ОТЧИСЛИТЬ{}, // был отчислен за неуспеваемость в 2007 году (ОТЧИСЛИТЬ В предл)
rus_verbs:проходить{}, // находился на санкционированном митинге , проходившем в рамках празднования Дня народного единства (проходить в предл)
rus_verbs:ПОДУМЫВАТЬ{}, // сейчас в правительстве Приамурья подумывают о создании специального пункта помощи туристам (ПОДУМЫВАТЬ В)
rus_verbs:ОТРАПОРТОВЫВАТЬ{}, // главы субъектов не просто отрапортовывали в Москве (ОТРАПОРТОВЫВАТЬ В предл)
rus_verbs:ВЕСТИСЬ{}, // в городе ведутся работы по установке праздничной иллюминации (ВЕСТИСЬ В)
rus_verbs:ОДОБРИТЬ{}, // Одобренным в первом чтении законопроектом (ОДОБРИТЬ В)
rus_verbs:ЗАМЫЛИТЬСЯ{}, // ему легче исправлять , то , что замылилось в глазах предыдущего руководства (ЗАМЫЛИТЬСЯ В)
rus_verbs:АВТОРИЗОВАТЬСЯ{}, // потом имеют право авторизоваться в системе Международного бакалавриата (АВТОРИЗОВАТЬСЯ В)
rus_verbs:ОПУСТИТЬСЯ{}, // Россия опустилась в списке на шесть позиций (ОПУСТИТЬСЯ В предл)
rus_verbs:СГОРЕТЬ{}, // Совладелец сгоревшего в Бразилии ночного клуба сдался полиции (СГОРЕТЬ В)
частица:нет{}, // В этом нет сомнения.
частица:нету{}, // В этом нету сомнения.
rus_verbs:поджечь{}, // Поджегший себя в Москве мужчина оказался ветераном-афганцем
rus_verbs:ввести{}, // В Молдавии введен запрет на амнистию или помилование педофилов.
прилагательное:ДОСТУПНЫЙ{}, // Наиболее интересные таблички доступны в основной экспозиции музея (ДОСТУПНЫЙ В)
rus_verbs:ПОВИСНУТЬ{}, // вопрос повис в мглистом демократическом воздухе (ПОВИСНУТЬ В)
rus_verbs:ВЗОРВАТЬ{}, // В Ираке смертник взорвал в мечети группу туркменов (ВЗОРВАТЬ В)
rus_verbs:ОТНЯТЬ{}, // В Финляндии у россиянки, прибывшей по туристической визе, отняли детей (ОТНЯТЬ В)
rus_verbs:НАЙТИ{}, // Я недавно посетил врача и у меня в глазах нашли какую-то фигню (НАЙТИ В предл)
rus_verbs:ЗАСТРЕЛИТЬСЯ{}, // Девушка, застрелившаяся в центре Киева, была замешана в скандале с влиятельными людьми (ЗАСТРЕЛИТЬСЯ В)
rus_verbs:стартовать{}, // В Страсбурге сегодня стартует зимняя сессия Парламентской ассамблеи Совета Европы (стартовать в)
rus_verbs:ЗАКЛАДЫВАТЬСЯ{}, // Отношение к деньгам закладывается в детстве (ЗАКЛАДЫВАТЬСЯ В)
rus_verbs:НАПИВАТЬСЯ{}, // Депутатам помешают напиваться в здании Госдумы (НАПИВАТЬСЯ В)
rus_verbs:ВЫПРАВИТЬСЯ{}, // Прежде всего было заявлено, что мировая экономика каким-то образом сама выправится в процессе бизнес-цикла (ВЫПРАВИТЬСЯ В)
rus_verbs:ЯВЛЯТЬСЯ{}, // она являлась ко мне во всех моих снах (ЯВЛЯТЬСЯ В)
rus_verbs:СТАЖИРОВАТЬСЯ{}, // сейчас я стажируюсь в одной компании (СТАЖИРОВАТЬСЯ В)
rus_verbs:ОБСТРЕЛЯТЬ{}, // Уроженцы Чечни, обстрелявшие полицейских в центре Москвы, арестованы (ОБСТРЕЛЯТЬ В)
rus_verbs:РАСПРОСТРАНИТЬ{}, // Воски — распространённые в растительном и животном мире сложные эфиры высших жирных кислот и высших высокомолекулярных спиртов (РАСПРОСТРАНИТЬ В)
rus_verbs:ПРИВЕСТИ{}, // Сравнительная фугасность некоторых взрывчатых веществ приведена в следующей таблице (ПРИВЕСТИ В)
rus_verbs:ЗАПОДОЗРИТЬ{}, // Чиновников Минкультуры заподозрили в афере с заповедными землями (ЗАПОДОЗРИТЬ В)
rus_verbs:НАСТУПАТЬ{}, // В Гренландии стали наступать ледники (НАСТУПАТЬ В)
rus_verbs:ВЫДЕЛЯТЬСЯ{}, // В истории Земли выделяются следующие ледниковые эры (ВЫДЕЛЯТЬСЯ В)
rus_verbs:ПРЕДСТАВИТЬ{}, // Данные представлены в хронологическом порядке (ПРЕДСТАВИТЬ В)
rus_verbs:ОБРУШИТЬСЯ{}, // В Северной Осетии на воинскую часть обрушилась снежная лавина (ОБРУШИТЬСЯ В, НА)
rus_verbs:ПОДАВАТЬ{}, // Готовые компоты подают в столовых и кафе (ПОДАВАТЬ В)
rus_verbs:ГОТОВИТЬ{}, // Сегодня компот готовят в домашних условиях из сухофруктов или замороженных фруктов и ягод (ГОТОВИТЬ В)
rus_verbs:ВОЗДЕЛЫВАТЬСЯ{}, // в настоящее время он повсеместно возделывается в огородах (ВОЗДЕЛЫВАТЬСЯ В)
rus_verbs:РАСКЛАДЫВАТЬ{}, // Созревшие семенные экземпляры раскладывают на солнце или в теплом месте, где они делаются мягкими (РАСКЛАДЫВАТЬСЯ В, НА)
rus_verbs:РАСКЛАДЫВАТЬСЯ{},
rus_verbs:СОБИРАТЬСЯ{}, // Обыкновенно огурцы собираются в полуспелом состоянии (СОБИРАТЬСЯ В)
rus_verbs:ПРОГРЕМЕТЬ{}, // В торговом центре Ижевска прогремел взрыв (ПРОГРЕМЕТЬ В)
rus_verbs:СНЯТЬ{}, // чтобы снять их во всей красоте. (СНЯТЬ В)
rus_verbs:ЯВИТЬСЯ{}, // она явилась к нему во сне. (ЯВИТЬСЯ В)
rus_verbs:ВЕРИТЬ{}, // мы же во всем верили капитану. (ВЕРИТЬ В предл)
rus_verbs:выдержать{}, // Игра выдержана в научно-фантастическом стиле. (ВЫДЕРЖАННЫЙ В)
rus_verbs:ПРЕОДОЛЕТЬ{}, // мы пытались преодолеть ее во многих местах. (ПРЕОДОЛЕТЬ В)
инфинитив:НАПИСАТЬ{ aux stress="напис^ать" }, // Программа, написанная в спешке, выполнила недопустимую операцию. (НАПИСАТЬ В)
глагол:НАПИСАТЬ{ aux stress="напис^ать" },
прилагательное:НАПИСАННЫЙ{},
rus_verbs:ЕСТЬ{}, // ты даже во сне ел. (ЕСТЬ/кушать В)
rus_verbs:УСЕСТЬСЯ{}, // Он удобно уселся в кресле. (УСЕСТЬСЯ В)
rus_verbs:ТОРГОВАТЬ{}, // Он торгует в палатке. (ТОРГОВАТЬ В)
rus_verbs:СОВМЕСТИТЬ{}, // Он совместил в себе писателя и художника. (СОВМЕСТИТЬ В)
rus_verbs:ЗАБЫВАТЬ{}, // об этом нельзя забывать даже во сне. (ЗАБЫВАТЬ В)
rus_verbs:поговорить{}, // Давайте поговорим об этом в присутствии адвоката
rus_verbs:убрать{}, // В вагонах метро для комфорта пассажиров уберут сиденья (УБРАТЬ В, ДЛЯ)
rus_verbs:упасть{}, // В Таиланде на автобус с российскими туристами упал башенный кран (УПАСТЬ В, НА)
rus_verbs:раскрыть{}, // В России раскрыли крупнейшую в стране сеть фальшивомонетчиков (РАСКРЫТЬ В)
rus_verbs:соединить{}, // соединить в себе (СОЕДИНИТЬ В предл)
rus_verbs:избрать{}, // В Южной Корее избран новый президент (ИЗБРАТЬ В предл)
rus_verbs:проводиться{}, // Обыски проводятся в воронежском Доме прав человека (ПРОВОДИТЬСЯ В)
безлич_глагол:хватает{}, // В этой статье не хватает ссылок на источники информации. (БЕЗЛИЧ хватать в)
rus_verbs:наносить{}, // В ближнем бою наносит мощные удары своим костлявым кулаком. (НАНОСИТЬ В + предл.)
rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА)
прилагательное:известный{}, // В Европе сахар был известен ещё римлянам. (ИЗВЕСТНЫЙ В)
rus_verbs:выработать{}, // Способы, выработанные во Франции, перешли затем в Германию и другие страны Европы. (ВЫРАБОТАТЬ В)
rus_verbs:КУЛЬТИВИРОВАТЬСЯ{}, // Культивируется в регионах с умеренным климатом с умеренным количеством осадков и требует плодородной почвы. (КУЛЬТИВИРОВАТЬСЯ В)
rus_verbs:чаять{}, // мама души не чаяла в своих детях (ЧАЯТЬ В)
rus_verbs:улыбаться{}, // Вадим улыбался во сне. (УЛЫБАТЬСЯ В)
rus_verbs:растеряться{}, // Приезжие растерялись в бетонном лабиринте улиц (РАСТЕРЯТЬСЯ В)
rus_verbs:выть{}, // выли волки где-то в лесу (ВЫТЬ В)
rus_verbs:ЗАВЕРИТЬ{}, // выступавший заверил нас в намерении выполнить обещание (ЗАВЕРИТЬ В)
rus_verbs:ИСЧЕЗНУТЬ{}, // звери исчезли во мраке. (ИСЧЕЗНУТЬ В)
rus_verbs:ВСТАТЬ{}, // встать во главе человечества. (ВСТАТЬ В)
rus_verbs:УПОТРЕБЛЯТЬ{}, // В Тибете употребляют кирпичный зелёный чай. (УПОТРЕБЛЯТЬ В)
rus_verbs:ПОДАВАТЬСЯ{}, // Напиток охлаждается и подаётся в холодном виде. (ПОДАВАТЬСЯ В)
rus_verbs:ИСПОЛЬЗОВАТЬСЯ{}, // в игре используются текстуры большего разрешения (ИСПОЛЬЗОВАТЬСЯ В)
rus_verbs:объявить{}, // В газете объявили о конкурсе.
rus_verbs:ВСПЫХНУТЬ{}, // во мне вспыхнул гнев. (ВСПЫХНУТЬ В)
rus_verbs:КРЫТЬСЯ{}, // В его словах кроется угроза. (КРЫТЬСЯ В)
rus_verbs:подняться{}, // В классе вдруг поднялся шум. (подняться в)
rus_verbs:наступить{}, // В классе наступила полная тишина. (наступить в)
rus_verbs:кипеть{}, // В нём кипит злоба. (кипеть в)
rus_verbs:соединиться{}, // В нём соединились храбрость и великодушие. (соединиться в)
инфинитив:ПАРИТЬ{ aux stress="пар^ить"}, // Высоко в небе парит орёл, плавно описывая круги. (ПАРИТЬ В)
глагол:ПАРИТЬ{ aux stress="пар^ить"},
деепричастие:паря{ aux stress="пар^я" },
прилагательное:ПАРЯЩИЙ{},
прилагательное:ПАРИВШИЙ{},
rus_verbs:СИЯТЬ{}, // Главы собора сияли в лучах солнца. (СИЯТЬ В)
rus_verbs:РАСПОЛОЖИТЬ{}, // Гостиница расположена глубоко в горах. (РАСПОЛОЖИТЬ В)
rus_verbs:развиваться{}, // Действие в комедии развивается в двух планах. (развиваться в)
rus_verbs:ПОСАДИТЬ{}, // Дети посадили у нас во дворе цветы. (ПОСАДИТЬ В)
rus_verbs:ИСКОРЕНЯТЬ{}, // Дурные привычки следует искоренять в самом начале. (ИСКОРЕНЯТЬ В)
rus_verbs:ВОССТАНОВИТЬ{}, // Его восстановили в правах. (ВОССТАНОВИТЬ В)
rus_verbs:ПОЛАГАТЬСЯ{}, // мы полагаемся на него в этих вопросах (ПОЛАГАТЬСЯ В)
rus_verbs:УМИРАТЬ{}, // они умирали во сне. (УМИРАТЬ В)
rus_verbs:ПРИБАВИТЬ{}, // Она сильно прибавила в весе. (ПРИБАВИТЬ В)
rus_verbs:посмотреть{}, // Посмотрите в списке. (посмотреть в)
rus_verbs:производиться{}, // Выдача новых паспортов будет производиться в следующем порядке (производиться в)
rus_verbs:принять{}, // Документ принят в следующей редакции (принять в)
rus_verbs:сверкнуть{}, // меч его сверкнул во тьме. (сверкнуть в)
rus_verbs:ВЫРАБАТЫВАТЬ{}, // ты должен вырабатывать в себе силу воли (ВЫРАБАТЫВАТЬ В)
rus_verbs:достать{}, // Эти сведения мы достали в Волгограде. (достать в)
rus_verbs:звучать{}, // в доме звучала музыка (звучать в)
rus_verbs:колебаться{}, // колеблется в выборе (колебаться в)
rus_verbs:мешать{}, // мешать в кастрюле суп (мешать в)
rus_verbs:нарастать{}, // во мне нарастал гнев (нарастать в)
rus_verbs:отбыть{}, // Вадим отбыл в неизвестном направлении (отбыть в)
rus_verbs:светиться{}, // во всем доме светилось только окно ее спальни. (светиться в)
rus_verbs:вычитывать{}, // вычитывать в книге
rus_verbs:гудеть{}, // У него в ушах гудит.
rus_verbs:давать{}, // В этой лавке дают в долг?
rus_verbs:поблескивать{}, // Красивое стеклышко поблескивало в пыльной траве у дорожки.
rus_verbs:разойтись{}, // Они разошлись в темноте.
rus_verbs:прибежать{}, // Мальчик прибежал в слезах.
rus_verbs:биться{}, // Она билась в истерике.
rus_verbs:регистрироваться{}, // регистрироваться в системе
rus_verbs:считать{}, // я буду считать в уме
rus_verbs:трахаться{}, // трахаться в гамаке
rus_verbs:сконцентрироваться{}, // сконцентрироваться в одной точке
rus_verbs:разрушать{}, // разрушать в дробилке
rus_verbs:засидеться{}, // засидеться в гостях
rus_verbs:засиживаться{}, // засиживаться в гостях
rus_verbs:утопить{}, // утопить лодку в реке (утопить в реке)
rus_verbs:навестить{}, // навестить в доме престарелых
rus_verbs:запомнить{}, // запомнить в кэше
rus_verbs:убивать{}, // убивать в помещении полиции (-score убивать неодуш. дом.)
rus_verbs:базироваться{}, // установка базируется в черте города (ngram черта города - проверить что есть проверка)
rus_verbs:покупать{}, // Чаще всего россияне покупают в интернете бытовую технику.
rus_verbs:ходить{}, // ходить в пальто (сделать ХОДИТЬ + в + ОДЕЖДА предл.п.)
rus_verbs:заложить{}, // диверсанты заложили в помещении бомбу
rus_verbs:оглядываться{}, // оглядываться в зеркале
rus_verbs:нарисовать{}, // нарисовать в тетрадке
rus_verbs:пробить{}, // пробить отверствие в стене
rus_verbs:повертеть{}, // повертеть в руке
rus_verbs:вертеть{}, // Я вертел в руках
rus_verbs:рваться{}, // Веревка рвется в месте надреза
rus_verbs:распространяться{}, // распространяться в среде наркоманов
rus_verbs:попрощаться{}, // попрощаться в здании морга
rus_verbs:соображать{}, // соображать в уме
инфинитив:просыпаться{ вид:несоверш }, глагол:просыпаться{ вид:несоверш }, // просыпаться в чужой кровати
rus_verbs:заехать{}, // Коля заехал в гости (в гости - устойчивый наречный оборот)
rus_verbs:разобрать{}, // разобрать в гараже
rus_verbs:помереть{}, // помереть в пути
rus_verbs:различить{}, // различить в темноте
rus_verbs:рисовать{}, // рисовать в графическом редакторе
rus_verbs:проследить{}, // проследить в записях камер слежения
rus_verbs:совершаться{}, // Правосудие совершается в суде
rus_verbs:задремать{}, // задремать в кровати
rus_verbs:ругаться{}, // ругаться в комнате
rus_verbs:зазвучать{}, // зазвучать в радиоприемниках
rus_verbs:задохнуться{}, // задохнуться в воде
rus_verbs:порождать{}, // порождать в неокрепших умах
rus_verbs:отдыхать{}, // отдыхать в санатории
rus_verbs:упоминаться{}, // упоминаться в предыдущем сообщении
rus_verbs:образовать{}, // образовать в пробирке темную взвесь
rus_verbs:отмечать{}, // отмечать в списке
rus_verbs:подчеркнуть{}, // подчеркнуть в блокноте
rus_verbs:плясать{}, // плясать в откружении незнакомых людей
rus_verbs:повысить{}, // повысить в звании
rus_verbs:поджидать{}, // поджидать в подъезде
rus_verbs:отказать{}, // отказать в пересмотре дела
rus_verbs:раствориться{}, // раствориться в бензине
rus_verbs:отражать{}, // отражать в стихах
rus_verbs:дремать{}, // дремать в гамаке
rus_verbs:применяться{}, // применяться в домашних условиях
rus_verbs:присниться{}, // присниться во сне
rus_verbs:трястись{}, // трястись в драндулете
rus_verbs:сохранять{}, // сохранять в неприкосновенности
rus_verbs:расстрелять{}, // расстрелять в ложбине
rus_verbs:рассчитать{}, // рассчитать в программе
rus_verbs:перебирать{}, // перебирать в руке
rus_verbs:разбиться{}, // разбиться в аварии
rus_verbs:поискать{}, // поискать в углу
rus_verbs:мучиться{}, // мучиться в тесной клетке
rus_verbs:замелькать{}, // замелькать в телевизоре
rus_verbs:грустить{}, // грустить в одиночестве
rus_verbs:крутить{}, // крутить в банке
rus_verbs:объявиться{}, // объявиться в городе
rus_verbs:подготовить{}, // подготовить в тайне
rus_verbs:различать{}, // различать в смеси
rus_verbs:обнаруживать{}, // обнаруживать в крови
rus_verbs:киснуть{}, // киснуть в захолустье
rus_verbs:оборваться{}, // оборваться в начале фразы
rus_verbs:запутаться{}, // запутаться в веревках
rus_verbs:общаться{}, // общаться в интимной обстановке
rus_verbs:сочинить{}, // сочинить в ресторане
rus_verbs:изобрести{}, // изобрести в домашней лаборатории
rus_verbs:прокомментировать{}, // прокомментировать в своем блоге
rus_verbs:давить{}, // давить в зародыше
rus_verbs:повториться{}, // повториться в новом обличье
rus_verbs:отставать{}, // отставать в общем зачете
rus_verbs:разработать{}, // разработать в лаборатории
rus_verbs:качать{}, // качать в кроватке
rus_verbs:заменить{}, // заменить в двигателе
rus_verbs:задыхаться{}, // задыхаться в душной и влажной атмосфере
rus_verbs:забегать{}, // забегать в спешке
rus_verbs:наделать{}, // наделать в решении ошибок
rus_verbs:исказиться{}, // исказиться в кривом зеркале
rus_verbs:тушить{}, // тушить в помещении пожар
rus_verbs:охранять{}, // охранять в здании входы
rus_verbs:приметить{}, // приметить в кустах
rus_verbs:скрыть{}, // скрыть в складках одежды
rus_verbs:удерживать{}, // удерживать в заложниках
rus_verbs:увеличиваться{}, // увеличиваться в размере
rus_verbs:красоваться{}, // красоваться в новом платье
rus_verbs:сохраниться{}, // сохраниться в тепле
rus_verbs:лечить{}, // лечить в стационаре
rus_verbs:смешаться{}, // смешаться в баке
rus_verbs:прокатиться{}, // прокатиться в троллейбусе
rus_verbs:договариваться{}, // договариваться в закрытом кабинете
rus_verbs:опубликовать{}, // опубликовать в официальном блоге
rus_verbs:охотиться{}, // охотиться в прериях
rus_verbs:отражаться{}, // отражаться в окне
rus_verbs:понизить{}, // понизить в должности
rus_verbs:обедать{}, // обедать в ресторане
rus_verbs:посидеть{}, // посидеть в тени
rus_verbs:сообщаться{}, // сообщаться в оппозиционной газете
rus_verbs:свершиться{}, // свершиться в суде
rus_verbs:ночевать{}, // ночевать в гостинице
rus_verbs:темнеть{}, // темнеть в воде
rus_verbs:гибнуть{}, // гибнуть в застенках
rus_verbs:усиливаться{}, // усиливаться в направлении главного удара
rus_verbs:расплыться{}, // расплыться в улыбке
rus_verbs:превышать{}, // превышать в несколько раз
rus_verbs:проживать{}, // проживать в отдельной коморке
rus_verbs:голубеть{}, // голубеть в тепле
rus_verbs:исследовать{}, // исследовать в естественных условиях
rus_verbs:обитать{}, // обитать в лесу
rus_verbs:скучать{}, // скучать в одиночестве
rus_verbs:сталкиваться{}, // сталкиваться в воздухе
rus_verbs:таиться{}, // таиться в глубине
rus_verbs:спасать{}, // спасать в море
rus_verbs:заблудиться{}, // заблудиться в лесу
rus_verbs:создаться{}, // создаться в новом виде
rus_verbs:пошарить{}, // пошарить в кармане
rus_verbs:планировать{}, // планировать в программе
rus_verbs:отбить{}, // отбить в нижней части
rus_verbs:отрицать{}, // отрицать в суде свою вину
rus_verbs:основать{}, // основать в пустыне новый город
rus_verbs:двоить{}, // двоить в глазах
rus_verbs:устоять{}, // устоять в лодке
rus_verbs:унять{}, // унять в ногах дрожь
rus_verbs:отзываться{}, // отзываться в обзоре
rus_verbs:притормозить{}, // притормозить в траве
rus_verbs:читаться{}, // читаться в глазах
rus_verbs:житься{}, // житься в деревне
rus_verbs:заиграть{}, // заиграть в жилах
rus_verbs:шевелить{}, // шевелить в воде
rus_verbs:зазвенеть{}, // зазвенеть в ушах
rus_verbs:зависнуть{}, // зависнуть в библиотеке
rus_verbs:затаить{}, // затаить в душе обиду
rus_verbs:сознаться{}, // сознаться в совершении
rus_verbs:протекать{}, // протекать в легкой форме
rus_verbs:выясняться{}, // выясняться в ходе эксперимента
rus_verbs:скрестить{}, // скрестить в неволе
rus_verbs:наводить{}, // наводить в комнате порядок
rus_verbs:значиться{}, // значиться в документах
rus_verbs:заинтересовать{}, // заинтересовать в получении результатов
rus_verbs:познакомить{}, // познакомить в непринужденной обстановке
rus_verbs:рассеяться{}, // рассеяться в воздухе
rus_verbs:грохнуть{}, // грохнуть в подвале
rus_verbs:обвинять{}, // обвинять в вымогательстве
rus_verbs:столпиться{}, // столпиться в фойе
rus_verbs:порыться{}, // порыться в сумке
rus_verbs:ослабить{}, // ослабить в верхней части
rus_verbs:обнаруживаться{}, // обнаруживаться в кармане куртки
rus_verbs:спастись{}, // спастись в хижине
rus_verbs:прерваться{}, // прерваться в середине фразы
rus_verbs:применять{}, // применять в повседневной работе
rus_verbs:строиться{}, // строиться в зоне отчуждения
rus_verbs:путешествовать{}, // путешествовать в самолете
rus_verbs:побеждать{}, // побеждать в честной битве
rus_verbs:погубить{}, // погубить в себе артиста
rus_verbs:рассматриваться{}, // рассматриваться в следующей главе
rus_verbs:продаваться{}, // продаваться в специализированном магазине
rus_verbs:разместиться{}, // разместиться в аудитории
rus_verbs:повидать{}, // повидать в жизни
rus_verbs:настигнуть{}, // настигнуть в пригородах
rus_verbs:сгрудиться{}, // сгрудиться в центре загона
rus_verbs:укрыться{}, // укрыться в доме
rus_verbs:расплакаться{}, // расплакаться в суде
rus_verbs:пролежать{}, // пролежать в канаве
rus_verbs:замерзнуть{}, // замерзнуть в ледяной воде
rus_verbs:поскользнуться{}, // поскользнуться в коридоре
rus_verbs:таскать{}, // таскать в руках
rus_verbs:нападать{}, // нападать в вольере
rus_verbs:просматривать{}, // просматривать в браузере
rus_verbs:обдумать{}, // обдумать в дороге
rus_verbs:обвинить{}, // обвинить в измене
rus_verbs:останавливать{}, // останавливать в дверях
rus_verbs:теряться{}, // теряться в догадках
rus_verbs:погибать{}, // погибать в бою
rus_verbs:обозначать{}, // обозначать в списке
rus_verbs:запрещать{}, // запрещать в парке
rus_verbs:долететь{}, // долететь в вертолёте
rus_verbs:тесниться{}, // тесниться в каморке
rus_verbs:уменьшаться{}, // уменьшаться в размере
rus_verbs:издавать{}, // издавать в небольшом издательстве
rus_verbs:хоронить{}, // хоронить в море
rus_verbs:перемениться{}, // перемениться в лице
rus_verbs:установиться{}, // установиться в северных областях
rus_verbs:прикидывать{}, // прикидывать в уме
rus_verbs:затаиться{}, // затаиться в траве
rus_verbs:раздобыть{}, // раздобыть в аптеке
rus_verbs:перебросить{}, // перебросить в товарном составе
rus_verbs:погружаться{}, // погружаться в батискафе
rus_verbs:поживать{}, // поживать в одиночестве
rus_verbs:признаваться{}, // признаваться в любви
rus_verbs:захватывать{}, // захватывать в здании
rus_verbs:покачиваться{}, // покачиваться в лодке
rus_verbs:крутиться{}, // крутиться в колесе
rus_verbs:помещаться{}, // помещаться в ящике
rus_verbs:питаться{}, // питаться в столовой
rus_verbs:отдохнуть{}, // отдохнуть в пансионате
rus_verbs:кататься{}, // кататься в коляске
rus_verbs:поработать{}, // поработать в цеху
rus_verbs:подразумевать{}, // подразумевать в задании
rus_verbs:ограбить{}, // ограбить в подворотне
rus_verbs:преуспеть{}, // преуспеть в бизнесе
rus_verbs:заерзать{}, // заерзать в кресле
rus_verbs:разъяснить{}, // разъяснить в другой статье
rus_verbs:продвинуться{}, // продвинуться в изучении
rus_verbs:поколебаться{}, // поколебаться в начале
rus_verbs:засомневаться{}, // засомневаться в честности
rus_verbs:приникнуть{}, // приникнуть в уме
rus_verbs:скривить{}, // скривить в усмешке
rus_verbs:рассечь{}, // рассечь в центре опухоли
rus_verbs:перепутать{}, // перепутать в роддоме
rus_verbs:посмеяться{}, // посмеяться в перерыве
rus_verbs:отмечаться{}, // отмечаться в полицейском участке
rus_verbs:накопиться{}, // накопиться в отстойнике
rus_verbs:уносить{}, // уносить в руках
rus_verbs:навещать{}, // навещать в больнице
rus_verbs:остыть{}, // остыть в проточной воде
rus_verbs:запереться{}, // запереться в комнате
rus_verbs:обогнать{}, // обогнать в первом круге
rus_verbs:убеждаться{}, // убеждаться в неизбежности
rus_verbs:подбирать{}, // подбирать в магазине
rus_verbs:уничтожать{}, // уничтожать в полете
rus_verbs:путаться{}, // путаться в показаниях
rus_verbs:притаиться{}, // притаиться в темноте
rus_verbs:проплывать{}, // проплывать в лодке
rus_verbs:засесть{}, // засесть в окопе
rus_verbs:подцепить{}, // подцепить в баре
rus_verbs:насчитать{}, // насчитать в диктанте несколько ошибок
rus_verbs:оправдаться{}, // оправдаться в суде
rus_verbs:созреть{}, // созреть в естественных условиях
rus_verbs:раскрываться{}, // раскрываться в подходящих условиях
rus_verbs:ожидаться{}, // ожидаться в верхней части
rus_verbs:одеваться{}, // одеваться в дорогих бутиках
rus_verbs:упрекнуть{}, // упрекнуть в недостатке опыта
rus_verbs:грабить{}, // грабить в подворотне
rus_verbs:ужинать{}, // ужинать в ресторане
rus_verbs:гонять{}, // гонять в жилах
rus_verbs:уверить{}, // уверить в безопасности
rus_verbs:потеряться{}, // потеряться в лесу
rus_verbs:устанавливаться{}, // устанавливаться в комнате
rus_verbs:предоставлять{}, // предоставлять в суде
rus_verbs:протянуться{}, // протянуться в стене
rus_verbs:допрашивать{}, // допрашивать в бункере
rus_verbs:проработать{}, // проработать в кабинете
rus_verbs:сосредоточить{}, // сосредоточить в своих руках
rus_verbs:утвердить{}, // утвердить в должности
rus_verbs:сочинять{}, // сочинять в дороге
rus_verbs:померкнуть{}, // померкнуть в глазах
rus_verbs:показываться{}, // показываться в окошке
rus_verbs:похудеть{}, // похудеть в талии
rus_verbs:проделывать{}, // проделывать в стене
rus_verbs:прославиться{}, // прославиться в интернете
rus_verbs:сдохнуть{}, // сдохнуть в нищете
rus_verbs:раскинуться{}, // раскинуться в степи
rus_verbs:развить{}, // развить в себе способности
rus_verbs:уставать{}, // уставать в цеху
rus_verbs:укрепить{}, // укрепить в земле
rus_verbs:числиться{}, // числиться в списке
rus_verbs:образовывать{}, // образовывать в смеси
rus_verbs:екнуть{}, // екнуть в груди
rus_verbs:одобрять{}, // одобрять в своей речи
rus_verbs:запить{}, // запить в одиночестве
rus_verbs:забыться{}, // забыться в тяжелом сне
rus_verbs:чернеть{}, // чернеть в кислой среде
rus_verbs:размещаться{}, // размещаться в гараже
rus_verbs:соорудить{}, // соорудить в гараже
rus_verbs:развивать{}, // развивать в себе
rus_verbs:пастись{}, // пастись в пойме
rus_verbs:формироваться{}, // формироваться в верхних слоях атмосферы
rus_verbs:ослабнуть{}, // ослабнуть в сочленении
rus_verbs:таить{}, // таить в себе
инфинитив:пробегать{ вид:несоверш }, глагол:пробегать{ вид:несоверш }, // пробегать в спешке
rus_verbs:приостановиться{}, // приостановиться в конце
rus_verbs:топтаться{}, // топтаться в грязи
rus_verbs:громить{}, // громить в финале
rus_verbs:заменять{}, // заменять в основном составе
rus_verbs:подъезжать{}, // подъезжать в колясках
rus_verbs:вычислить{}, // вычислить в уме
rus_verbs:заказывать{}, // заказывать в магазине
rus_verbs:осуществить{}, // осуществить в реальных условиях
rus_verbs:обосноваться{}, // обосноваться в дупле
rus_verbs:пытать{}, // пытать в камере
rus_verbs:поменять{}, // поменять в магазине
rus_verbs:совершиться{}, // совершиться в суде
rus_verbs:пролетать{}, // пролетать в вертолете
rus_verbs:сбыться{}, // сбыться во сне
rus_verbs:разговориться{}, // разговориться в отделении
rus_verbs:преподнести{}, // преподнести в красивой упаковке
rus_verbs:напечатать{}, // напечатать в типографии
rus_verbs:прорвать{}, // прорвать в центре
rus_verbs:раскачиваться{}, // раскачиваться в кресле
rus_verbs:задерживаться{}, // задерживаться в дверях
rus_verbs:угощать{}, // угощать в кафе
rus_verbs:проступать{}, // проступать в глубине
rus_verbs:шарить{}, // шарить в математике
rus_verbs:увеличивать{}, // увеличивать в конце
rus_verbs:расцвести{}, // расцвести в оранжерее
rus_verbs:закипеть{}, // закипеть в баке
rus_verbs:подлететь{}, // подлететь в вертолете
rus_verbs:рыться{}, // рыться в куче
rus_verbs:пожить{}, // пожить в гостинице
rus_verbs:добираться{}, // добираться в попутном транспорте
rus_verbs:перекрыть{}, // перекрыть в коридоре
rus_verbs:продержаться{}, // продержаться в барокамере
rus_verbs:разыскивать{}, // разыскивать в толпе
rus_verbs:освобождать{}, // освобождать в зале суда
rus_verbs:подметить{}, // подметить в человеке
rus_verbs:передвигаться{}, // передвигаться в узкой юбке
rus_verbs:продумать{}, // продумать в уме
rus_verbs:извиваться{}, // извиваться в траве
rus_verbs:процитировать{}, // процитировать в статье
rus_verbs:прогуливаться{}, // прогуливаться в парке
rus_verbs:защемить{}, // защемить в двери
rus_verbs:увеличиться{}, // увеличиться в объеме
rus_verbs:проявиться{}, // проявиться в результатах
rus_verbs:заскользить{}, // заскользить в ботинках
rus_verbs:пересказать{}, // пересказать в своем выступлении
rus_verbs:протестовать{}, // протестовать в здании парламента
rus_verbs:указываться{}, // указываться в путеводителе
rus_verbs:копошиться{}, // копошиться в песке
rus_verbs:проигнорировать{}, // проигнорировать в своей работе
rus_verbs:купаться{}, // купаться в речке
rus_verbs:подсчитать{}, // подсчитать в уме
rus_verbs:разволноваться{}, // разволноваться в классе
rus_verbs:придумывать{}, // придумывать в своем воображении
rus_verbs:предусмотреть{}, // предусмотреть в программе
rus_verbs:завертеться{}, // завертеться в колесе
rus_verbs:зачерпнуть{}, // зачерпнуть в ручье
rus_verbs:очистить{}, // очистить в химической лаборатории
rus_verbs:прозвенеть{}, // прозвенеть в коридорах
rus_verbs:уменьшиться{}, // уменьшиться в размере
rus_verbs:колыхаться{}, // колыхаться в проточной воде
rus_verbs:ознакомиться{}, // ознакомиться в автобусе
rus_verbs:ржать{}, // ржать в аудитории
rus_verbs:раскинуть{}, // раскинуть в микрорайоне
rus_verbs:разлиться{}, // разлиться в воде
rus_verbs:сквозить{}, // сквозить в словах
rus_verbs:задушить{}, // задушить в объятиях
rus_verbs:осудить{}, // осудить в особом порядке
rus_verbs:разгромить{}, // разгромить в честном поединке
rus_verbs:подслушать{}, // подслушать в кулуарах
rus_verbs:проповедовать{}, // проповедовать в сельских районах
rus_verbs:озарить{}, // озарить во сне
rus_verbs:потирать{}, // потирать в предвкушении
rus_verbs:описываться{}, // описываться в статье
rus_verbs:качаться{}, // качаться в кроватке
rus_verbs:усилить{}, // усилить в центре
rus_verbs:прохаживаться{}, // прохаживаться в новом костюме
rus_verbs:полечить{}, // полечить в больничке
rus_verbs:сниматься{}, // сниматься в римейке
rus_verbs:сыскать{}, // сыскать в наших краях
rus_verbs:поприветствовать{}, // поприветствовать в коридоре
rus_verbs:подтвердиться{}, // подтвердиться в эксперименте
rus_verbs:плескаться{}, // плескаться в теплой водичке
rus_verbs:расширяться{}, // расширяться в первом сегменте
rus_verbs:мерещиться{}, // мерещиться в тумане
rus_verbs:сгущаться{}, // сгущаться в воздухе
rus_verbs:храпеть{}, // храпеть во сне
rus_verbs:подержать{}, // подержать в руках
rus_verbs:накинуться{}, // накинуться в подворотне
rus_verbs:планироваться{}, // планироваться в закрытом режиме
rus_verbs:пробудить{}, // пробудить в себе
rus_verbs:побриться{}, // побриться в ванной
rus_verbs:сгинуть{}, // сгинуть в пучине
rus_verbs:окрестить{}, // окрестить в церкви
инфинитив:резюмировать{ вид:соверш }, глагол:резюмировать{ вид:соверш }, // резюмировать в конце выступления
rus_verbs:замкнуться{}, // замкнуться в себе
rus_verbs:прибавлять{}, // прибавлять в весе
rus_verbs:проплыть{}, // проплыть в лодке
rus_verbs:растворяться{}, // растворяться в тумане
rus_verbs:упрекать{}, // упрекать в небрежности
rus_verbs:затеряться{}, // затеряться в лабиринте
rus_verbs:перечитывать{}, // перечитывать в поезде
rus_verbs:перелететь{}, // перелететь в вертолете
rus_verbs:оживать{}, // оживать в теплой воде
rus_verbs:заглохнуть{}, // заглохнуть в полете
rus_verbs:кольнуть{}, // кольнуть в боку
rus_verbs:копаться{}, // копаться в куче
rus_verbs:развлекаться{}, // развлекаться в клубе
rus_verbs:отливать{}, // отливать в кустах
rus_verbs:зажить{}, // зажить в деревне
rus_verbs:одолжить{}, // одолжить в соседнем кабинете
rus_verbs:заклинать{}, // заклинать в своей речи
rus_verbs:различаться{}, // различаться в мелочах
rus_verbs:печататься{}, // печататься в типографии
rus_verbs:угадываться{}, // угадываться в контурах
rus_verbs:обрывать{}, // обрывать в начале
rus_verbs:поглаживать{}, // поглаживать в кармане
rus_verbs:подписывать{}, // подписывать в присутствии понятых
rus_verbs:добывать{}, // добывать в разломе
rus_verbs:скопиться{}, // скопиться в воротах
rus_verbs:повстречать{}, // повстречать в бане
rus_verbs:совпасть{}, // совпасть в упрощенном виде
rus_verbs:разрываться{}, // разрываться в точке спайки
rus_verbs:улавливать{}, // улавливать в датчике
rus_verbs:повстречаться{}, // повстречаться в лифте
rus_verbs:отразить{}, // отразить в отчете
rus_verbs:пояснять{}, // пояснять в примечаниях
rus_verbs:накормить{}, // накормить в столовке
rus_verbs:поужинать{}, // поужинать в ресторане
инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть в суде
инфинитив:спеть{ вид:несоверш }, глагол:спеть{ вид:несоверш },
rus_verbs:топить{}, // топить в молоке
rus_verbs:освоить{}, // освоить в работе
rus_verbs:зародиться{}, // зародиться в голове
rus_verbs:отплыть{}, // отплыть в старой лодке
rus_verbs:отстаивать{}, // отстаивать в суде
rus_verbs:осуждать{}, // осуждать в своем выступлении
rus_verbs:переговорить{}, // переговорить в перерыве
rus_verbs:разгораться{}, // разгораться в сердце
rus_verbs:укрыть{}, // укрыть в шалаше
rus_verbs:томиться{}, // томиться в застенках
rus_verbs:клубиться{}, // клубиться в воздухе
rus_verbs:сжигать{}, // сжигать в топке
rus_verbs:позавтракать{}, // позавтракать в кафешке
rus_verbs:функционировать{}, // функционировать в лабораторных условиях
rus_verbs:смять{}, // смять в руке
rus_verbs:разместить{}, // разместить в интернете
rus_verbs:пронести{}, // пронести в потайном кармане
rus_verbs:руководствоваться{}, // руководствоваться в работе
rus_verbs:нашарить{}, // нашарить в потемках
rus_verbs:закрутить{}, // закрутить в вихре
rus_verbs:просматриваться{}, // просматриваться в дальней перспективе
rus_verbs:распознать{}, // распознать в незнакомце
rus_verbs:повеситься{}, // повеситься в камере
rus_verbs:обшарить{}, // обшарить в поисках наркотиков
rus_verbs:наполняться{}, // наполняется в карьере
rus_verbs:засвистеть{}, // засвистеть в воздухе
rus_verbs:процветать{}, // процветать в мягком климате
rus_verbs:шуршать{}, // шуршать в простенке
rus_verbs:подхватывать{}, // подхватывать в полете
инфинитив:роиться{}, глагол:роиться{}, // роиться в воздухе
прилагательное:роившийся{}, прилагательное:роящийся{},
// деепричастие:роясь{ aux stress="ро^ясь" },
rus_verbs:преобладать{}, // преобладать в тексте
rus_verbs:посветлеть{}, // посветлеть в лице
rus_verbs:игнорировать{}, // игнорировать в рекомендациях
rus_verbs:обсуждаться{}, // обсуждаться в кулуарах
rus_verbs:отказывать{}, // отказывать в визе
rus_verbs:ощупывать{}, // ощупывать в кармане
rus_verbs:разливаться{}, // разливаться в цеху
rus_verbs:расписаться{}, // расписаться в получении
rus_verbs:учинить{}, // учинить в казарме
rus_verbs:плестись{}, // плестись в хвосте
rus_verbs:объявляться{}, // объявляться в группе
rus_verbs:повышаться{}, // повышаться в первой части
rus_verbs:напрягать{}, // напрягать в паху
rus_verbs:разрабатывать{}, // разрабатывать в студии
rus_verbs:хлопотать{}, // хлопотать в мэрии
rus_verbs:прерывать{}, // прерывать в самом начале
rus_verbs:каяться{}, // каяться в грехах
rus_verbs:освоиться{}, // освоиться в кабине
rus_verbs:подплыть{}, // подплыть в лодке
rus_verbs:замигать{}, // замигать в темноте
rus_verbs:оскорблять{}, // оскорблять в выступлении
rus_verbs:торжествовать{}, // торжествовать в душе
rus_verbs:поправлять{}, // поправлять в прологе
rus_verbs:угадывать{}, // угадывать в размытом изображении
rus_verbs:потоптаться{}, // потоптаться в прихожей
rus_verbs:переправиться{}, // переправиться в лодочке
rus_verbs:увериться{}, // увериться в невиновности
rus_verbs:забрезжить{}, // забрезжить в конце тоннеля
rus_verbs:утвердиться{}, // утвердиться во мнении
rus_verbs:завывать{}, // завывать в трубе
rus_verbs:заварить{}, // заварить в заварнике
rus_verbs:скомкать{}, // скомкать в руке
rus_verbs:перемещаться{}, // перемещаться в капсуле
инфинитив:писаться{ aux stress="пис^аться" }, глагол:писаться{ aux stress="пис^аться" }, // писаться в первом поле
rus_verbs:праздновать{}, // праздновать в баре
rus_verbs:мигать{}, // мигать в темноте
rus_verbs:обучить{}, // обучить в мастерской
rus_verbs:орудовать{}, // орудовать в кладовке
rus_verbs:упорствовать{}, // упорствовать в заблуждении
rus_verbs:переминаться{}, // переминаться в прихожей
rus_verbs:подрасти{}, // подрасти в теплице
rus_verbs:предписываться{}, // предписываться в законе
rus_verbs:приписать{}, // приписать в конце
rus_verbs:задаваться{}, // задаваться в своей статье
rus_verbs:чинить{}, // чинить в домашних условиях
rus_verbs:раздеваться{}, // раздеваться в пляжной кабинке
rus_verbs:пообедать{}, // пообедать в ресторанчике
rus_verbs:жрать{}, // жрать в чуланчике
rus_verbs:исполняться{}, // исполняться в антракте
rus_verbs:гнить{}, // гнить в тюрьме
rus_verbs:глодать{}, // глодать в конуре
rus_verbs:прослушать{}, // прослушать в дороге
rus_verbs:истратить{}, // истратить в кабаке
rus_verbs:стареть{}, // стареть в одиночестве
rus_verbs:разжечь{}, // разжечь в сердце
rus_verbs:совещаться{}, // совещаться в кабинете
rus_verbs:покачивать{}, // покачивать в кроватке
rus_verbs:отсидеть{}, // отсидеть в одиночке
rus_verbs:формировать{}, // формировать в умах
rus_verbs:захрапеть{}, // захрапеть во сне
rus_verbs:петься{}, // петься в хоре
rus_verbs:объехать{}, // объехать в автобусе
rus_verbs:поселить{}, // поселить в гостинице
rus_verbs:предаться{}, // предаться в книге
rus_verbs:заворочаться{}, // заворочаться во сне
rus_verbs:напрятать{}, // напрятать в карманах
rus_verbs:очухаться{}, // очухаться в незнакомом месте
rus_verbs:ограничивать{}, // ограничивать в движениях
rus_verbs:завертеть{}, // завертеть в руках
rus_verbs:печатать{}, // печатать в редакторе
rus_verbs:теплиться{}, // теплиться в сердце
rus_verbs:увязнуть{}, // увязнуть в зыбучем песке
rus_verbs:усмотреть{}, // усмотреть в обращении
rus_verbs:отыскаться{}, // отыскаться в запасах
rus_verbs:потушить{}, // потушить в горле огонь
rus_verbs:поубавиться{}, // поубавиться в размере
rus_verbs:зафиксировать{}, // зафиксировать в постоянной памяти
rus_verbs:смыть{}, // смыть в ванной
rus_verbs:заместить{}, // заместить в кресле
rus_verbs:угасать{}, // угасать в одиночестве
rus_verbs:сразить{}, // сразить в споре
rus_verbs:фигурировать{}, // фигурировать в бюллетене
rus_verbs:расплываться{}, // расплываться в глазах
rus_verbs:сосчитать{}, // сосчитать в уме
rus_verbs:сгуститься{}, // сгуститься в воздухе
rus_verbs:цитировать{}, // цитировать в своей статье
rus_verbs:помяться{}, // помяться в давке
rus_verbs:затрагивать{}, // затрагивать в процессе выполнения
rus_verbs:обтереть{}, // обтереть в гараже
rus_verbs:подстрелить{}, // подстрелить в пойме реки
rus_verbs:растереть{}, // растереть в руке
rus_verbs:подавлять{}, // подавлять в зародыше
rus_verbs:смешиваться{}, // смешиваться в чане
инфинитив:вычитать{ вид:соверш }, глагол:вычитать{ вид:соверш }, // вычитать в книжечке
rus_verbs:сократиться{}, // сократиться в обхвате
rus_verbs:занервничать{}, // занервничать в кабинете
rus_verbs:соприкоснуться{}, // соприкоснуться в полете
rus_verbs:обозначить{}, // обозначить в объявлении
rus_verbs:обучаться{}, // обучаться в училище
rus_verbs:снизиться{}, // снизиться в нижних слоях атмосферы
rus_verbs:лелеять{}, // лелеять в сердце
rus_verbs:поддерживаться{}, // поддерживаться в суде
rus_verbs:уплыть{}, // уплыть в лодочке
rus_verbs:резвиться{}, // резвиться в саду
rus_verbs:поерзать{}, // поерзать в гамаке
rus_verbs:оплатить{}, // оплатить в ресторане
rus_verbs:похвастаться{}, // похвастаться в компании
rus_verbs:знакомиться{}, // знакомиться в классе
rus_verbs:приплыть{}, // приплыть в подводной лодке
rus_verbs:зажигать{}, // зажигать в классе
rus_verbs:смыслить{}, // смыслить в математике
rus_verbs:закопать{}, // закопать в огороде
rus_verbs:порхать{}, // порхать в зарослях
rus_verbs:потонуть{}, // потонуть в бумажках
rus_verbs:стирать{}, // стирать в холодной воде
rus_verbs:подстерегать{}, // подстерегать в придорожных кустах
rus_verbs:погулять{}, // погулять в парке
rus_verbs:предвкушать{}, // предвкушать в воображении
rus_verbs:ошеломить{}, // ошеломить в бою
rus_verbs:удостовериться{}, // удостовериться в безопасности
rus_verbs:огласить{}, // огласить в заключительной части
rus_verbs:разбогатеть{}, // разбогатеть в деревне
rus_verbs:грохотать{}, // грохотать в мастерской
rus_verbs:реализоваться{}, // реализоваться в должности
rus_verbs:красть{}, // красть в магазине
rus_verbs:нарваться{}, // нарваться в коридоре
rus_verbs:застывать{}, // застывать в неудобной позе
rus_verbs:толкаться{}, // толкаться в тесной комнате
rus_verbs:извлекать{}, // извлекать в аппарате
rus_verbs:обжигать{}, // обжигать в печи
rus_verbs:запечатлеть{}, // запечатлеть в кинохронике
rus_verbs:тренироваться{}, // тренироваться в зале
rus_verbs:поспорить{}, // поспорить в кабинете
rus_verbs:рыскать{}, // рыскать в лесу
rus_verbs:надрываться{}, // надрываться в шахте
rus_verbs:сняться{}, // сняться в фильме
rus_verbs:закружить{}, // закружить в танце
rus_verbs:затонуть{}, // затонуть в порту
rus_verbs:побыть{}, // побыть в гостях
rus_verbs:почистить{}, // почистить в носу
rus_verbs:сгорбиться{}, // сгорбиться в тесной конуре
rus_verbs:подслушивать{}, // подслушивать в классе
rus_verbs:сгорать{}, // сгорать в танке
rus_verbs:разочароваться{}, // разочароваться в артисте
инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать в кустиках
rus_verbs:мять{}, // мять в руках
rus_verbs:подраться{}, // подраться в классе
rus_verbs:замести{}, // замести в прихожей
rus_verbs:откладываться{}, // откладываться в печени
rus_verbs:обозначаться{}, // обозначаться в перечне
rus_verbs:просиживать{}, // просиживать в интернете
rus_verbs:соприкасаться{}, // соприкасаться в точке
rus_verbs:начертить{}, // начертить в тетрадке
rus_verbs:уменьшать{}, // уменьшать в поперечнике
rus_verbs:тормозить{}, // тормозить в облаке
rus_verbs:затевать{}, // затевать в лаборатории
rus_verbs:затопить{}, // затопить в бухте
rus_verbs:задерживать{}, // задерживать в лифте
rus_verbs:прогуляться{}, // прогуляться в лесу
rus_verbs:прорубить{}, // прорубить во льду
rus_verbs:очищать{}, // очищать в кислоте
rus_verbs:полулежать{}, // полулежать в гамаке
rus_verbs:исправить{}, // исправить в задании
rus_verbs:предусматриваться{}, // предусматриваться в постановке задачи
rus_verbs:замучить{}, // замучить в плену
rus_verbs:разрушаться{}, // разрушаться в верхней части
rus_verbs:ерзать{}, // ерзать в кресле
rus_verbs:покопаться{}, // покопаться в залежах
rus_verbs:раскаяться{}, // раскаяться в содеянном
rus_verbs:пробежаться{}, // пробежаться в парке
rus_verbs:полежать{}, // полежать в гамаке
rus_verbs:позаимствовать{}, // позаимствовать в книге
rus_verbs:снижать{}, // снижать в несколько раз
rus_verbs:черпать{}, // черпать в поэзии
rus_verbs:заверять{}, // заверять в своей искренности
rus_verbs:проглядеть{}, // проглядеть в сумерках
rus_verbs:припарковать{}, // припарковать во дворе
rus_verbs:сверлить{}, // сверлить в стене
rus_verbs:здороваться{}, // здороваться в аудитории
rus_verbs:рожать{}, // рожать в воде
rus_verbs:нацарапать{}, // нацарапать в тетрадке
rus_verbs:затопать{}, // затопать в коридоре
rus_verbs:прописать{}, // прописать в правилах
rus_verbs:сориентироваться{}, // сориентироваться в обстоятельствах
rus_verbs:снизить{}, // снизить в несколько раз
rus_verbs:заблуждаться{}, // заблуждаться в своей теории
rus_verbs:откопать{}, // откопать в отвалах
rus_verbs:смастерить{}, // смастерить в лаборатории
rus_verbs:замедлиться{}, // замедлиться в парафине
rus_verbs:избивать{}, // избивать в участке
rus_verbs:мыться{}, // мыться в бане
rus_verbs:сварить{}, // сварить в кастрюльке
rus_verbs:раскопать{}, // раскопать в снегу
rus_verbs:крепиться{}, // крепиться в держателе
rus_verbs:дробить{}, // дробить в мельнице
rus_verbs:попить{}, // попить в ресторанчике
rus_verbs:затронуть{}, // затронуть в душе
rus_verbs:лязгнуть{}, // лязгнуть в тишине
rus_verbs:заправлять{}, // заправлять в полете
rus_verbs:размножаться{}, // размножаться в неволе
rus_verbs:потопить{}, // потопить в Тихом Океане
rus_verbs:кушать{}, // кушать в столовой
rus_verbs:замолкать{}, // замолкать в замешательстве
rus_verbs:измеряться{}, // измеряться в дюймах
rus_verbs:сбываться{}, // сбываться в мечтах
rus_verbs:задернуть{}, // задернуть в комнате
rus_verbs:затихать{}, // затихать в темноте
rus_verbs:прослеживаться{}, // прослеживается в журнале
rus_verbs:прерываться{}, // прерывается в начале
rus_verbs:изображаться{}, // изображается в любых фильмах
rus_verbs:фиксировать{}, // фиксировать в данной точке
rus_verbs:ослаблять{}, // ослаблять в поясе
rus_verbs:зреть{}, // зреть в теплице
rus_verbs:зеленеть{}, // зеленеть в огороде
rus_verbs:критиковать{}, // критиковать в статье
rus_verbs:облететь{}, // облететь в частном вертолете
rus_verbs:разбросать{}, // разбросать в комнате
rus_verbs:заразиться{}, // заразиться в людном месте
rus_verbs:рассеять{}, // рассеять в бою
rus_verbs:печься{}, // печься в духовке
rus_verbs:поспать{}, // поспать в палатке
rus_verbs:заступиться{}, // заступиться в драке
rus_verbs:сплетаться{}, // сплетаться в середине
rus_verbs:поместиться{}, // поместиться в мешке
rus_verbs:спереть{}, // спереть в лавке
// инфинитив:ликвидировать{ вид:несоверш }, глагол:ликвидировать{ вид:несоверш }, // ликвидировать в пригороде
// инфинитив:ликвидировать{ вид:соверш }, глагол:ликвидировать{ вид:соверш },
rus_verbs:проваляться{}, // проваляться в постели
rus_verbs:лечиться{}, // лечиться в стационаре
rus_verbs:определиться{}, // определиться в честном бою
rus_verbs:обработать{}, // обработать в растворе
rus_verbs:пробивать{}, // пробивать в стене
rus_verbs:перемешаться{}, // перемешаться в чане
rus_verbs:чесать{}, // чесать в паху
rus_verbs:пролечь{}, // пролечь в пустынной местности
rus_verbs:скитаться{}, // скитаться в дальних странах
rus_verbs:затрудняться{}, // затрудняться в выборе
rus_verbs:отряхнуться{}, // отряхнуться в коридоре
rus_verbs:разыгрываться{}, // разыгрываться в лотерее
rus_verbs:помолиться{}, // помолиться в церкви
rus_verbs:предписывать{}, // предписывать в рецепте
rus_verbs:порваться{}, // порваться в слабом месте
rus_verbs:греться{}, // греться в здании
rus_verbs:опровергать{}, // опровергать в своем выступлении
rus_verbs:помянуть{}, // помянуть в своем выступлении
rus_verbs:допросить{}, // допросить в прокуратуре
rus_verbs:материализоваться{}, // материализоваться в соседнем здании
rus_verbs:рассеиваться{}, // рассеиваться в воздухе
rus_verbs:перевозить{}, // перевозить в вагоне
rus_verbs:отбывать{}, // отбывать в тюрьме
rus_verbs:попахивать{}, // попахивать в отхожем месте
rus_verbs:перечислять{}, // перечислять в заключении
rus_verbs:зарождаться{}, // зарождаться в дебрях
rus_verbs:предъявлять{}, // предъявлять в своем письме
rus_verbs:распространять{}, // распространять в сети
rus_verbs:пировать{}, // пировать в соседнем селе
rus_verbs:начертать{}, // начертать в летописи
rus_verbs:расцветать{}, // расцветать в подходящих условиях
rus_verbs:царствовать{}, // царствовать в южной части материка
rus_verbs:накопить{}, // накопить в буфере
rus_verbs:закрутиться{}, // закрутиться в рутине
rus_verbs:отработать{}, // отработать в забое
rus_verbs:обокрасть{}, // обокрасть в автобусе
rus_verbs:прокладывать{}, // прокладывать в снегу
rus_verbs:ковырять{}, // ковырять в носу
rus_verbs:копить{}, // копить в очереди
rus_verbs:полечь{}, // полечь в степях
rus_verbs:щебетать{}, // щебетать в кустиках
rus_verbs:подчеркиваться{}, // подчеркиваться в сообщении
rus_verbs:посеять{}, // посеять в огороде
rus_verbs:разъезжать{}, // разъезжать в кабриолете
rus_verbs:замечаться{}, // замечаться в лесу
rus_verbs:просчитать{}, // просчитать в уме
rus_verbs:маяться{}, // маяться в командировке
rus_verbs:выхватывать{}, // выхватывать в тексте
rus_verbs:креститься{}, // креститься в деревенской часовне
rus_verbs:обрабатывать{}, // обрабатывать в растворе кислоты
rus_verbs:настигать{}, // настигать в огороде
rus_verbs:разгуливать{}, // разгуливать в роще
rus_verbs:насиловать{}, // насиловать в квартире
rus_verbs:побороть{}, // побороть в себе
rus_verbs:учитывать{}, // учитывать в расчетах
rus_verbs:искажать{}, // искажать в заметке
rus_verbs:пропить{}, // пропить в кабаке
rus_verbs:катать{}, // катать в лодочке
rus_verbs:припрятать{}, // припрятать в кармашке
rus_verbs:запаниковать{}, // запаниковать в бою
rus_verbs:рассыпать{}, // рассыпать в траве
rus_verbs:застревать{}, // застревать в ограде
rus_verbs:зажигаться{}, // зажигаться в сумерках
rus_verbs:жарить{}, // жарить в масле
rus_verbs:накапливаться{}, // накапливаться в костях
rus_verbs:распуститься{}, // распуститься в горшке
rus_verbs:проголосовать{}, // проголосовать в передвижном пункте
rus_verbs:странствовать{}, // странствовать в автомобиле
rus_verbs:осматриваться{}, // осматриваться в хоромах
rus_verbs:разворачивать{}, // разворачивать в спортзале
rus_verbs:заскучать{}, // заскучать в самолете
rus_verbs:напутать{}, // напутать в расчете
rus_verbs:перекусить{}, // перекусить в столовой
rus_verbs:спасаться{}, // спасаться в автономной капсуле
rus_verbs:посовещаться{}, // посовещаться в комнате
rus_verbs:доказываться{}, // доказываться в статье
rus_verbs:познаваться{}, // познаваться в беде
rus_verbs:загрустить{}, // загрустить в одиночестве
rus_verbs:оживить{}, // оживить в памяти
rus_verbs:переворачиваться{}, // переворачиваться в гробу
rus_verbs:заприметить{}, // заприметить в лесу
rus_verbs:отравиться{}, // отравиться в забегаловке
rus_verbs:продержать{}, // продержать в клетке
rus_verbs:выявить{}, // выявить в костях
rus_verbs:заседать{}, // заседать в совете
rus_verbs:расплачиваться{}, // расплачиваться в первой кассе
rus_verbs:проломить{}, // проломить в двери
rus_verbs:подражать{}, // подражать в мелочах
rus_verbs:подсчитывать{}, // подсчитывать в уме
rus_verbs:опережать{}, // опережать во всем
rus_verbs:сформироваться{}, // сформироваться в облаке
rus_verbs:укрепиться{}, // укрепиться в мнении
rus_verbs:отстоять{}, // отстоять в очереди
rus_verbs:развертываться{}, // развертываться в месте испытания
rus_verbs:замерзать{}, // замерзать во льду
rus_verbs:утопать{}, // утопать в снегу
rus_verbs:раскаиваться{}, // раскаиваться в содеянном
rus_verbs:организовывать{}, // организовывать в пионерлагере
rus_verbs:перевестись{}, // перевестись в наших краях
rus_verbs:смешивать{}, // смешивать в блендере
rus_verbs:ютиться{}, // ютиться в тесной каморке
rus_verbs:прождать{}, // прождать в аудитории
rus_verbs:подыскивать{}, // подыскивать в женском общежитии
rus_verbs:замочить{}, // замочить в сортире
rus_verbs:мерзнуть{}, // мерзнуть в тонкой курточке
rus_verbs:растирать{}, // растирать в ступке
rus_verbs:замедлять{}, // замедлять в парафине
rus_verbs:переспать{}, // переспать в палатке
rus_verbs:рассекать{}, // рассекать в кабриолете
rus_verbs:отыскивать{}, // отыскивать в залежах
rus_verbs:опровергнуть{}, // опровергнуть в своем выступлении
rus_verbs:дрыхнуть{}, // дрыхнуть в гамаке
rus_verbs:укрываться{}, // укрываться в землянке
rus_verbs:запечься{}, // запечься в золе
rus_verbs:догорать{}, // догорать в темноте
rus_verbs:застилать{}, // застилать в коридоре
rus_verbs:сыскаться{}, // сыскаться в деревне
rus_verbs:переделать{}, // переделать в мастерской
rus_verbs:разъяснять{}, // разъяснять в своей лекции
rus_verbs:селиться{}, // селиться в центре
rus_verbs:оплачивать{}, // оплачивать в магазине
rus_verbs:переворачивать{}, // переворачивать в закрытой банке
rus_verbs:упражняться{}, // упражняться в остроумии
rus_verbs:пометить{}, // пометить в списке
rus_verbs:припомниться{}, // припомниться в завещании
rus_verbs:приютить{}, // приютить в амбаре
rus_verbs:натерпеться{}, // натерпеться в темнице
rus_verbs:затеваться{}, // затеваться в клубе
rus_verbs:уплывать{}, // уплывать в лодке
rus_verbs:скиснуть{}, // скиснуть в бидоне
rus_verbs:заколоть{}, // заколоть в боку
rus_verbs:замерцать{}, // замерцать в темноте
rus_verbs:фиксироваться{}, // фиксироваться в протоколе
rus_verbs:запираться{}, // запираться в комнате
rus_verbs:съезжаться{}, // съезжаться в каретах
rus_verbs:толочься{}, // толочься в ступе
rus_verbs:потанцевать{}, // потанцевать в клубе
rus_verbs:побродить{}, // побродить в парке
rus_verbs:назревать{}, // назревать в коллективе
rus_verbs:дохнуть{}, // дохнуть в питомнике
rus_verbs:крестить{}, // крестить в деревенской церквушке
rus_verbs:рассчитаться{}, // рассчитаться в банке
rus_verbs:припарковаться{}, // припарковаться во дворе
rus_verbs:отхватить{}, // отхватить в магазинчике
rus_verbs:остывать{}, // остывать в холодильнике
rus_verbs:составляться{}, // составляться в атмосфере тайны
rus_verbs:переваривать{}, // переваривать в тишине
rus_verbs:хвастать{}, // хвастать в казино
rus_verbs:отрабатывать{}, // отрабатывать в теплице
rus_verbs:разлечься{}, // разлечься в кровати
rus_verbs:прокручивать{}, // прокручивать в голове
rus_verbs:очертить{}, // очертить в воздухе
rus_verbs:сконфузиться{}, // сконфузиться в окружении незнакомых людей
rus_verbs:выявлять{}, // выявлять в боевых условиях
rus_verbs:караулить{}, // караулить в лифте
rus_verbs:расставлять{}, // расставлять в бойницах
rus_verbs:прокрутить{}, // прокрутить в голове
rus_verbs:пересказывать{}, // пересказывать в первой главе
rus_verbs:задавить{}, // задавить в зародыше
rus_verbs:хозяйничать{}, // хозяйничать в холодильнике
rus_verbs:хвалиться{}, // хвалиться в детском садике
rus_verbs:оперировать{}, // оперировать в полевом госпитале
rus_verbs:формулировать{}, // формулировать в следующей главе
rus_verbs:застигнуть{}, // застигнуть в неприглядном виде
rus_verbs:замурлыкать{}, // замурлыкать в тепле
rus_verbs:поддакивать{}, // поддакивать в споре
rus_verbs:прочертить{}, // прочертить в воздухе
rus_verbs:отменять{}, // отменять в городе коменданский час
rus_verbs:колдовать{}, // колдовать в лаборатории
rus_verbs:отвозить{}, // отвозить в машине
rus_verbs:трахать{}, // трахать в гамаке
rus_verbs:повозиться{}, // повозиться в мешке
rus_verbs:ремонтировать{}, // ремонтировать в центре
rus_verbs:робеть{}, // робеть в гостях
rus_verbs:перепробовать{}, // перепробовать в деле
инфинитив:реализовать{ вид:соверш }, инфинитив:реализовать{ вид:несоверш }, // реализовать в новой версии
глагол:реализовать{ вид:соверш }, глагол:реализовать{ вид:несоверш },
rus_verbs:покаяться{}, // покаяться в церкви
rus_verbs:попрыгать{}, // попрыгать в бассейне
rus_verbs:умалчивать{}, // умалчивать в своем докладе
rus_verbs:ковыряться{}, // ковыряться в старой технике
rus_verbs:расписывать{}, // расписывать в деталях
rus_verbs:вязнуть{}, // вязнуть в песке
rus_verbs:погрязнуть{}, // погрязнуть в скандалах
rus_verbs:корениться{}, // корениться в неспособности выполнить поставленную задачу
rus_verbs:зажимать{}, // зажимать в углу
rus_verbs:стискивать{}, // стискивать в ладонях
rus_verbs:практиковаться{}, // практиковаться в приготовлении соуса
rus_verbs:израсходовать{}, // израсходовать в полете
rus_verbs:клокотать{}, // клокотать в жерле
rus_verbs:обвиняться{}, // обвиняться в растрате
rus_verbs:уединиться{}, // уединиться в кладовке
rus_verbs:подохнуть{}, // подохнуть в болоте
rus_verbs:кипятиться{}, // кипятиться в чайнике
rus_verbs:уродиться{}, // уродиться в лесу
rus_verbs:продолжиться{}, // продолжиться в баре
rus_verbs:расшифровать{}, // расшифровать в специальном устройстве
rus_verbs:посапывать{}, // посапывать в кровати
rus_verbs:скрючиться{}, // скрючиться в мешке
rus_verbs:лютовать{}, // лютовать в отдаленных селах
rus_verbs:расписать{}, // расписать в статье
rus_verbs:публиковаться{}, // публиковаться в научном журнале
rus_verbs:зарегистрировать{}, // зарегистрировать в комитете
rus_verbs:прожечь{}, // прожечь в листе
rus_verbs:переждать{}, // переждать в окопе
rus_verbs:публиковать{}, // публиковать в журнале
rus_verbs:морщить{}, // морщить в уголках глаз
rus_verbs:спиться{}, // спиться в одиночестве
rus_verbs:изведать{}, // изведать в гареме
rus_verbs:обмануться{}, // обмануться в ожиданиях
rus_verbs:сочетать{}, // сочетать в себе
rus_verbs:подрабатывать{}, // подрабатывать в магазине
rus_verbs:репетировать{}, // репетировать в студии
rus_verbs:рябить{}, // рябить в глазах
rus_verbs:намочить{}, // намочить в луже
rus_verbs:скатать{}, // скатать в руке
rus_verbs:одевать{}, // одевать в магазине
rus_verbs:испечь{}, // испечь в духовке
rus_verbs:сбрить{}, // сбрить в подмышках
rus_verbs:зажужжать{}, // зажужжать в ухе
rus_verbs:сберечь{}, // сберечь в тайном месте
rus_verbs:согреться{}, // согреться в хижине
инфинитив:дебютировать{ вид:несоверш }, инфинитив:дебютировать{ вид:соверш }, // дебютировать в спектакле
глагол:дебютировать{ вид:несоверш }, глагол:дебютировать{ вид:соверш },
rus_verbs:переплыть{}, // переплыть в лодочке
rus_verbs:передохнуть{}, // передохнуть в тени
rus_verbs:отсвечивать{}, // отсвечивать в зеркалах
rus_verbs:переправляться{}, // переправляться в лодках
rus_verbs:накупить{}, // накупить в магазине
rus_verbs:проторчать{}, // проторчать в очереди
rus_verbs:проскальзывать{}, // проскальзывать в сообщениях
rus_verbs:застукать{}, // застукать в солярии
rus_verbs:наесть{}, // наесть в отпуске
rus_verbs:подвизаться{}, // подвизаться в новом деле
rus_verbs:вычистить{}, // вычистить в саду
rus_verbs:кормиться{}, // кормиться в лесу
rus_verbs:покурить{}, // покурить в саду
rus_verbs:понизиться{}, // понизиться в ранге
rus_verbs:зимовать{}, // зимовать в избушке
rus_verbs:проверяться{}, // проверяться в службе безопасности
rus_verbs:подпирать{}, // подпирать в первом забое
rus_verbs:кувыркаться{}, // кувыркаться в постели
rus_verbs:похрапывать{}, // похрапывать в постели
rus_verbs:завязнуть{}, // завязнуть в песке
rus_verbs:трактовать{}, // трактовать в исследовательской статье
rus_verbs:замедляться{}, // замедляться в тяжелой воде
rus_verbs:шастать{}, // шастать в здании
rus_verbs:заночевать{}, // заночевать в пути
rus_verbs:наметиться{}, // наметиться в исследованиях рака
rus_verbs:освежить{}, // освежить в памяти
rus_verbs:оспаривать{}, // оспаривать в суде
rus_verbs:умещаться{}, // умещаться в ячейке
rus_verbs:искупить{}, // искупить в бою
rus_verbs:отсиживаться{}, // отсиживаться в тылу
rus_verbs:мчать{}, // мчать в кабриолете
rus_verbs:обличать{}, // обличать в своем выступлении
rus_verbs:сгнить{}, // сгнить в тюряге
rus_verbs:опробовать{}, // опробовать в деле
rus_verbs:тренировать{}, // тренировать в зале
rus_verbs:прославить{}, // прославить в академии
rus_verbs:учитываться{}, // учитываться в дипломной работе
rus_verbs:повеселиться{}, // повеселиться в лагере
rus_verbs:поумнеть{}, // поумнеть в карцере
rus_verbs:перестрелять{}, // перестрелять в воздухе
rus_verbs:проведать{}, // проведать в больнице
rus_verbs:измучиться{}, // измучиться в деревне
rus_verbs:прощупать{}, // прощупать в глубине
rus_verbs:изготовлять{}, // изготовлять в сарае
rus_verbs:свирепствовать{}, // свирепствовать в популяции
rus_verbs:иссякать{}, // иссякать в источнике
rus_verbs:гнездиться{}, // гнездиться в дупле
rus_verbs:разогнаться{}, // разогнаться в спортивной машине
rus_verbs:опознавать{}, // опознавать в неизвестном
rus_verbs:засвидетельствовать{}, // засвидетельствовать в суде
rus_verbs:сконцентрировать{}, // сконцентрировать в своих руках
rus_verbs:редактировать{}, // редактировать в редакторе
rus_verbs:покупаться{}, // покупаться в магазине
rus_verbs:промышлять{}, // промышлять в роще
rus_verbs:растягиваться{}, // растягиваться в коридоре
rus_verbs:приобретаться{}, // приобретаться в антикварных лавках
инфинитив:подрезать{ вид:несоверш }, инфинитив:подрезать{ вид:соверш }, // подрезать в воде
глагол:подрезать{ вид:несоверш }, глагол:подрезать{ вид:соверш },
rus_verbs:запечатлеться{}, // запечатлеться в мозгу
rus_verbs:укрывать{}, // укрывать в подвале
rus_verbs:закрепиться{}, // закрепиться в первой башне
rus_verbs:освежать{}, // освежать в памяти
rus_verbs:громыхать{}, // громыхать в ванной
инфинитив:подвигаться{ вид:соверш }, инфинитив:подвигаться{ вид:несоверш }, // подвигаться в кровати
глагол:подвигаться{ вид:соверш }, глагол:подвигаться{ вид:несоверш },
rus_verbs:добываться{}, // добываться в шахтах
rus_verbs:растворить{}, // растворить в кислоте
rus_verbs:приплясывать{}, // приплясывать в гримерке
rus_verbs:доживать{}, // доживать в доме престарелых
rus_verbs:отпраздновать{}, // отпраздновать в ресторане
rus_verbs:сотрясаться{}, // сотрясаться в конвульсиях
rus_verbs:помыть{}, // помыть в проточной воде
инфинитив:увязать{ вид:несоверш }, инфинитив:увязать{ вид:соверш }, // увязать в песке
глагол:увязать{ вид:несоверш }, глагол:увязать{ вид:соверш },
прилагательное:увязавший{ вид:несоверш },
rus_verbs:наличествовать{}, // наличествовать в запаснике
rus_verbs:нащупывать{}, // нащупывать в кармане
rus_verbs:повествоваться{}, // повествоваться в рассказе
rus_verbs:отремонтировать{}, // отремонтировать в техцентре
rus_verbs:покалывать{}, // покалывать в правом боку
rus_verbs:сиживать{}, // сиживать в саду
rus_verbs:разрабатываться{}, // разрабатываться в секретных лабораториях
rus_verbs:укрепляться{}, // укрепляться в мнении
rus_verbs:разниться{}, // разниться во взглядах
rus_verbs:сполоснуть{}, // сполоснуть в водичке
rus_verbs:скупать{}, // скупать в магазине
rus_verbs:почесывать{}, // почесывать в паху
rus_verbs:оформлять{}, // оформлять в конторе
rus_verbs:распускаться{}, // распускаться в садах
rus_verbs:зарябить{}, // зарябить в глазах
rus_verbs:загореть{}, // загореть в Испании
rus_verbs:очищаться{}, // очищаться в баке
rus_verbs:остудить{}, // остудить в холодной воде
rus_verbs:разбомбить{}, // разбомбить в горах
rus_verbs:издохнуть{}, // издохнуть в бедности
rus_verbs:проехаться{}, // проехаться в новой машине
rus_verbs:задействовать{}, // задействовать в анализе
rus_verbs:произрастать{}, // произрастать в степи
rus_verbs:разуться{}, // разуться в прихожей
rus_verbs:сооружать{}, // сооружать в огороде
rus_verbs:зачитывать{}, // зачитывать в суде
rus_verbs:состязаться{}, // состязаться в остроумии
rus_verbs:ополоснуть{}, // ополоснуть в молоке
rus_verbs:уместиться{}, // уместиться в кармане
rus_verbs:совершенствоваться{}, // совершенствоваться в управлении мотоциклом
rus_verbs:стираться{}, // стираться в стиральной машине
rus_verbs:искупаться{}, // искупаться в прохладной реке
rus_verbs:курировать{}, // курировать в правительстве
rus_verbs:закупить{}, // закупить в магазине
rus_verbs:плодиться{}, // плодиться в подходящих условиях
rus_verbs:горланить{}, // горланить в парке
rus_verbs:першить{}, // першить в горле
rus_verbs:пригрезиться{}, // пригрезиться во сне
rus_verbs:исправлять{}, // исправлять в тетрадке
rus_verbs:расслабляться{}, // расслабляться в гамаке
rus_verbs:скапливаться{}, // скапливаться в нижней части
rus_verbs:сплетничать{}, // сплетничают в комнате
rus_verbs:раздевать{}, // раздевать в кабинке
rus_verbs:окопаться{}, // окопаться в лесу
rus_verbs:загорать{}, // загорать в Испании
rus_verbs:подпевать{}, // подпевать в церковном хоре
rus_verbs:прожужжать{}, // прожужжать в динамике
rus_verbs:изучаться{}, // изучаться в дикой природе
rus_verbs:заклубиться{}, // заклубиться в воздухе
rus_verbs:подметать{}, // подметать в зале
rus_verbs:подозреваться{}, // подозреваться в совершении кражи
rus_verbs:обогащать{}, // обогащать в специальном аппарате
rus_verbs:издаться{}, // издаться в другом издательстве
rus_verbs:справить{}, // справить в кустах нужду
rus_verbs:помыться{}, // помыться в бане
rus_verbs:проскакивать{}, // проскакивать в словах
rus_verbs:попивать{}, // попивать в кафе чай
rus_verbs:оформляться{}, // оформляться в регистратуре
rus_verbs:чирикать{}, // чирикать в кустах
rus_verbs:скупить{}, // скупить в магазинах
rus_verbs:переночевать{}, // переночевать в гостинице
rus_verbs:концентрироваться{}, // концентрироваться в пробирке
rus_verbs:одичать{}, // одичать в лесу
rus_verbs:ковырнуть{}, // ковырнуть в ухе
rus_verbs:затеплиться{}, // затеплиться в глубине души
rus_verbs:разгрести{}, // разгрести в задачах залежи
rus_verbs:застопориться{}, // застопориться в начале списка
rus_verbs:перечисляться{}, // перечисляться во введении
rus_verbs:покататься{}, // покататься в парке аттракционов
rus_verbs:изловить{}, // изловить в поле
rus_verbs:прославлять{}, // прославлять в стихах
rus_verbs:промочить{}, // промочить в луже
rus_verbs:поделывать{}, // поделывать в отпуске
rus_verbs:просуществовать{}, // просуществовать в первобытном состоянии
rus_verbs:подстеречь{}, // подстеречь в подъезде
rus_verbs:прикупить{}, // прикупить в магазине
rus_verbs:перемешивать{}, // перемешивать в кастрюле
rus_verbs:тискать{}, // тискать в углу
rus_verbs:купать{}, // купать в теплой водичке
rus_verbs:завариться{}, // завариться в стакане
rus_verbs:притулиться{}, // притулиться в углу
rus_verbs:пострелять{}, // пострелять в тире
rus_verbs:навесить{}, // навесить в больнице
инфинитив:изолировать{ вид:соверш }, инфинитив:изолировать{ вид:несоверш }, // изолировать в камере
глагол:изолировать{ вид:соверш }, глагол:изолировать{ вид:несоверш },
rus_verbs:нежиться{}, // нежится в постельке
rus_verbs:притомиться{}, // притомиться в школе
rus_verbs:раздвоиться{}, // раздвоиться в глазах
rus_verbs:навалить{}, // навалить в углу
rus_verbs:замуровать{}, // замуровать в склепе
rus_verbs:поселяться{}, // поселяться в кроне дуба
rus_verbs:потягиваться{}, // потягиваться в кровати
rus_verbs:укачать{}, // укачать в поезде
rus_verbs:отлеживаться{}, // отлеживаться в гамаке
rus_verbs:разменять{}, // разменять в кассе
rus_verbs:прополоскать{}, // прополоскать в чистой теплой воде
rus_verbs:ржаветь{}, // ржаветь в воде
rus_verbs:уличить{}, // уличить в плагиате
rus_verbs:мутиться{}, // мутиться в голове
rus_verbs:растворять{}, // растворять в бензоле
rus_verbs:двоиться{}, // двоиться в глазах
rus_verbs:оговорить{}, // оговорить в договоре
rus_verbs:подделать{}, // подделать в документе
rus_verbs:зарегистрироваться{}, // зарегистрироваться в социальной сети
rus_verbs:растолстеть{}, // растолстеть в талии
rus_verbs:повоевать{}, // повоевать в городских условиях
rus_verbs:прибраться{}, // гнушаться прибраться в хлеву
rus_verbs:поглощаться{}, // поглощаться в металлической фольге
rus_verbs:ухать{}, // ухать в лесу
rus_verbs:подписываться{}, // подписываться в петиции
rus_verbs:покатать{}, // покатать в машинке
rus_verbs:излечиться{}, // излечиться в клинике
rus_verbs:трепыхаться{}, // трепыхаться в мешке
rus_verbs:кипятить{}, // кипятить в кастрюле
rus_verbs:понастроить{}, // понастроить в прибрежной зоне
rus_verbs:перебывать{}, // перебывать во всех европейских столицах
rus_verbs:оглашать{}, // оглашать в итоговой части
rus_verbs:преуспевать{}, // преуспевать в новом бизнесе
rus_verbs:консультироваться{}, // консультироваться в техподдержке
rus_verbs:накапливать{}, // накапливать в печени
rus_verbs:перемешать{}, // перемешать в контейнере
rus_verbs:наследить{}, // наследить в коридоре
rus_verbs:выявиться{}, // выявиться в результе
rus_verbs:забулькать{}, // забулькать в болоте
rus_verbs:отваривать{}, // отваривать в молоке
rus_verbs:запутываться{}, // запутываться в веревках
rus_verbs:нагреться{}, // нагреться в микроволновой печке
rus_verbs:рыбачить{}, // рыбачить в открытом море
rus_verbs:укорениться{}, // укорениться в сознании широких народных масс
rus_verbs:умывать{}, // умывать в тазике
rus_verbs:защекотать{}, // защекотать в носу
rus_verbs:заходиться{}, // заходиться в плаче
инфинитив:искупать{ вид:соверш }, инфинитив:искупать{ вид:несоверш }, // искупать в прохладной водичке
глагол:искупать{ вид:соверш }, глагол:искупать{ вид:несоверш },
деепричастие:искупав{}, деепричастие:искупая{},
rus_verbs:заморозить{}, // заморозить в холодильнике
rus_verbs:закреплять{}, // закреплять в металлическом держателе
rus_verbs:расхватать{}, // расхватать в магазине
rus_verbs:истязать{}, // истязать в тюремном подвале
rus_verbs:заржаветь{}, // заржаветь во влажной атмосфере
rus_verbs:обжаривать{}, // обжаривать в подсолнечном масле
rus_verbs:умереть{}, // Ты, подлый предатель, умрешь в нищете
rus_verbs:подогреть{}, // подогрей в микроволновке
rus_verbs:подогревать{},
rus_verbs:затянуть{}, // Кузнечики, сверчки, скрипачи и медведки затянули в траве свою трескучую музыку
rus_verbs:проделать{}, // проделать в стене дыру
инфинитив:жениться{ вид:соверш }, // жениться в Техасе
инфинитив:жениться{ вид:несоверш },
глагол:жениться{ вид:соверш },
глагол:жениться{ вид:несоверш },
деепричастие:женившись{},
деепричастие:женясь{},
прилагательное:женатый{},
прилагательное:женившийся{вид:соверш},
прилагательное:женящийся{},
rus_verbs:всхрапнуть{}, // всхрапнуть во сне
rus_verbs:всхрапывать{}, // всхрапывать во сне
rus_verbs:ворочаться{}, // Собака ворочается во сне
rus_verbs:воссоздаваться{}, // воссоздаваться в памяти
rus_verbs:акклиматизироваться{}, // альпинисты готовятся акклиматизироваться в горах
инфинитив:атаковать{ вид:несоверш }, // взвод был атакован в лесу
инфинитив:атаковать{ вид:соверш },
глагол:атаковать{ вид:несоверш },
глагол:атаковать{ вид:соверш },
прилагательное:атакованный{},
прилагательное:атаковавший{},
прилагательное:атакующий{},
инфинитив:аккумулировать{вид:несоверш}, // энергия была аккумулирована в печени
инфинитив:аккумулировать{вид:соверш},
глагол:аккумулировать{вид:несоверш},
глагол:аккумулировать{вид:соверш},
прилагательное:аккумулированный{},
прилагательное:аккумулирующий{},
//прилагательное:аккумулировавший{ вид:несоверш },
прилагательное:аккумулировавший{ вид:соверш },
rus_verbs:врисовывать{}, // врисовывать нового персонажа в анимацию
rus_verbs:вырасти{}, // Он вырос в глазах коллег.
rus_verbs:иметь{}, // Он всегда имел в резерве острое словцо.
rus_verbs:убить{}, // убить в себе зверя
инфинитив:абсорбироваться{ вид:соверш }, // жидкость абсорбируется в поглощающей ткани
инфинитив:абсорбироваться{ вид:несоверш },
глагол:абсорбироваться{ вид:соверш },
глагол:абсорбироваться{ вид:несоверш },
rus_verbs:поставить{}, // поставить в углу
rus_verbs:сжимать{}, // сжимать в кулаке
rus_verbs:готовиться{}, // альпинисты готовятся акклиматизироваться в горах
rus_verbs:аккумулироваться{}, // энергия аккумулируется в жировых отложениях
инфинитив:активизироваться{ вид:несоверш }, // в горах активизировались повстанцы
инфинитив:активизироваться{ вид:соверш },
глагол:активизироваться{ вид:несоверш },
глагол:активизироваться{ вид:соверш },
rus_verbs:апробировать{}, // пилот апробировал в ходе испытаний новый режим планера
rus_verbs:арестовать{}, // наркодилер был арестован в помещении кафе
rus_verbs:базировать{}, // установка будет базирована в лесу
rus_verbs:барахтаться{}, // дети барахтались в воде
rus_verbs:баррикадироваться{}, // преступники баррикадируются в помещении банка
rus_verbs:барствовать{}, // Семен Семенович барствовал в своей деревне
rus_verbs:бесчинствовать{}, // Боевики бесчинствовали в захваченном селе
rus_verbs:блаженствовать{}, // Воробьи блаженствовали в кроне рябины
rus_verbs:блуждать{}, // Туристы блуждали в лесу
rus_verbs:брать{}, // Жена берет деньги в тумбочке
rus_verbs:бродить{}, // парочки бродили в парке
rus_verbs:обойти{}, // Бразилия обошла Россию в рейтинге
rus_verbs:задержать{}, // Знаменитый советский фигурист задержан в США
rus_verbs:бултыхаться{}, // Ноги бултыхаются в воде
rus_verbs:вариться{}, // Курица варится в кастрюле
rus_verbs:закончиться{}, // Эта рецессия закончилась в 2003 году
rus_verbs:прокручиваться{}, // Ключ прокручивается в замке
rus_verbs:прокрутиться{}, // Ключ трижды прокрутился в замке
rus_verbs:храниться{}, // Настройки хранятся в текстовом файле
rus_verbs:сохраняться{}, // Настройки сохраняются в текстовом файле
rus_verbs:витать{}, // Мальчик витает в облаках
rus_verbs:владычествовать{}, // Король владычествует в стране
rus_verbs:властвовать{}, // Олигархи властвовали в стране
rus_verbs:возбудить{}, // возбудить в сердце тоску
rus_verbs:возбуждать{}, // возбуждать в сердце тоску
rus_verbs:возвыситься{}, // возвыситься в глазах современников
rus_verbs:возжечь{}, // возжечь в храме огонь
rus_verbs:возжечься{}, // Огонь возжёгся в храме
rus_verbs:возжигать{}, // возжигать в храме огонь
rus_verbs:возжигаться{}, // Огонь возжигается в храме
rus_verbs:вознамериваться{}, // вознамериваться уйти в монастырь
rus_verbs:вознамериться{}, // вознамериться уйти в монастырь
rus_verbs:возникать{}, // Новые идеи неожиданно возникают в колиной голове
rus_verbs:возникнуть{}, // Новые идейки возникли в голове
rus_verbs:возродиться{}, // возродиться в новом качестве
rus_verbs:возрождать{}, // возрождать в новом качестве
rus_verbs:возрождаться{}, // возрождаться в новом амплуа
rus_verbs:ворошить{}, // ворошить в камине кочергой золу
rus_verbs:воспевать{}, // Поэты воспевают героев в одах
rus_verbs:воспеваться{}, // Герои воспеваются в одах поэтами
rus_verbs:воспеть{}, // Поэты воспели в этой оде героев
rus_verbs:воспретить{}, // воспретить в помещении азартные игры
rus_verbs:восславить{}, // Поэты восславили в одах
rus_verbs:восславлять{}, // Поэты восславляют в одах
rus_verbs:восславляться{}, // Героя восславляются в одах
rus_verbs:воссоздать{}, // воссоздает в памяти образ человека
rus_verbs:воссоздавать{}, // воссоздать в памяти образ человека
rus_verbs:воссоздаться{}, // воссоздаться в памяти
rus_verbs:вскипятить{}, // вскипятить в чайнике воду
rus_verbs:вскипятиться{}, // вскипятиться в чайнике
rus_verbs:встретить{}, // встретить в классе старого приятеля
rus_verbs:встретиться{}, // встретиться в классе
rus_verbs:встречать{}, // встречать в лесу голодного медведя
rus_verbs:встречаться{}, // встречаться в кафе
rus_verbs:выбривать{}, // выбривать что-то в подмышках
rus_verbs:выбрить{}, // выбрить что-то в паху
rus_verbs:вывалять{}, // вывалять кого-то в грязи
rus_verbs:вываляться{}, // вываляться в грязи
rus_verbs:вываривать{}, // вываривать в молоке
rus_verbs:вывариваться{}, // вывариваться в молоке
rus_verbs:выварить{}, // выварить в молоке
rus_verbs:вывариться{}, // вывариться в молоке
rus_verbs:выгрызать{}, // выгрызать в сыре отверствие
rus_verbs:выгрызть{}, // выгрызть в сыре отверстие
rus_verbs:выгуливать{}, // выгуливать в парке собаку
rus_verbs:выгулять{}, // выгулять в парке собаку
rus_verbs:выдолбить{}, // выдолбить в стволе углубление
rus_verbs:выжить{}, // выжить в пустыне
rus_verbs:Выискать{}, // Выискать в программе ошибку
rus_verbs:выискаться{}, // Ошибка выискалась в программе
rus_verbs:выискивать{}, // выискивать в программе ошибку
rus_verbs:выискиваться{}, // выискиваться в программе
rus_verbs:выкраивать{}, // выкраивать в расписании время
rus_verbs:выкраиваться{}, // выкраиваться в расписании
инфинитив:выкупаться{aux stress="в^ыкупаться"}, // выкупаться в озере
глагол:выкупаться{вид:соверш},
rus_verbs:выловить{}, // выловить в пруду
rus_verbs:вымачивать{}, // вымачивать в молоке
rus_verbs:вымачиваться{}, // вымачиваться в молоке
rus_verbs:вынюхивать{}, // вынюхивать в траве следы
rus_verbs:выпачкать{}, // выпачкать в смоле свою одежду
rus_verbs:выпачкаться{}, // выпачкаться в грязи
rus_verbs:вырастить{}, // вырастить в теплице ведро огурчиков
rus_verbs:выращивать{}, // выращивать в теплице помидоры
rus_verbs:выращиваться{}, // выращиваться в теплице
rus_verbs:вырыть{}, // вырыть в земле глубокую яму
rus_verbs:высадить{}, // высадить в пустынной местности
rus_verbs:высадиться{}, // высадиться в пустынной местности
rus_verbs:высаживать{}, // высаживать в пустыне
rus_verbs:высверливать{}, // высверливать в доске отверствие
rus_verbs:высверливаться{}, // высверливаться в стене
rus_verbs:высверлить{}, // высверлить в стене отверствие
rus_verbs:высверлиться{}, // высверлиться в стене
rus_verbs:выскоблить{}, // выскоблить в столешнице канавку
rus_verbs:высматривать{}, // высматривать в темноте
rus_verbs:заметить{}, // заметить в помещении
rus_verbs:оказаться{}, // оказаться в первых рядах
rus_verbs:душить{}, // душить в объятиях
rus_verbs:оставаться{}, // оставаться в классе
rus_verbs:появиться{}, // впервые появиться в фильме
rus_verbs:лежать{}, // лежать в футляре
rus_verbs:раздаться{}, // раздаться в плечах
rus_verbs:ждать{}, // ждать в здании вокзала
rus_verbs:жить{}, // жить в трущобах
rus_verbs:постелить{}, // постелить в прихожей
rus_verbs:оказываться{}, // оказываться в неприятной ситуации
rus_verbs:держать{}, // держать в голове
rus_verbs:обнаружить{}, // обнаружить в себе способность
rus_verbs:начинать{}, // начинать в лаборатории
rus_verbs:рассказывать{}, // рассказывать в лицах
rus_verbs:ожидать{}, // ожидать в помещении
rus_verbs:продолжить{}, // продолжить в помещении
rus_verbs:состоять{}, // состоять в группе
rus_verbs:родиться{}, // родиться в рубашке
rus_verbs:искать{}, // искать в кармане
rus_verbs:иметься{}, // иметься в наличии
rus_verbs:говориться{}, // говориться в среде панков
rus_verbs:клясться{}, // клясться в верности
rus_verbs:узнавать{}, // узнавать в нем своего сына
rus_verbs:признаться{}, // признаться в ошибке
rus_verbs:сомневаться{}, // сомневаться в искренности
rus_verbs:толочь{}, // толочь в ступе
rus_verbs:понадобиться{}, // понадобиться в суде
rus_verbs:служить{}, // служить в пехоте
rus_verbs:потолочь{}, // потолочь в ступе
rus_verbs:появляться{}, // появляться в театре
rus_verbs:сжать{}, // сжать в объятиях
rus_verbs:действовать{}, // действовать в постановке
rus_verbs:селить{}, // селить в гостинице
rus_verbs:поймать{}, // поймать в лесу
rus_verbs:увидать{}, // увидать в толпе
rus_verbs:подождать{}, // подождать в кабинете
rus_verbs:прочесть{}, // прочесть в глазах
rus_verbs:тонуть{}, // тонуть в реке
rus_verbs:ощущать{}, // ощущать в животе
rus_verbs:ошибиться{}, // ошибиться в расчетах
rus_verbs:отметить{}, // отметить в списке
rus_verbs:показывать{}, // показывать в динамике
rus_verbs:скрыться{}, // скрыться в траве
rus_verbs:убедиться{}, // убедиться в корректности
rus_verbs:прозвучать{}, // прозвучать в наушниках
rus_verbs:разговаривать{}, // разговаривать в фойе
rus_verbs:издать{}, // издать в России
rus_verbs:прочитать{}, // прочитать в газете
rus_verbs:попробовать{}, // попробовать в деле
rus_verbs:замечать{}, // замечать в программе ошибку
rus_verbs:нести{}, // нести в руках
rus_verbs:пропасть{}, // пропасть в плену
rus_verbs:носить{}, // носить в кармане
rus_verbs:гореть{}, // гореть в аду
rus_verbs:поправить{}, // поправить в программе
rus_verbs:застыть{}, // застыть в неудобной позе
rus_verbs:получать{}, // получать в кассе
rus_verbs:потребоваться{}, // потребоваться в работе
rus_verbs:спрятать{}, // спрятать в шкафу
rus_verbs:учиться{}, // учиться в институте
rus_verbs:развернуться{}, // развернуться в коридоре
rus_verbs:подозревать{}, // подозревать в мошенничестве
rus_verbs:играть{}, // играть в команде
rus_verbs:сыграть{}, // сыграть в команде
rus_verbs:строить{}, // строить в деревне
rus_verbs:устроить{}, // устроить в доме вечеринку
rus_verbs:находить{}, // находить в лесу
rus_verbs:нуждаться{}, // нуждаться в деньгах
rus_verbs:испытать{}, // испытать в рабочей обстановке
rus_verbs:мелькнуть{}, // мелькнуть в прицеле
rus_verbs:очутиться{}, // очутиться в закрытом помещении
инфинитив:использовать{вид:соверш}, // использовать в работе
инфинитив:использовать{вид:несоверш},
глагол:использовать{вид:несоверш},
глагол:использовать{вид:соверш},
rus_verbs:лететь{}, // лететь в самолете
rus_verbs:смеяться{}, // смеяться в цирке
rus_verbs:ездить{}, // ездить в лимузине
rus_verbs:заснуть{}, // заснуть в неудобной позе
rus_verbs:застать{}, // застать в неформальной обстановке
rus_verbs:очнуться{}, // очнуться в незнакомой обстановке
rus_verbs:твориться{}, // Что творится в закрытой зоне
rus_verbs:разглядеть{}, // разглядеть в темноте
rus_verbs:изучать{}, // изучать в естественных условиях
rus_verbs:удержаться{}, // удержаться в седле
rus_verbs:побывать{}, // побывать в зоопарке
rus_verbs:уловить{}, // уловить в словах нотку отчаяния
rus_verbs:приобрести{}, // приобрести в лавке
rus_verbs:исчезать{}, // исчезать в тумане
rus_verbs:уверять{}, // уверять в своей невиновности
rus_verbs:продолжаться{}, // продолжаться в воздухе
rus_verbs:открывать{}, // открывать в городе новый стадион
rus_verbs:поддержать{}, // поддержать в парке порядок
rus_verbs:солить{}, // солить в бочке
rus_verbs:прожить{}, // прожить в деревне
rus_verbs:создавать{}, // создавать в театре
rus_verbs:обсуждать{}, // обсуждать в коллективе
rus_verbs:заказать{}, // заказать в магазине
rus_verbs:отыскать{}, // отыскать в гараже
rus_verbs:уснуть{}, // уснуть в кресле
rus_verbs:задержаться{}, // задержаться в театре
rus_verbs:подобрать{}, // подобрать в коллекции
rus_verbs:пробовать{}, // пробовать в работе
rus_verbs:курить{}, // курить в закрытом помещении
rus_verbs:устраивать{}, // устраивать в лесу засаду
rus_verbs:установить{}, // установить в багажнике
rus_verbs:запереть{}, // запереть в сарае
rus_verbs:содержать{}, // содержать в достатке
rus_verbs:синеть{}, // синеть в кислородной атмосфере
rus_verbs:слышаться{}, // слышаться в голосе
rus_verbs:закрыться{}, // закрыться в здании
rus_verbs:скрываться{}, // скрываться в квартире
rus_verbs:родить{}, // родить в больнице
rus_verbs:описать{}, // описать в заметках
rus_verbs:перехватить{}, // перехватить в коридоре
rus_verbs:менять{}, // менять в магазине
rus_verbs:скрывать{}, // скрывать в чужой квартире
rus_verbs:стиснуть{}, // стиснуть в стальных объятиях
rus_verbs:останавливаться{}, // останавливаться в гостинице
rus_verbs:мелькать{}, // мелькать в телевизоре
rus_verbs:присутствовать{}, // присутствовать в аудитории
rus_verbs:украсть{}, // украсть в магазине
rus_verbs:победить{}, // победить в войне
rus_verbs:расположиться{}, // расположиться в гостинице
rus_verbs:упомянуть{}, // упомянуть в своей книге
rus_verbs:плыть{}, // плыть в старой бочке
rus_verbs:нащупать{}, // нащупать в глубине
rus_verbs:проявляться{}, // проявляться в работе
rus_verbs:затихнуть{}, // затихнуть в норе
rus_verbs:построить{}, // построить в гараже
rus_verbs:поддерживать{}, // поддерживать в исправном состоянии
rus_verbs:заработать{}, // заработать в стартапе
rus_verbs:сломать{}, // сломать в суставе
rus_verbs:снимать{}, // снимать в гардеробе
rus_verbs:сохранить{}, // сохранить в коллекции
rus_verbs:располагаться{}, // располагаться в отдельном кабинете
rus_verbs:сражаться{}, // сражаться в честном бою
rus_verbs:спускаться{}, // спускаться в батискафе
rus_verbs:уничтожить{}, // уничтожить в схроне
rus_verbs:изучить{}, // изучить в естественных условиях
rus_verbs:рождаться{}, // рождаться в муках
rus_verbs:пребывать{}, // пребывать в прострации
rus_verbs:прилететь{}, // прилететь в аэробусе
rus_verbs:догнать{}, // догнать в переулке
rus_verbs:изобразить{}, // изобразить в танце
rus_verbs:проехать{}, // проехать в легковушке
rus_verbs:убедить{}, // убедить в разумности
rus_verbs:приготовить{}, // приготовить в духовке
rus_verbs:собирать{}, // собирать в лесу
rus_verbs:поплыть{}, // поплыть в катере
rus_verbs:доверять{}, // доверять в управлении
rus_verbs:разобраться{}, // разобраться в законах
rus_verbs:ловить{}, // ловить в озере
rus_verbs:проесть{}, // проесть в куске металла отверстие
rus_verbs:спрятаться{}, // спрятаться в подвале
rus_verbs:провозгласить{}, // провозгласить в речи
rus_verbs:изложить{}, // изложить в своём выступлении
rus_verbs:замяться{}, // замяться в коридоре
rus_verbs:раздаваться{}, // Крик ягуара раздается в джунглях
rus_verbs:доказать{}, // Автор доказал в своей работе, что теорема верна
rus_verbs:хранить{}, // хранить в шкатулке
rus_verbs:шутить{}, // шутить в классе
глагол:рассыпаться{ aux stress="рассып^аться" }, // рассыпаться в извинениях
инфинитив:рассыпаться{ aux stress="рассып^аться" },
rus_verbs:чертить{}, // чертить в тетрадке
rus_verbs:отразиться{}, // отразиться в аттестате
rus_verbs:греть{}, // греть в микроволновке
rus_verbs:зарычать{}, // Кто-то зарычал в глубине леса
rus_verbs:рассуждать{}, // Автор рассуждает в своей статье
rus_verbs:освободить{}, // Обвиняемые были освобождены в зале суда
rus_verbs:окружать{}, // окружать в лесу
rus_verbs:сопровождать{}, // сопровождать в операции
rus_verbs:заканчиваться{}, // заканчиваться в дороге
rus_verbs:поселиться{}, // поселиться в загородном доме
rus_verbs:охватывать{}, // охватывать в хронологии
rus_verbs:запеть{}, // запеть в кино
инфинитив:провозить{вид:несоверш}, // провозить в багаже
глагол:провозить{вид:несоверш},
rus_verbs:мочить{}, // мочить в сортире
rus_verbs:перевернуться{}, // перевернуться в полёте
rus_verbs:улететь{}, // улететь в теплые края
rus_verbs:сдержать{}, // сдержать в руках
rus_verbs:преследовать{}, // преследовать в любой другой стране
rus_verbs:драться{}, // драться в баре
rus_verbs:просидеть{}, // просидеть в классе
rus_verbs:убираться{}, // убираться в квартире
rus_verbs:содрогнуться{}, // содрогнуться в приступе отвращения
rus_verbs:пугать{}, // пугать в прессе
rus_verbs:отреагировать{}, // отреагировать в прессе
rus_verbs:проверять{}, // проверять в аппарате
rus_verbs:убеждать{}, // убеждать в отсутствии альтернатив
rus_verbs:летать{}, // летать в комфортабельном частном самолёте
rus_verbs:толпиться{}, // толпиться в фойе
rus_verbs:плавать{}, // плавать в специальном костюме
rus_verbs:пробыть{}, // пробыть в воде слишком долго
rus_verbs:прикинуть{}, // прикинуть в уме
rus_verbs:застрять{}, // застрять в лифте
rus_verbs:метаться{}, // метаться в кровате
rus_verbs:сжечь{}, // сжечь в печке
rus_verbs:расслабиться{}, // расслабиться в ванной
rus_verbs:услыхать{}, // услыхать в автобусе
rus_verbs:удержать{}, // удержать в вертикальном положении
rus_verbs:образоваться{}, // образоваться в верхних слоях атмосферы
rus_verbs:рассмотреть{}, // рассмотреть в капле воды
rus_verbs:просмотреть{}, // просмотреть в браузере
rus_verbs:учесть{}, // учесть в планах
rus_verbs:уезжать{}, // уезжать в чьей-то машине
rus_verbs:похоронить{}, // похоронить в мерзлой земле
rus_verbs:растянуться{}, // растянуться в расслабленной позе
rus_verbs:обнаружиться{}, // обнаружиться в чужой сумке
rus_verbs:гулять{}, // гулять в парке
rus_verbs:утонуть{}, // утонуть в реке
rus_verbs:зажать{}, // зажать в медвежьих объятиях
rus_verbs:усомниться{}, // усомниться в объективности
rus_verbs:танцевать{}, // танцевать в спортзале
rus_verbs:проноситься{}, // проноситься в голове
rus_verbs:трудиться{}, // трудиться в кооперативе
глагол:засыпать{ aux stress="засып^ать" переходность:непереходный }, // засыпать в спальном мешке
инфинитив:засыпать{ aux stress="засып^ать" переходность:непереходный },
rus_verbs:сушить{}, // сушить в сушильном шкафу
rus_verbs:зашевелиться{}, // зашевелиться в траве
rus_verbs:обдумывать{}, // обдумывать в спокойной обстановке
rus_verbs:промелькнуть{}, // промелькнуть в окне
rus_verbs:поучаствовать{}, // поучаствовать в обсуждении
rus_verbs:закрыть{}, // закрыть в комнате
rus_verbs:запирать{}, // запирать в комнате
rus_verbs:закрывать{}, // закрывать в доме
rus_verbs:заблокировать{}, // заблокировать в доме
rus_verbs:зацвести{}, // В садах зацвела сирень
rus_verbs:кричать{}, // Какое-то животное кричало в ночном лесу.
rus_verbs:поглотить{}, // фотон, поглощенный в рецепторе
rus_verbs:стоять{}, // войска, стоявшие в Риме
rus_verbs:закалить{}, // ветераны, закаленные в боях
rus_verbs:выступать{}, // пришлось выступать в тюрьме.
rus_verbs:выступить{}, // пришлось выступить в тюрьме.
rus_verbs:закопошиться{}, // Мыши закопошились в траве
rus_verbs:воспламениться{}, // смесь, воспламенившаяся в цилиндре
rus_verbs:воспламеняться{}, // смесь, воспламеняющаяся в цилиндре
rus_verbs:закрываться{}, // закрываться в комнате
rus_verbs:провалиться{}, // провалиться в прокате
деепричастие:авторизируясь{ вид:несоверш },
глагол:авторизироваться{ вид:несоверш },
инфинитив:авторизироваться{ вид:несоверш }, // авторизироваться в системе
rus_verbs:существовать{}, // существовать в вакууме
деепричастие:находясь{},
прилагательное:находившийся{},
прилагательное:находящийся{},
глагол:находиться{ вид:несоверш },
инфинитив:находиться{ вид:несоверш }, // находиться в вакууме
rus_verbs:регистрировать{}, // регистрировать в инспекции
глагол:перерегистрировать{ вид:несоверш }, глагол:перерегистрировать{ вид:соверш },
инфинитив:перерегистрировать{ вид:несоверш }, инфинитив:перерегистрировать{ вид:соверш }, // перерегистрировать в инспекции
rus_verbs:поковыряться{}, // поковыряться в носу
rus_verbs:оттаять{}, // оттаять в кипятке
rus_verbs:распинаться{}, // распинаться в проклятиях
rus_verbs:отменить{}, // Министерство связи предлагает отменить внутренний роуминг в России
rus_verbs:столкнуться{}, // Американский эсминец и японский танкер столкнулись в Персидском заливе
rus_verbs:ценить{}, // Он очень ценил в статьях краткость изложения.
прилагательное:несчастный{}, // Он очень несчастен в семейной жизни.
rus_verbs:объясниться{}, // Он объяснился в любви.
прилагательное:нетвердый{}, // Он нетвёрд в истории.
rus_verbs:заниматься{}, // Он занимается в читальном зале.
rus_verbs:вращаться{}, // Он вращается в учёных кругах.
прилагательное:спокойный{}, // Он был спокоен и уверен в завтрашнем дне.
rus_verbs:бегать{}, // Он бегал по городу в поисках квартиры.
rus_verbs:заключать{}, // Письмо заключало в себе очень важные сведения.
rus_verbs:срабатывать{}, // Алгоритм срабатывает в половине случаев.
rus_verbs:специализироваться{}, // мы специализируемся в создании ядерного оружия
rus_verbs:сравниться{}, // Никто не может сравниться с ним в знаниях.
rus_verbs:продолжать{}, // Продолжайте в том же духе.
rus_verbs:говорить{}, // Не говорите об этом в присутствии третьих лиц.
rus_verbs:болтать{}, // Не болтай в присутствии начальника!
rus_verbs:проболтаться{}, // Не проболтайся в присутствии начальника!
rus_verbs:повторить{}, // Он должен повторить свои показания в присутствии свидетелей
rus_verbs:получить{}, // ректор поздравил студентов, получивших в этом семестре повышенную стипендию
rus_verbs:приобретать{}, // Эту еду мы приобретаем в соседнем магазине.
rus_verbs:расходиться{}, // Маша и Петя расходятся во взглядах
rus_verbs:сходиться{}, // Все дороги сходятся в Москве
rus_verbs:убирать{}, // убирать в комнате
rus_verbs:удостоверяться{}, // он удостоверяется в личности специалиста
rus_verbs:уединяться{}, // уединяться в пустыне
rus_verbs:уживаться{}, // уживаться в одном коллективе
rus_verbs:укорять{}, // укорять друга в забывчивости
rus_verbs:читать{}, // он читал об этом в журнале
rus_verbs:состояться{}, // В Израиле состоятся досрочные парламентские выборы
rus_verbs:погибнуть{}, // Список погибших в авиакатастрофе под Ярославлем
rus_verbs:работать{}, // Я работаю в театре.
rus_verbs:признать{}, // Я признал в нём старого друга.
rus_verbs:преподавать{}, // Я преподаю в университете.
rus_verbs:понимать{}, // Я плохо понимаю в живописи.
rus_verbs:водиться{}, // неизвестный науке зверь, который водится в жарких тропических лесах
rus_verbs:разразиться{}, // В Москве разразилась эпидемия гриппа
rus_verbs:замереть{}, // вся толпа замерла в восхищении
rus_verbs:сидеть{}, // Я люблю сидеть в этом удобном кресле.
rus_verbs:идти{}, // Я иду в неопределённом направлении.
rus_verbs:заболеть{}, // Я заболел в дороге.
rus_verbs:ехать{}, // Я еду в автобусе
rus_verbs:взять{}, // Я взял книгу в библиотеке на неделю.
rus_verbs:провести{}, // Юные годы он провёл в Италии.
rus_verbs:вставать{}, // Этот случай живо встаёт в моей памяти.
rus_verbs:возвысить{}, // Это событие возвысило его в общественном мнении.
rus_verbs:произойти{}, // Это произошло в одном городе в Японии.
rus_verbs:привидеться{}, // Это мне привиделось во сне.
rus_verbs:держаться{}, // Это дело держится в большом секрете.
rus_verbs:привиться{}, // Это выражение не привилось в русском языке.
rus_verbs:восстановиться{}, // Эти писатели восстановились в правах.
rus_verbs:быть{}, // Эта книга есть в любом книжном магазине.
прилагательное:популярный{}, // Эта идея очень популярна в массах.
rus_verbs:шуметь{}, // Шумит в голове.
rus_verbs:остаться{}, // Шляпа осталась в поезде.
rus_verbs:выражаться{}, // Характер писателя лучше всего выражается в его произведениях.
rus_verbs:воспитать{}, // Учительница воспитала в детях любовь к природе.
rus_verbs:пересохнуть{}, // У меня в горле пересохло.
rus_verbs:щекотать{}, // У меня в горле щекочет.
rus_verbs:колоть{}, // У меня в боку колет.
прилагательное:свежий{}, // Событие ещё свежо в памяти.
rus_verbs:собрать{}, // Соберите всех учеников во дворе.
rus_verbs:белеть{}, // Снег белеет в горах.
rus_verbs:сделать{}, // Сколько орфографических ошибок ты сделал в диктанте?
rus_verbs:таять{}, // Сахар тает в кипятке.
rus_verbs:жать{}, // Сапог жмёт в подъёме.
rus_verbs:возиться{}, // Ребята возятся в углу.
rus_verbs:распоряжаться{}, // Прошу не распоряжаться в чужом доме.
rus_verbs:кружиться{}, // Они кружились в вальсе.
rus_verbs:выставлять{}, // Они выставляют его в смешном виде.
rus_verbs:бывать{}, // Она часто бывает в обществе.
rus_verbs:петь{}, // Она поёт в опере.
rus_verbs:сойтись{}, // Все свидетели сошлись в своих показаниях.
rus_verbs:валяться{}, // Вещи валялись в беспорядке.
rus_verbs:пройти{}, // Весь день прошёл в беготне.
rus_verbs:продавать{}, // В этом магазине продают обувь.
rus_verbs:заключаться{}, // В этом заключается вся сущность.
rus_verbs:звенеть{}, // В ушах звенит.
rus_verbs:проступить{}, // В тумане проступили очертания корабля.
rus_verbs:бить{}, // В саду бьёт фонтан.
rus_verbs:проскользнуть{}, // В речи проскользнул упрёк.
rus_verbs:оставить{}, // Не оставь товарища в опасности.
rus_verbs:прогулять{}, // Мы прогуляли час в парке.
rus_verbs:перебить{}, // Мы перебили врагов в бою.
rus_verbs:остановиться{}, // Мы остановились в первой попавшейся гостинице.
rus_verbs:видеть{}, // Он многое видел в жизни.
// глагол:проходить{ вид:несоверш }, // Беседа проходила в дружественной атмосфере.
rus_verbs:подать{}, // Автор подал своих героев в реалистических тонах.
rus_verbs:кинуть{}, // Он кинул меня в беде.
rus_verbs:приходить{}, // Приходи в сентябре
rus_verbs:воскрешать{}, // воскрешать в памяти
rus_verbs:соединять{}, // соединять в себе
rus_verbs:разбираться{}, // умение разбираться в вещах
rus_verbs:делать{}, // В её комнате делали обыск.
rus_verbs:воцариться{}, // В зале воцарилась глубокая тишина.
rus_verbs:начаться{}, // В деревне начались полевые работы.
rus_verbs:блеснуть{}, // В голове блеснула хорошая мысль.
rus_verbs:вертеться{}, // В голове вертится вчерашний разговор.
rus_verbs:веять{}, // В воздухе веет прохладой.
rus_verbs:висеть{}, // В воздухе висит зной.
rus_verbs:носиться{}, // В воздухе носятся комары.
rus_verbs:грести{}, // Грести в спокойной воде будет немного легче, но скучнее
rus_verbs:воскресить{}, // воскресить в памяти
rus_verbs:поплавать{}, // поплавать в 100-метровом бассейне
rus_verbs:пострадать{}, // В массовой драке пострадал 23-летний мужчина
прилагательное:уверенный{ причастие }, // Она уверена в своих силах.
прилагательное:постоянный{}, // Она постоянна во вкусах.
прилагательное:сильный{}, // Он не силён в математике.
прилагательное:повинный{}, // Он не повинен в этом.
прилагательное:возможный{}, // Ураганы, сильные грозы и даже смерчи возможны в конце периода сильной жары
rus_verbs:вывести{}, // способный летать над землей крокодил был выведен в секретной лаборатории
прилагательное:нужный{}, // сковородка тоже нужна в хозяйстве.
rus_verbs:сесть{}, // Она села в тени
rus_verbs:заливаться{}, // в нашем парке заливаются соловьи
rus_verbs:разнести{}, // В лесу огонь пожара мгновенно разнесло
rus_verbs:чувствоваться{}, // В тёплом, но сыром воздухе остро чувствовалось дыхание осени
// rus_verbs:расти{}, // дерево, растущее в лесу
rus_verbs:происходить{}, // что происходит в поликлиннике
rus_verbs:спать{}, // кто спит в моей кровати
rus_verbs:мыть{}, // мыть машину в саду
ГЛ_ИНФ(царить), // В воздухе царило безмолвие
ГЛ_ИНФ(мести), // мести в прихожей пол
ГЛ_ИНФ(прятать), // прятать в яме
ГЛ_ИНФ(увидеть), прилагательное:увидевший{}, деепричастие:увидев{}, // увидел периодическую таблицу элементов во сне.
// ГЛ_ИНФ(собраться), // собраться в порту
ГЛ_ИНФ(случиться), // что-то случилось в больнице
ГЛ_ИНФ(зажечься), // в небе зажглись звёзды
ГЛ_ИНФ(купить), // купи молока в магазине
прилагательное:пропагандировавшийся{} // группа студентов университета дружбы народов, активно пропагандировавшейся в СССР
}
// Чтобы разрешить связывание в паттернах типа: пообедать в macdonalds
fact гл_предл
{
if context { Гл_В_Предл предлог:в{} @regex("[a-z]+[0-9]*") }
then return true
}
fact гл_предл
{
if context { Гл_В_Предл предлог:в{} *:*{ падеж:предл } }
then return true
}
// С локативом:
// собраться в порту
fact гл_предл
{
if context { Гл_В_Предл предлог:в{} существительное:*{ падеж:мест } }
then return true
}
#endregion Предложный
#region Винительный
// Для глаголов движения с выраженным направлением действия может присоединяться
// предложный паттерн с винительным падежом.
wordentry_set Гл_В_Вин =
{
rus_verbs:вдавиться{}, // Дуло больно вдавилось в позвонок.
глагол:ввергнуть{}, // Двух прелестнейших дам он ввергнул в горе.
глагол:ввергать{},
инфинитив:ввергнуть{},
инфинитив:ввергать{},
rus_verbs:двинуться{}, // Двинулись в путь и мы.
rus_verbs:сплавать{}, // Сплавать в Россию!
rus_verbs:уложиться{}, // Уложиться в воскресенье.
rus_verbs:спешить{}, // Спешите в Лондон
rus_verbs:кинуть{}, // Киньте в море.
rus_verbs:проситься{}, // Просилась в Никарагуа.
rus_verbs:притопать{}, // Притопал в Будапешт.
rus_verbs:скататься{}, // Скатался в Красноярск.
rus_verbs:соскользнуть{}, // Соскользнул в пике.
rus_verbs:соскальзывать{},
rus_verbs:играть{}, // Играл в дутье.
глагол:айда{}, // Айда в каморы.
rus_verbs:отзывать{}, // Отзывали в Москву...
rus_verbs:сообщаться{}, // Сообщается в Лондон.
rus_verbs:вдуматься{}, // Вдумайтесь в них.
rus_verbs:проехать{}, // Проехать в Лунево...
rus_verbs:спрыгивать{}, // Спрыгиваем в него.
rus_verbs:верить{}, // Верю в вас!
rus_verbs:прибыть{}, // Прибыл в Подмосковье.
rus_verbs:переходить{}, // Переходите в школу.
rus_verbs:доложить{}, // Доложили в Москву.
rus_verbs:подаваться{}, // Подаваться в Россию?
rus_verbs:спрыгнуть{}, // Спрыгнул в него.
rus_verbs:вывезти{}, // Вывезли в Китай.
rus_verbs:пропихивать{}, // Я очень аккуратно пропихивал дуло в ноздрю.
rus_verbs:пропихнуть{},
rus_verbs:транспортироваться{},
rus_verbs:закрадываться{}, // в голову начали закрадываться кое-какие сомнения и подозрения
rus_verbs:дуть{},
rus_verbs:БОГАТЕТЬ{}, //
rus_verbs:РАЗБОГАТЕТЬ{}, //
rus_verbs:ВОЗРАСТАТЬ{}, //
rus_verbs:ВОЗРАСТИ{}, //
rus_verbs:ПОДНЯТЬ{}, // Он поднял половинку самолета в воздух и на всей скорости повел ее к горам. (ПОДНЯТЬ)
rus_verbs:ОТКАТИТЬСЯ{}, // Услышав за спиной дыхание, он прыгнул вперед и откатился в сторону, рассчитывая ускользнуть от врага, нападавшего сзади (ОТКАТИТЬСЯ)
rus_verbs:ВПЛЕТАТЬСЯ{}, // В общий смрад вплеталось зловонье пены, летевшей из пастей, и крови из легких (ВПЛЕТАТЬСЯ)
rus_verbs:ЗАМАНИТЬ{}, // Они подумали, что Павел пытается заманить их в зону обстрела. (ЗАМАНИТЬ,ЗАМАНИВАТЬ)
rus_verbs:ЗАМАНИВАТЬ{},
rus_verbs:ПРОТРУБИТЬ{}, // Эти врата откроются, когда он протрубит в рог, и пропустят его в другую вселенную. (ПРОТРУБИТЬ)
rus_verbs:ВРУБИТЬСЯ{}, // Клинок сломался, не врубившись в металл. (ВРУБИТЬСЯ/ВРУБАТЬСЯ)
rus_verbs:ВРУБАТЬСЯ{},
rus_verbs:ОТПРАВИТЬ{}, // Мы ищем благородного вельможу, который нанял бы нас или отправил в рыцарский поиск. (ОТПРАВИТЬ)
rus_verbs:ОБЛАЧИТЬ{}, // Этот был облачен в сверкавшие красные доспехи с опущенным забралом и держал огромное копье, дожидаясь своей очереди. (ОБЛАЧИТЬ/ОБЛАЧАТЬ/ОБЛАЧИТЬСЯ/ОБЛАЧАТЬСЯ/НАРЯДИТЬСЯ/НАРЯЖАТЬСЯ)
rus_verbs:ОБЛАЧАТЬ{},
rus_verbs:ОБЛАЧИТЬСЯ{},
rus_verbs:ОБЛАЧАТЬСЯ{},
rus_verbs:НАРЯДИТЬСЯ{},
rus_verbs:НАРЯЖАТЬСЯ{},
rus_verbs:ЗАХВАТИТЬ{}, // Кроме набранного рабского материала обычного типа, он захватил в плен группу очень странных созданий, а также женщину исключительной красоты (ЗАХВАТИТЬ/ЗАХВАТЫВАТЬ/ЗАХВАТ)
rus_verbs:ЗАХВАТЫВАТЬ{},
rus_verbs:ПРОВЕСТИ{}, // Он провел их в маленькое святилище позади штурвала. (ПРОВЕСТИ)
rus_verbs:ПОЙМАТЬ{}, // Их можно поймать в ловушку (ПОЙМАТЬ)
rus_verbs:СТРОИТЬСЯ{}, // На вершине они остановились, строясь в круг. (СТРОИТЬСЯ,ПОСТРОИТЬСЯ,ВЫСТРОИТЬСЯ)
rus_verbs:ПОСТРОИТЬСЯ{},
rus_verbs:ВЫСТРОИТЬСЯ{},
rus_verbs:ВЫПУСТИТЬ{}, // Несколько стрел, выпущенных в преследуемых, вонзились в траву (ВЫПУСТИТЬ/ВЫПУСКАТЬ)
rus_verbs:ВЫПУСКАТЬ{},
rus_verbs:ВЦЕПЛЯТЬСЯ{}, // Они вцепляются тебе в горло. (ВЦЕПЛЯТЬСЯ/ВЦЕПИТЬСЯ)
rus_verbs:ВЦЕПИТЬСЯ{},
rus_verbs:ПАЛЬНУТЬ{}, // Вольф вставил в тетиву новую стрелу и пальнул в белое брюхо (ПАЛЬНУТЬ)
rus_verbs:ОТСТУПИТЬ{}, // Вольф отступил в щель. (ОТСТУПИТЬ/ОТСТУПАТЬ)
rus_verbs:ОТСТУПАТЬ{},
rus_verbs:КРИКНУТЬ{}, // Вольф крикнул в ответ и медленно отступил от птицы. (КРИКНУТЬ)
rus_verbs:ДЫХНУТЬ{}, // В лицо ему дыхнули винным перегаром. (ДЫХНУТЬ)
rus_verbs:ПОТРУБИТЬ{}, // Я видел рог во время своих скитаний по дворцу и даже потрубил в него (ПОТРУБИТЬ)
rus_verbs:ОТКРЫВАТЬСЯ{}, // Некоторые врата открывались в другие вселенные (ОТКРЫВАТЬСЯ)
rus_verbs:ТРУБИТЬ{}, // А я трубил в рог (ТРУБИТЬ)
rus_verbs:ПЫРНУТЬ{}, // Вольф пырнул его в бок. (ПЫРНУТЬ)
rus_verbs:ПРОСКРЕЖЕТАТЬ{}, // Тот что-то проскрежетал в ответ, а затем наорал на него. (ПРОСКРЕЖЕТАТЬ В вин, НАОРАТЬ НА вин)
rus_verbs:ИМПОРТИРОВАТЬ{}, // импортировать товары двойного применения только в Российскую Федерацию (ИМПОРТИРОВАТЬ)
rus_verbs:ОТЪЕХАТЬ{}, // Легкий грохот катков заглушил рог, когда дверь отъехала в сторону. (ОТЪЕХАТЬ)
rus_verbs:ПОПЛЕСТИСЬ{}, // Подобрав нижнее белье, носки и ботинки, он поплелся по песку обратно в джунгли. (ПОПЛЕЛСЯ)
rus_verbs:СЖАТЬСЯ{}, // Желудок у него сжался в кулак. (СЖАТЬСЯ, СЖИМАТЬСЯ)
rus_verbs:СЖИМАТЬСЯ{},
rus_verbs:проверять{}, // Школьников будут принудительно проверять на курение
rus_verbs:ПОТЯНУТЬ{}, // Я потянул его в кино (ПОТЯНУТЬ)
rus_verbs:ПЕРЕВЕСТИ{}, // Премьер-министр Казахстана поручил до конца года перевести все социально-значимые услуги в электронный вид (ПЕРЕВЕСТИ)
rus_verbs:КРАСИТЬ{}, // Почему китайские партийные боссы красят волосы в черный цвет? (КРАСИТЬ/ПОКРАСИТЬ/ПЕРЕКРАСИТЬ/ОКРАСИТЬ/ЗАКРАСИТЬ)
rus_verbs:ПОКРАСИТЬ{}, //
rus_verbs:ПЕРЕКРАСИТЬ{}, //
rus_verbs:ОКРАСИТЬ{}, //
rus_verbs:ЗАКРАСИТЬ{}, //
rus_verbs:СООБЩИТЬ{}, // Мужчина ранил человека в щеку и сам сообщил об этом в полицию (СООБЩИТЬ)
rus_verbs:СТЯГИВАТЬ{}, // Но толщина пузыря постоянно меняется из-за гравитации, которая стягивает жидкость в нижнюю часть (СТЯГИВАТЬ/СТЯНУТЬ/ЗАТЯНУТЬ/ВТЯНУТЬ)
rus_verbs:СТЯНУТЬ{}, //
rus_verbs:ЗАТЯНУТЬ{}, //
rus_verbs:ВТЯНУТЬ{}, //
rus_verbs:СОХРАНИТЬ{}, // сохранить данные в файл (СОХРАНИТЬ)
деепричастие:придя{}, // Немного придя в себя
rus_verbs:наблюдать{}, // Судья , долго наблюдавший в трубу , вдруг вскричал
rus_verbs:УЛЫБАТЬСЯ{}, // она улыбалась во весь рот (УЛЫБАТЬСЯ)
rus_verbs:МЕТНУТЬСЯ{}, // она метнулась обратно во тьму (МЕТНУТЬСЯ)
rus_verbs:ПОСЛЕДОВАТЬ{}, // большинство жителей города последовало за ним во дворец (ПОСЛЕДОВАТЬ)
rus_verbs:ПЕРЕМЕЩАТЬСЯ{}, // экстремисты перемещаются из лесов в Сеть (ПЕРЕМЕЩАТЬСЯ)
rus_verbs:ВЫТАЩИТЬ{}, // Алексей позволил вытащить себя через дверь во тьму (ВЫТАЩИТЬ)
rus_verbs:СЫПАТЬСЯ{}, // внизу под ними камни градом сыпались во двор (СЫПАТЬСЯ)
rus_verbs:выезжать{}, // заключенные сами шьют куклы и иногда выезжают с представлениями в детский дом неподалеку
rus_verbs:КРИЧАТЬ{}, // ей хотелось кричать во весь голос (КРИЧАТЬ В вин)
rus_verbs:ВЫПРЯМИТЬСЯ{}, // волк выпрямился во весь огромный рост (ВЫПРЯМИТЬСЯ В вин)
rus_verbs:спрятать{}, // Джон спрятал очки во внутренний карман (спрятать в вин)
rus_verbs:ЭКСТРАДИРОВАТЬ{}, // Украина экстрадирует в Таджикистан задержанного бывшего премьер-министра (ЭКСТРАДИРОВАТЬ В вин)
rus_verbs:ВВОЗИТЬ{}, // лабораторный мониторинг ввозимой в Россию мясной продукции из США (ВВОЗИТЬ В вин)
rus_verbs:УПАКОВАТЬ{}, // упакованных в несколько слоев полиэтилена (УПАКОВАТЬ В вин)
rus_verbs:ОТТЯГИВАТЬ{}, // использовать естественную силу гравитации, оттягивая объекты в сторону и изменяя их орбиту (ОТТЯГИВАТЬ В вин)
rus_verbs:ПОЗВОНИТЬ{}, // они позвонили в отдел экологии городской администрации (ПОЗВОНИТЬ В)
rus_verbs:ПРИВЛЕЧЬ{}, // Открытость данных о лесе поможет привлечь инвестиции в отрасль (ПРИВЛЕЧЬ В)
rus_verbs:ЗАПРОСИТЬСЯ{}, // набегавшись и наплясавшись, Стасик утомился и запросился в кроватку (ЗАПРОСИТЬСЯ В)
rus_verbs:ОТСТАВИТЬ{}, // бутыль с ацетоном Витька отставил в сторонку (ОТСТАВИТЬ В)
rus_verbs:ИСПОЛЬЗОВАТЬ{}, // ты использовал свою магию во зло. (ИСПОЛЬЗОВАТЬ В вин)
rus_verbs:ВЫСЕВАТЬ{}, // В апреле редис возможно уже высевать в грунт (ВЫСЕВАТЬ В)
rus_verbs:ЗАГНАТЬ{}, // Американский психолог загнал любовь в три угла (ЗАГНАТЬ В)
rus_verbs:ЭВОЛЮЦИОНИРОВАТЬ{}, // Почему не все обезьяны эволюционировали в человека? (ЭВОЛЮЦИОНИРОВАТЬ В вин)
rus_verbs:СФОТОГРАФИРОВАТЬСЯ{}, // Он сфотографировался во весь рост. (СФОТОГРАФИРОВАТЬСЯ В)
rus_verbs:СТАВИТЬ{}, // Он ставит мне в упрёк свою ошибку. (СТАВИТЬ В)
rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА)
rus_verbs:ПЕРЕСЕЛЯТЬСЯ{}, // Греки переселяются в Германию (ПЕРЕСЕЛЯТЬСЯ В)
rus_verbs:ФОРМИРОВАТЬСЯ{}, // Сахарная свекла относится к двулетним растениям, мясистый корнеплод формируется в первый год. (ФОРМИРОВАТЬСЯ В)
rus_verbs:ПРОВОРЧАТЬ{}, // дедуля что-то проворчал в ответ (ПРОВОРЧАТЬ В)
rus_verbs:БУРКНУТЬ{}, // нелюдимый парень что-то буркнул в ответ (БУРКНУТЬ В)
rus_verbs:ВЕСТИ{}, // дверь вела во тьму. (ВЕСТИ В)
rus_verbs:ВЫСКОЧИТЬ{}, // беглецы выскочили во двор. (ВЫСКОЧИТЬ В)
rus_verbs:ДОСЫЛАТЬ{}, // Одним движением стрелок досылает патрон в ствол (ДОСЫЛАТЬ В)
rus_verbs:СЪЕХАТЬСЯ{}, // Финалисты съехались на свои игры в Лос-Анжелес. (СЪЕХАТЬСЯ НА, В)
rus_verbs:ВЫТЯНУТЬ{}, // Дым вытянуло в трубу. (ВЫТЯНУТЬ В)
rus_verbs:торчать{}, // острые обломки бревен торчали во все стороны.
rus_verbs:ОГЛЯДЫВАТЬ{}, // Она оглядывает себя в зеркало. (ОГЛЯДЫВАТЬ В)
rus_verbs:ДЕЙСТВОВАТЬ{}, // Этот пакет законов действует в ущерб частным предпринимателям.
rus_verbs:РАЗЛЕТЕТЬСЯ{}, // люди разлетелись во все стороны. (РАЗЛЕТЕТЬСЯ В)
rus_verbs:брызнуть{}, // во все стороны брызнула кровь. (брызнуть в)
rus_verbs:ТЯНУТЬСЯ{}, // провода тянулись во все углы. (ТЯНУТЬСЯ В)
rus_verbs:валить{}, // валить все в одну кучу (валить в)
rus_verbs:выдвинуть{}, // его выдвинули в палату представителей (выдвинуть в)
rus_verbs:карабкаться{}, // карабкаться в гору (карабкаться в)
rus_verbs:клониться{}, // он клонился в сторону (клониться в)
rus_verbs:командировать{}, // мы командировали нашего представителя в Рим (командировать в)
rus_verbs:запасть{}, // Эти слова запали мне в душу.
rus_verbs:давать{}, // В этой лавке дают в долг?
rus_verbs:ездить{}, // Каждый день грузовик ездит в город.
rus_verbs:претвориться{}, // Замысел претворился в жизнь.
rus_verbs:разойтись{}, // Они разошлись в разные стороны.
rus_verbs:выйти{}, // Охотник вышел в поле с ружьём.
rus_verbs:отозвать{}, // Отзовите его в сторону и скажите ему об этом.
rus_verbs:расходиться{}, // Маша и Петя расходятся в разные стороны
rus_verbs:переодеваться{}, // переодеваться в женское платье
rus_verbs:перерастать{}, // перерастать в массовые беспорядки
rus_verbs:завязываться{}, // завязываться в узел
rus_verbs:похватать{}, // похватать в руки
rus_verbs:увлечь{}, // увлечь в прогулку по парку
rus_verbs:помещать{}, // помещать в изолятор
rus_verbs:зыркнуть{}, // зыркнуть в окошко
rus_verbs:закатать{}, // закатать в асфальт
rus_verbs:усаживаться{}, // усаживаться в кресло
rus_verbs:загонять{}, // загонять в сарай
rus_verbs:подбрасывать{}, // подбрасывать в воздух
rus_verbs:телеграфировать{}, // телеграфировать в центр
rus_verbs:вязать{}, // вязать в стопы
rus_verbs:подлить{}, // подлить в огонь
rus_verbs:заполучить{}, // заполучить в распоряжение
rus_verbs:подогнать{}, // подогнать в док
rus_verbs:ломиться{}, // ломиться в открытую дверь
rus_verbs:переправить{}, // переправить в деревню
rus_verbs:затягиваться{}, // затягиваться в трубу
rus_verbs:разлетаться{}, // разлетаться в стороны
rus_verbs:кланяться{}, // кланяться в ножки
rus_verbs:устремляться{}, // устремляться в открытое море
rus_verbs:переместиться{}, // переместиться в другую аудиторию
rus_verbs:ложить{}, // ложить в ящик
rus_verbs:отвозить{}, // отвозить в аэропорт
rus_verbs:напрашиваться{}, // напрашиваться в гости
rus_verbs:напроситься{}, // напроситься в гости
rus_verbs:нагрянуть{}, // нагрянуть в гости
rus_verbs:заворачивать{}, // заворачивать в фольгу
rus_verbs:заковать{}, // заковать в кандалы
rus_verbs:свезти{}, // свезти в сарай
rus_verbs:притащиться{}, // притащиться в дом
rus_verbs:завербовать{}, // завербовать в разведку
rus_verbs:рубиться{}, // рубиться в компьютерные игры
rus_verbs:тыкаться{}, // тыкаться в материнскую грудь
инфинитив:ссыпать{ вид:несоверш }, инфинитив:ссыпать{ вид:соверш }, // ссыпать в контейнер
глагол:ссыпать{ вид:несоверш }, глагол:ссыпать{ вид:соверш },
деепричастие:ссыпав{}, деепричастие:ссыпая{},
rus_verbs:засасывать{}, // засасывать в себя
rus_verbs:скакнуть{}, // скакнуть в будущее
rus_verbs:подвозить{}, // подвозить в театр
rus_verbs:переиграть{}, // переиграть в покер
rus_verbs:мобилизовать{}, // мобилизовать в действующую армию
rus_verbs:залетать{}, // залетать в закрытое воздушное пространство
rus_verbs:подышать{}, // подышать в трубочку
rus_verbs:смотаться{}, // смотаться в институт
rus_verbs:рассовать{}, // рассовать в кармашки
rus_verbs:захаживать{}, // захаживать в дом
инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять в ломбард
деепричастие:сгоняя{},
rus_verbs:посылаться{}, // посылаться в порт
rus_verbs:отлить{}, // отлить в кастрюлю
rus_verbs:преобразоваться{}, // преобразоваться в линейное уравнение
rus_verbs:поплакать{}, // поплакать в платочек
rus_verbs:обуться{}, // обуться в сапоги
rus_verbs:закапать{}, // закапать в глаза
инфинитив:свозить{ вид:несоверш }, инфинитив:свозить{ вид:соверш }, // свозить в центр утилизации
глагол:свозить{ вид:несоверш }, глагол:свозить{ вид:соверш },
деепричастие:свозив{}, деепричастие:свозя{},
rus_verbs:преобразовать{}, // преобразовать в линейное уравнение
rus_verbs:кутаться{}, // кутаться в плед
rus_verbs:смещаться{}, // смещаться в сторону
rus_verbs:зазывать{}, // зазывать в свой магазин
инфинитив:трансформироваться{ вид:несоверш }, инфинитив:трансформироваться{ вид:соверш }, // трансформироваться в комбинезон
глагол:трансформироваться{ вид:несоверш }, глагол:трансформироваться{ вид:соверш },
деепричастие:трансформируясь{}, деепричастие:трансформировавшись{},
rus_verbs:погружать{}, // погружать в кипящее масло
rus_verbs:обыграть{}, // обыграть в теннис
rus_verbs:закутать{}, // закутать в одеяло
rus_verbs:изливаться{}, // изливаться в воду
rus_verbs:закатывать{}, // закатывать в асфальт
rus_verbs:мотнуться{}, // мотнуться в банк
rus_verbs:избираться{}, // избираться в сенат
rus_verbs:наниматься{}, // наниматься в услужение
rus_verbs:настучать{}, // настучать в органы
rus_verbs:запихивать{}, // запихивать в печку
rus_verbs:закапывать{}, // закапывать в нос
rus_verbs:засобираться{}, // засобираться в поход
rus_verbs:копировать{}, // копировать в другую папку
rus_verbs:замуровать{}, // замуровать в стену
rus_verbs:упечь{}, // упечь в тюрьму
rus_verbs:зрить{}, // зрить в корень
rus_verbs:стягиваться{}, // стягиваться в одну точку
rus_verbs:усаживать{}, // усаживать в тренажер
rus_verbs:протолкнуть{}, // протолкнуть в отверстие
rus_verbs:расшибиться{}, // расшибиться в лепешку
rus_verbs:приглашаться{}, // приглашаться в кабинет
rus_verbs:садить{}, // садить в телегу
rus_verbs:уткнуть{}, // уткнуть в подушку
rus_verbs:протечь{}, // протечь в подвал
rus_verbs:перегнать{}, // перегнать в другую страну
rus_verbs:переползти{}, // переползти в тень
rus_verbs:зарываться{}, // зарываться в грунт
rus_verbs:переодеть{}, // переодеть в сухую одежду
rus_verbs:припуститься{}, // припуститься в пляс
rus_verbs:лопотать{}, // лопотать в микрофон
rus_verbs:прогнусавить{}, // прогнусавить в микрофон
rus_verbs:мочиться{}, // мочиться в штаны
rus_verbs:загружать{}, // загружать в патронник
rus_verbs:радировать{}, // радировать в центр
rus_verbs:промотать{}, // промотать в конец
rus_verbs:помчать{}, // помчать в школу
rus_verbs:съезжать{}, // съезжать в кювет
rus_verbs:завозить{}, // завозить в магазин
rus_verbs:заявляться{}, // заявляться в школу
rus_verbs:наглядеться{}, // наглядеться в зеркало
rus_verbs:сворачиваться{}, // сворачиваться в клубочек
rus_verbs:устремлять{}, // устремлять взор в будущее
rus_verbs:забредать{}, // забредать в глухие уголки
rus_verbs:перемотать{}, // перемотать в самое начало диалога
rus_verbs:сморкаться{}, // сморкаться в носовой платочек
rus_verbs:перетекать{}, // перетекать в другой сосуд
rus_verbs:закачать{}, // закачать в шарик
rus_verbs:запрятать{}, // запрятать в сейф
rus_verbs:пинать{}, // пинать в живот
rus_verbs:затрубить{}, // затрубить в горн
rus_verbs:подглядывать{}, // подглядывать в замочную скважину
инфинитив:подсыпать{ вид:соверш }, инфинитив:подсыпать{ вид:несоверш }, // подсыпать в питье
глагол:подсыпать{ вид:соверш }, глагол:подсыпать{ вид:несоверш },
деепричастие:подсыпав{}, деепричастие:подсыпая{},
rus_verbs:засовывать{}, // засовывать в пенал
rus_verbs:отрядить{}, // отрядить в командировку
rus_verbs:справлять{}, // справлять в кусты
rus_verbs:поторапливаться{}, // поторапливаться в самолет
rus_verbs:скопировать{}, // скопировать в кэш
rus_verbs:подливать{}, // подливать в огонь
rus_verbs:запрячь{}, // запрячь в повозку
rus_verbs:окраситься{}, // окраситься в пурпур
rus_verbs:уколоть{}, // уколоть в шею
rus_verbs:слететься{}, // слететься в гнездо
rus_verbs:резаться{}, // резаться в карты
rus_verbs:затесаться{}, // затесаться в ряды оппозиционеров
инфинитив:задвигать{ вид:несоверш }, глагол:задвигать{ вид:несоверш }, // задвигать в ячейку (несоверш)
деепричастие:задвигая{},
rus_verbs:доставляться{}, // доставляться в ресторан
rus_verbs:поплевать{}, // поплевать в чашку
rus_verbs:попереться{}, // попереться в магазин
rus_verbs:хаживать{}, // хаживать в церковь
rus_verbs:преображаться{}, // преображаться в королеву
rus_verbs:организоваться{}, // организоваться в группу
rus_verbs:ужалить{}, // ужалить в руку
rus_verbs:протискиваться{}, // протискиваться в аудиторию
rus_verbs:препроводить{}, // препроводить в закуток
rus_verbs:разъезжаться{}, // разъезжаться в разные стороны
rus_verbs:пропыхтеть{}, // пропыхтеть в трубку
rus_verbs:уволочь{}, // уволочь в нору
rus_verbs:отодвигаться{}, // отодвигаться в сторону
rus_verbs:разливать{}, // разливать в стаканы
rus_verbs:сбегаться{}, // сбегаться в актовый зал
rus_verbs:наведаться{}, // наведаться в кладовку
rus_verbs:перекочевать{}, // перекочевать в горы
rus_verbs:прощебетать{}, // прощебетать в трубку
rus_verbs:перекладывать{}, // перекладывать в другой карман
rus_verbs:углубляться{}, // углубляться в теорию
rus_verbs:переименовать{}, // переименовать в город
rus_verbs:переметнуться{}, // переметнуться в лагерь противника
rus_verbs:разносить{}, // разносить в щепки
rus_verbs:осыпаться{}, // осыпаться в холода
rus_verbs:попроситься{}, // попроситься в туалет
rus_verbs:уязвить{}, // уязвить в сердце
rus_verbs:перетащить{}, // перетащить в дом
rus_verbs:закутаться{}, // закутаться в плед
// rus_verbs:упаковать{}, // упаковать в бумагу
инфинитив:тикать{ aux stress="тик^ать" }, глагол:тикать{ aux stress="тик^ать" }, // тикать в крепость
rus_verbs:хихикать{}, // хихикать в кулачок
rus_verbs:объединить{}, // объединить в сеть
инфинитив:слетать{ вид:соверш }, глагол:слетать{ вид:соверш }, // слетать в Калифорнию
деепричастие:слетав{},
rus_verbs:заползти{}, // заползти в норку
rus_verbs:перерасти{}, // перерасти в крупную аферу
rus_verbs:списать{}, // списать в утиль
rus_verbs:просачиваться{}, // просачиваться в бункер
rus_verbs:пускаться{}, // пускаться в погоню
rus_verbs:согревать{}, // согревать в мороз
rus_verbs:наливаться{}, // наливаться в емкость
rus_verbs:унестись{}, // унестись в небо
rus_verbs:зашвырнуть{}, // зашвырнуть в шкаф
rus_verbs:сигануть{}, // сигануть в воду
rus_verbs:окунуть{}, // окунуть в ледяную воду
rus_verbs:просочиться{}, // просочиться в сапог
rus_verbs:соваться{}, // соваться в толпу
rus_verbs:протолкаться{}, // протолкаться в гардероб
rus_verbs:заложить{}, // заложить в ломбард
rus_verbs:перекатить{}, // перекатить в сарай
rus_verbs:поставлять{}, // поставлять в Китай
rus_verbs:залезать{}, // залезать в долги
rus_verbs:отлучаться{}, // отлучаться в туалет
rus_verbs:сбиваться{}, // сбиваться в кучу
rus_verbs:зарыть{}, // зарыть в землю
rus_verbs:засадить{}, // засадить в тело
rus_verbs:прошмыгнуть{}, // прошмыгнуть в дверь
rus_verbs:переставить{}, // переставить в шкаф
rus_verbs:отчалить{}, // отчалить в плавание
rus_verbs:набираться{}, // набираться в команду
rus_verbs:лягнуть{}, // лягнуть в живот
rus_verbs:притворить{}, // притворить в жизнь
rus_verbs:проковылять{}, // проковылять в гардероб
rus_verbs:прикатить{}, // прикатить в гараж
rus_verbs:залететь{}, // залететь в окно
rus_verbs:переделать{}, // переделать в мопед
rus_verbs:протащить{}, // протащить в совет
rus_verbs:обмакнуть{}, // обмакнуть в воду
rus_verbs:отклоняться{}, // отклоняться в сторону
rus_verbs:запихать{}, // запихать в пакет
rus_verbs:избирать{}, // избирать в совет
rus_verbs:загрузить{}, // загрузить в буфер
rus_verbs:уплывать{}, // уплывать в Париж
rus_verbs:забивать{}, // забивать в мерзлоту
rus_verbs:потыкать{}, // потыкать в безжизненную тушу
rus_verbs:съезжаться{}, // съезжаться в санаторий
rus_verbs:залепить{}, // залепить в рыло
rus_verbs:набиться{}, // набиться в карманы
rus_verbs:уползти{}, // уползти в нору
rus_verbs:упрятать{}, // упрятать в камеру
rus_verbs:переместить{}, // переместить в камеру анабиоза
rus_verbs:закрасться{}, // закрасться в душу
rus_verbs:сместиться{}, // сместиться в инфракрасную область
rus_verbs:запускать{}, // запускать в серию
rus_verbs:потрусить{}, // потрусить в чащобу
rus_verbs:забрасывать{}, // забрасывать в чистую воду
rus_verbs:переселить{}, // переселить в отдаленную деревню
rus_verbs:переезжать{}, // переезжать в новую квартиру
rus_verbs:приподнимать{}, // приподнимать в воздух
rus_verbs:добавиться{}, // добавиться в конец очереди
rus_verbs:убыть{}, // убыть в часть
rus_verbs:передвигать{}, // передвигать в соседнюю клетку
rus_verbs:добавляться{}, // добавляться в очередь
rus_verbs:дописать{}, // дописать в перечень
rus_verbs:записываться{}, // записываться в кружок
rus_verbs:продаться{}, // продаться в кредитное рабство
rus_verbs:переписывать{}, // переписывать в тетрадку
rus_verbs:заплыть{}, // заплыть в территориальные воды
инфинитив:пописать{ aux stress="поп^исать" }, инфинитив:пописать{ aux stress="попис^ать" }, // пописать в горшок
глагол:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="попис^ать" },
rus_verbs:отбирать{}, // отбирать в гвардию
rus_verbs:нашептывать{}, // нашептывать в микрофон
rus_verbs:ковылять{}, // ковылять в стойло
rus_verbs:прилетать{}, // прилетать в Париж
rus_verbs:пролиться{}, // пролиться в канализацию
rus_verbs:запищать{}, // запищать в микрофон
rus_verbs:подвезти{}, // подвезти в больницу
rus_verbs:припереться{}, // припереться в театр
rus_verbs:утечь{}, // утечь в сеть
rus_verbs:прорываться{}, // прорываться в буфет
rus_verbs:увозить{}, // увозить в ремонт
rus_verbs:съедать{}, // съедать в обед
rus_verbs:просунуться{}, // просунуться в дверь
rus_verbs:перенестись{}, // перенестись в прошлое
rus_verbs:завезти{}, // завезти в магазин
rus_verbs:проложить{}, // проложить в деревню
rus_verbs:объединяться{}, // объединяться в профсоюз
rus_verbs:развиться{}, // развиться в бабочку
rus_verbs:засеменить{}, // засеменить в кабинку
rus_verbs:скатываться{}, // скатываться в яму
rus_verbs:завозиться{}, // завозиться в магазин
rus_verbs:нанимать{}, // нанимать в рейс
rus_verbs:поспеть{}, // поспеть в класс
rus_verbs:кидаться{}, // кинаться в крайности
rus_verbs:поспевать{}, // поспевать в оперу
rus_verbs:обернуть{}, // обернуть в фольгу
rus_verbs:обратиться{}, // обратиться в прокуратуру
rus_verbs:истолковать{}, // истолковать в свою пользу
rus_verbs:таращиться{}, // таращиться в дисплей
rus_verbs:прыснуть{}, // прыснуть в кулачок
rus_verbs:загнуть{}, // загнуть в другую сторону
rus_verbs:раздать{}, // раздать в разные руки
rus_verbs:назначить{}, // назначить в приемную комиссию
rus_verbs:кидать{}, // кидать в кусты
rus_verbs:увлекать{}, // увлекать в лес
rus_verbs:переселиться{}, // переселиться в чужое тело
rus_verbs:присылать{}, // присылать в город
rus_verbs:уплыть{}, // уплыть в Европу
rus_verbs:запричитать{}, // запричитать в полный голос
rus_verbs:утащить{}, // утащить в логово
rus_verbs:завернуться{}, // завернуться в плед
rus_verbs:заносить{}, // заносить в блокнот
rus_verbs:пятиться{}, // пятиться в дом
rus_verbs:наведываться{}, // наведываться в больницу
rus_verbs:нырять{}, // нырять в прорубь
rus_verbs:зачастить{}, // зачастить в бар
rus_verbs:назначаться{}, // назначается в комиссию
rus_verbs:мотаться{}, // мотаться в областной центр
rus_verbs:разыграть{}, // разыграть в карты
rus_verbs:пропищать{}, // пропищать в микрофон
rus_verbs:пихнуть{}, // пихнуть в бок
rus_verbs:эмигрировать{}, // эмигрировать в Канаду
rus_verbs:подключить{}, // подключить в сеть
rus_verbs:упереть{}, // упереть в фундамент
rus_verbs:уплатить{}, // уплатить в кассу
rus_verbs:потащиться{}, // потащиться в медпункт
rus_verbs:пригнать{}, // пригнать в стойло
rus_verbs:оттеснить{}, // оттеснить в фойе
rus_verbs:стучаться{}, // стучаться в ворота
rus_verbs:перечислить{}, // перечислить в фонд
rus_verbs:сомкнуть{}, // сомкнуть в круг
rus_verbs:закачаться{}, // закачаться в резервуар
rus_verbs:кольнуть{}, // кольнуть в бок
rus_verbs:накрениться{}, // накрениться в сторону берега
rus_verbs:подвинуться{}, // подвинуться в другую сторону
rus_verbs:разнести{}, // разнести в клочья
rus_verbs:отливать{}, // отливать в форму
rus_verbs:подкинуть{}, // подкинуть в карман
rus_verbs:уводить{}, // уводить в кабинет
rus_verbs:ускакать{}, // ускакать в школу
rus_verbs:ударять{}, // ударять в барабаны
rus_verbs:даться{}, // даться в руки
rus_verbs:поцеловаться{}, // поцеловаться в губы
rus_verbs:посветить{}, // посветить в подвал
rus_verbs:тыкать{}, // тыкать в арбуз
rus_verbs:соединяться{}, // соединяться в кольцо
rus_verbs:растянуть{}, // растянуть в тонкую ниточку
rus_verbs:побросать{}, // побросать в пыль
rus_verbs:стукнуться{}, // стукнуться в закрытую дверь
rus_verbs:проигрывать{}, // проигрывать в теннис
rus_verbs:дунуть{}, // дунуть в трубочку
rus_verbs:улетать{}, // улетать в Париж
rus_verbs:переводиться{}, // переводиться в филиал
rus_verbs:окунуться{}, // окунуться в водоворот событий
rus_verbs:попрятаться{}, // попрятаться в норы
rus_verbs:перевезти{}, // перевезти в соседнюю палату
rus_verbs:топать{}, // топать в школу
rus_verbs:относить{}, // относить в помещение
rus_verbs:укладывать{}, // укладывать в стопку
rus_verbs:укатить{}, // укатил в турне
rus_verbs:убирать{}, // убирать в сумку
rus_verbs:помалкивать{}, // помалкивать в тряпочку
rus_verbs:ронять{}, // ронять в грязь
rus_verbs:глазеть{}, // глазеть в бинокль
rus_verbs:преобразиться{}, // преобразиться в другого человека
rus_verbs:запрыгнуть{}, // запрыгнуть в поезд
rus_verbs:сгодиться{}, // сгодиться в суп
rus_verbs:проползти{}, // проползти в нору
rus_verbs:забираться{}, // забираться в коляску
rus_verbs:сбежаться{}, // сбежались в класс
rus_verbs:закатиться{}, // закатиться в угол
rus_verbs:плевать{}, // плевать в душу
rus_verbs:поиграть{}, // поиграть в демократию
rus_verbs:кануть{}, // кануть в небытие
rus_verbs:опаздывать{}, // опаздывать в школу
rus_verbs:отползти{}, // отползти в сторону
rus_verbs:стекаться{}, // стекаться в отстойник
rus_verbs:запихнуть{}, // запихнуть в пакет
rus_verbs:вышвырнуть{}, // вышвырнуть в коридор
rus_verbs:связываться{}, // связываться в плотный узел
rus_verbs:затолкать{}, // затолкать в ухо
rus_verbs:скрутить{}, // скрутить в трубочку
rus_verbs:сворачивать{}, // сворачивать в трубочку
rus_verbs:сплестись{}, // сплестись в узел
rus_verbs:заскочить{}, // заскочить в кабинет
rus_verbs:проваливаться{}, // проваливаться в сон
rus_verbs:уверовать{}, // уверовать в свою безнаказанность
rus_verbs:переписать{}, // переписать в тетрадку
rus_verbs:переноситься{}, // переноситься в мир фантазий
rus_verbs:заводить{}, // заводить в помещение
rus_verbs:сунуться{}, // сунуться в аудиторию
rus_verbs:устраиваться{}, // устраиваться в автомастерскую
rus_verbs:пропускать{}, // пропускать в зал
инфинитив:сбегать{ вид:несоверш }, инфинитив:сбегать{ вид:соверш }, // сбегать в кино
глагол:сбегать{ вид:несоверш }, глагол:сбегать{ вид:соверш },
деепричастие:сбегая{}, деепричастие:сбегав{},
rus_verbs:прибегать{}, // прибегать в школу
rus_verbs:съездить{}, // съездить в лес
rus_verbs:захлопать{}, // захлопать в ладошки
rus_verbs:опрокинуться{}, // опрокинуться в грязь
инфинитив:насыпать{ вид:несоверш }, инфинитив:насыпать{ вид:соверш }, // насыпать в стакан
глагол:насыпать{ вид:несоверш }, глагол:насыпать{ вид:соверш },
деепричастие:насыпая{}, деепричастие:насыпав{},
rus_verbs:употреблять{}, // употреблять в пищу
rus_verbs:приводиться{}, // приводиться в действие
rus_verbs:пристроить{}, // пристроить в надежные руки
rus_verbs:юркнуть{}, // юркнуть в нору
rus_verbs:объединиться{}, // объединиться в банду
rus_verbs:сажать{}, // сажать в одиночку
rus_verbs:соединить{}, // соединить в кольцо
rus_verbs:забрести{}, // забрести в кафешку
rus_verbs:свернуться{}, // свернуться в клубочек
rus_verbs:пересесть{}, // пересесть в другой автобус
rus_verbs:постучаться{}, // постучаться в дверцу
rus_verbs:соединять{}, // соединять в кольцо
rus_verbs:приволочь{}, // приволочь в коморку
rus_verbs:смахивать{}, // смахивать в ящик стола
rus_verbs:забежать{}, // забежать в помещение
rus_verbs:целиться{}, // целиться в беглеца
rus_verbs:прокрасться{}, // прокрасться в хранилище
rus_verbs:заковылять{}, // заковылять в травтамологию
rus_verbs:прискакать{}, // прискакать в стойло
rus_verbs:колотить{}, // колотить в дверь
rus_verbs:смотреться{}, // смотреться в зеркало
rus_verbs:подложить{}, // подложить в салон
rus_verbs:пущать{}, // пущать в королевские покои
rus_verbs:согнуть{}, // согнуть в дугу
rus_verbs:забарабанить{}, // забарабанить в дверь
rus_verbs:отклонить{}, // отклонить в сторону посадочной полосы
rus_verbs:убраться{}, // убраться в специальную нишу
rus_verbs:насмотреться{}, // насмотреться в зеркало
rus_verbs:чмокнуть{}, // чмокнуть в щечку
rus_verbs:усмехаться{}, // усмехаться в бороду
rus_verbs:передвинуть{}, // передвинуть в конец очереди
rus_verbs:допускаться{}, // допускаться в опочивальню
rus_verbs:задвинуть{}, // задвинуть в дальний угол
rus_verbs:отправлять{}, // отправлять в центр
rus_verbs:сбрасывать{}, // сбрасывать в жерло
rus_verbs:расстреливать{}, // расстреливать в момент обнаружения
rus_verbs:заволочь{}, // заволочь в закуток
rus_verbs:пролить{}, // пролить в воду
rus_verbs:зарыться{}, // зарыться в сено
rus_verbs:переливаться{}, // переливаться в емкость
rus_verbs:затащить{}, // затащить в клуб
rus_verbs:перебежать{}, // перебежать в лагерь врагов
rus_verbs:одеть{}, // одеть в новое платье
инфинитив:задвигаться{ вид:несоверш }, глагол:задвигаться{ вид:несоверш }, // задвигаться в нишу
деепричастие:задвигаясь{},
rus_verbs:клюнуть{}, // клюнуть в темечко
rus_verbs:наливать{}, // наливать в кружку
rus_verbs:пролезть{}, // пролезть в ушко
rus_verbs:откладывать{}, // откладывать в ящик
rus_verbs:протянуться{}, // протянуться в соседний дом
rus_verbs:шлепнуться{}, // шлепнуться лицом в грязь
rus_verbs:устанавливать{}, // устанавливать в машину
rus_verbs:употребляться{}, // употребляться в пищу
rus_verbs:переключиться{}, // переключиться в реверсный режим
rus_verbs:пискнуть{}, // пискнуть в микрофон
rus_verbs:заявиться{}, // заявиться в класс
rus_verbs:налиться{}, // налиться в стакан
rus_verbs:заливать{}, // заливать в бак
rus_verbs:ставиться{}, // ставиться в очередь
инфинитив:писаться{ aux stress="п^исаться" }, глагол:писаться{ aux stress="п^исаться" }, // писаться в штаны
деепричастие:писаясь{},
rus_verbs:целоваться{}, // целоваться в губы
rus_verbs:наносить{}, // наносить в область сердца
rus_verbs:посмеяться{}, // посмеяться в кулачок
rus_verbs:употребить{}, // употребить в пищу
rus_verbs:прорваться{}, // прорваться в столовую
rus_verbs:укладываться{}, // укладываться в ровные стопки
rus_verbs:пробиться{}, // пробиться в финал
rus_verbs:забить{}, // забить в землю
rus_verbs:переложить{}, // переложить в другой карман
rus_verbs:опускать{}, // опускать в свежевырытую могилу
rus_verbs:поторопиться{}, // поторопиться в школу
rus_verbs:сдвинуться{}, // сдвинуться в сторону
rus_verbs:капать{}, // капать в смесь
rus_verbs:погружаться{}, // погружаться во тьму
rus_verbs:направлять{}, // направлять в кабинку
rus_verbs:погрузить{}, // погрузить во тьму
rus_verbs:примчаться{}, // примчаться в школу
rus_verbs:упираться{}, // упираться в дверь
rus_verbs:удаляться{}, // удаляться в комнату совещаний
rus_verbs:ткнуться{}, // ткнуться в окошко
rus_verbs:убегать{}, // убегать в чащу
rus_verbs:соединиться{}, // соединиться в необычную пространственную фигуру
rus_verbs:наговорить{}, // наговорить в микрофон
rus_verbs:переносить{}, // переносить в дом
rus_verbs:прилечь{}, // прилечь в кроватку
rus_verbs:поворачивать{}, // поворачивать в обратную сторону
rus_verbs:проскочить{}, // проскочить в щель
rus_verbs:совать{}, // совать в духовку
rus_verbs:переодеться{}, // переодеться в чистую одежду
rus_verbs:порвать{}, // порвать в лоскуты
rus_verbs:завязать{}, // завязать в бараний рог
rus_verbs:съехать{}, // съехать в кювет
rus_verbs:литься{}, // литься в канистру
rus_verbs:уклониться{}, // уклониться в левую сторону
rus_verbs:смахнуть{}, // смахнуть в мусорное ведро
rus_verbs:спускать{}, // спускать в шахту
rus_verbs:плеснуть{}, // плеснуть в воду
rus_verbs:подуть{}, // подуть в угольки
rus_verbs:набирать{}, // набирать в команду
rus_verbs:хлопать{}, // хлопать в ладошки
rus_verbs:ранить{}, // ранить в самое сердце
rus_verbs:посматривать{}, // посматривать в иллюминатор
rus_verbs:превращать{}, // превращать воду в вино
rus_verbs:толкать{}, // толкать в пучину
rus_verbs:отбыть{}, // отбыть в расположение части
rus_verbs:сгрести{}, // сгрести в карман
rus_verbs:удрать{}, // удрать в тайгу
rus_verbs:пристроиться{}, // пристроиться в хорошую фирму
rus_verbs:сбиться{}, // сбиться в плотную группу
rus_verbs:заключать{}, // заключать в объятия
rus_verbs:отпускать{}, // отпускать в поход
rus_verbs:устремить{}, // устремить взгляд в будущее
rus_verbs:обронить{}, // обронить в траву
rus_verbs:сливаться{}, // сливаться в речку
rus_verbs:стекать{}, // стекать в канаву
rus_verbs:свалить{}, // свалить в кучу
rus_verbs:подтянуть{}, // подтянуть в кабину
rus_verbs:скатиться{}, // скатиться в канаву
rus_verbs:проскользнуть{}, // проскользнуть в приоткрытую дверь
rus_verbs:заторопиться{}, // заторопиться в буфет
rus_verbs:протиснуться{}, // протиснуться в центр толпы
rus_verbs:прятать{}, // прятать в укромненькое местечко
rus_verbs:пропеть{}, // пропеть в микрофон
rus_verbs:углубиться{}, // углубиться в джунгли
rus_verbs:сползти{}, // сползти в яму
rus_verbs:записывать{}, // записывать в память
rus_verbs:расстрелять{}, // расстрелять в упор (наречный оборот В УПОР)
rus_verbs:колотиться{}, // колотиться в дверь
rus_verbs:просунуть{}, // просунуть в отверстие
rus_verbs:провожать{}, // провожать в армию
rus_verbs:катить{}, // катить в гараж
rus_verbs:поражать{}, // поражать в самое сердце
rus_verbs:отлететь{}, // отлететь в дальний угол
rus_verbs:закинуть{}, // закинуть в речку
rus_verbs:катиться{}, // катиться в пропасть
rus_verbs:забросить{}, // забросить в дальний угол
rus_verbs:отвезти{}, // отвезти в лагерь
rus_verbs:втопить{}, // втопить педаль в пол
rus_verbs:втапливать{}, // втапливать педать в пол
rus_verbs:утопить{}, // утопить кнопку в панель
rus_verbs:напасть{}, // В Пекине участники антияпонских протестов напали на машину посла США
rus_verbs:нанять{}, // Босс нанял в службу поддержки еще несколько девушек
rus_verbs:переводить{}, // переводить в устойчивую к перегреву форму
rus_verbs:баллотировать{}, // претендент был баллотирован в жюри (баллотирован?)
rus_verbs:вбухать{}, // Власти вбухали в этой проект много денег
rus_verbs:вбухивать{}, // Власти вбухивают в этот проект очень много денег
rus_verbs:поскакать{}, // поскакать в атаку
rus_verbs:прицелиться{}, // прицелиться в бегущего зайца
rus_verbs:прыгать{}, // прыгать в кровать
rus_verbs:приглашать{}, // приглашать в дом
rus_verbs:понестись{}, // понестись в ворота
rus_verbs:заехать{}, // заехать в гаражный бокс
rus_verbs:опускаться{}, // опускаться в бездну
rus_verbs:переехать{}, // переехать в коттедж
rus_verbs:поместить{}, // поместить в карантин
rus_verbs:ползти{}, // ползти в нору
rus_verbs:добавлять{}, // добавлять в корзину
rus_verbs:уткнуться{}, // уткнуться в подушку
rus_verbs:продавать{}, // продавать в рабство
rus_verbs:спрятаться{}, // Белка спрячется в дупло.
rus_verbs:врисовывать{}, // врисовывать новый персонаж в анимацию
rus_verbs:воткнуть{}, // воткни вилку в розетку
rus_verbs:нести{}, // нести в больницу
rus_verbs:воткнуться{}, // вилка воткнулась в сочную котлетку
rus_verbs:впаивать{}, // впаивать деталь в плату
rus_verbs:впаиваться{}, // деталь впаивается в плату
rus_verbs:впархивать{}, // впархивать в помещение
rus_verbs:впаять{}, // впаять деталь в плату
rus_verbs:впендюривать{}, // впендюривать штукенцию в агрегат
rus_verbs:впендюрить{}, // впендюрить штукенцию в агрегат
rus_verbs:вперивать{}, // вперивать взгляд в экран
rus_verbs:впериваться{}, // впериваться в экран
rus_verbs:вперить{}, // вперить взгляд в экран
rus_verbs:впериться{}, // впериться в экран
rus_verbs:вперять{}, // вперять взгляд в экран
rus_verbs:вперяться{}, // вперяться в экран
rus_verbs:впечатать{}, // впечатать текст в первую главу
rus_verbs:впечататься{}, // впечататься в стену
rus_verbs:впечатывать{}, // впечатывать текст в первую главу
rus_verbs:впечатываться{}, // впечатываться в стену
rus_verbs:впиваться{}, // Хищник впивается в жертву мощными зубами
rus_verbs:впитаться{}, // Жидкость впиталась в ткань
rus_verbs:впитываться{}, // Жидкость впитывается в ткань
rus_verbs:впихивать{}, // Мама впихивает в сумку кусок колбасы
rus_verbs:впихиваться{}, // Кусок колбасы впихивается в сумку
rus_verbs:впихнуть{}, // Мама впихнула кастрюлю в холодильник
rus_verbs:впихнуться{}, // Кастрюля впихнулась в холодильник
rus_verbs:вплавиться{}, // Провод вплавился в плату
rus_verbs:вплеснуть{}, // вплеснуть краситель в бак
rus_verbs:вплести{}, // вплести ленту в волосы
rus_verbs:вплестись{}, // вплестись в волосы
rus_verbs:вплетать{}, // вплетать ленты в волосы
rus_verbs:вплывать{}, // корабль вплывает в порт
rus_verbs:вплыть{}, // яхта вплыла в бухту
rus_verbs:вползать{}, // дракон вползает в пещеру
rus_verbs:вползти{}, // дракон вполз в свою пещеру
rus_verbs:впорхнуть{}, // бабочка впорхнула в окно
rus_verbs:впрессовать{}, // впрессовать деталь в плиту
rus_verbs:впрессоваться{}, // впрессоваться в плиту
rus_verbs:впрессовывать{}, // впрессовывать деталь в плиту
rus_verbs:впрессовываться{}, // впрессовываться в плиту
rus_verbs:впрыгивать{}, // Пассажир впрыгивает в вагон
rus_verbs:впрыгнуть{}, // Пассажир впрыгнул в вагон
rus_verbs:впрыскивать{}, // Форсунка впрыскивает топливо в цилиндр
rus_verbs:впрыскиваться{}, // Топливо впрыскивается форсункой в цилиндр
rus_verbs:впрыснуть{}, // Форсунка впрыснула топливную смесь в камеру сгорания
rus_verbs:впрягать{}, // впрягать лошадь в телегу
rus_verbs:впрягаться{}, // впрягаться в работу
rus_verbs:впрячь{}, // впрячь лошадь в телегу
rus_verbs:впрячься{}, // впрячься в работу
rus_verbs:впускать{}, // впускать посетителей в музей
rus_verbs:впускаться{}, // впускаться в помещение
rus_verbs:впустить{}, // впустить посетителей в музей
rus_verbs:впутать{}, // впутать кого-то во что-то
rus_verbs:впутаться{}, // впутаться во что-то
rus_verbs:впутывать{}, // впутывать кого-то во что-то
rus_verbs:впутываться{}, // впутываться во что-то
rus_verbs:врабатываться{}, // врабатываться в режим
rus_verbs:вработаться{}, // вработаться в режим
rus_verbs:врастать{}, // врастать в кожу
rus_verbs:врасти{}, // врасти в кожу
инфинитив:врезать{ вид:несоверш }, // врезать замок в дверь
инфинитив:врезать{ вид:соверш },
глагол:врезать{ вид:несоверш },
глагол:врезать{ вид:соверш },
деепричастие:врезая{},
деепричастие:врезав{},
прилагательное:врезанный{},
инфинитив:врезаться{ вид:несоверш }, // врезаться в стену
инфинитив:врезаться{ вид:соверш },
глагол:врезаться{ вид:несоверш },
деепричастие:врезаясь{},
деепричастие:врезавшись{},
rus_verbs:врубить{}, // врубить в нагрузку
rus_verbs:врываться{}, // врываться в здание
rus_verbs:закачивать{}, // Насос закачивает топливо в бак
rus_verbs:ввезти{}, // Предприятие ввезло товар в страну
rus_verbs:вверстать{}, // Дизайнер вверстал блок в страницу
rus_verbs:вверстывать{}, // Дизайнер с трудом вверстывает блоки в страницу
rus_verbs:вверстываться{}, // Блок тяжело вверстывается в эту страницу
rus_verbs:ввивать{}, // Женщина ввивает полоску в косу
rus_verbs:вволакиваться{}, // Пойманная мышь вволакивается котиком в дом
rus_verbs:вволочь{}, // Кот вволок в дом пойманную крысу
rus_verbs:вдергивать{}, // приспособление вдергивает нитку в игольное ушко
rus_verbs:вдернуть{}, // приспособление вдернуло нитку в игольное ушко
rus_verbs:вдувать{}, // Челоек вдувает воздух в легкие второго человека
rus_verbs:вдуваться{}, // Воздух вдувается в легкие человека
rus_verbs:вламываться{}, // Полиция вламывается в квартиру
rus_verbs:вовлекаться{}, // трудные подростки вовлекаются в занятие спортом
rus_verbs:вовлечь{}, // вовлечь трудных подростков в занятие спортом
rus_verbs:вовлечься{}, // вовлечься в занятие спортом
rus_verbs:спуститься{}, // спуститься в подвал
rus_verbs:спускаться{}, // спускаться в подвал
rus_verbs:отправляться{}, // отправляться в дальнее плавание
инфинитив:эмитировать{ вид:соверш }, // Поверхность эмитирует электроны в пространство
инфинитив:эмитировать{ вид:несоверш },
глагол:эмитировать{ вид:соверш },
глагол:эмитировать{ вид:несоверш },
деепричастие:эмитируя{},
деепричастие:эмитировав{},
прилагательное:эмитировавший{ вид:несоверш },
// прилагательное:эмитировавший{ вид:соверш },
прилагательное:эмитирующий{},
прилагательное:эмитируемый{},
прилагательное:эмитированный{},
инфинитив:этапировать{вид:несоверш}, // Преступника этапировали в колонию
инфинитив:этапировать{вид:соверш},
глагол:этапировать{вид:несоверш},
глагол:этапировать{вид:соверш},
деепричастие:этапируя{},
прилагательное:этапируемый{},
прилагательное:этапированный{},
rus_verbs:этапироваться{}, // Преступники этапируются в колонию
rus_verbs:баллотироваться{}, // они баллотировались в жюри
rus_verbs:бежать{}, // Олигарх с семьей любовницы бежал в другую страну
rus_verbs:бросать{}, // Они бросали в фонтан медные монетки
rus_verbs:бросаться{}, // Дети бросались в воду с моста
rus_verbs:бросить{}, // Он бросил в фонтан медную монетку
rus_verbs:броситься{}, // самоубийца бросился с моста в воду
rus_verbs:превратить{}, // Найден белок, который превратит человека в супергероя
rus_verbs:буксировать{}, // Буксир буксирует танкер в порт
rus_verbs:буксироваться{}, // Сухогруз буксируется в порт
rus_verbs:вбегать{}, // Курьер вбегает в дверь
rus_verbs:вбежать{}, // Курьер вбежал в дверь
rus_verbs:вбетонировать{}, // Опора была вбетонирована в пол
rus_verbs:вбивать{}, // Мастер вбивает штырь в плиту
rus_verbs:вбиваться{}, // Штырь вбивается в плиту
rus_verbs:вбирать{}, // Вата вбирает в себя влагу
rus_verbs:вбить{}, // Ученик вбил в доску маленький гвоздь
rus_verbs:вбрасывать{}, // Арбитр вбрасывает мяч в игру
rus_verbs:вбрасываться{}, // Мяч вбрасывается в игру
rus_verbs:вбросить{}, // Судья вбросил мяч в игру
rus_verbs:вбуравиться{}, // Сверло вбуравилось в бетон
rus_verbs:вбуравливаться{}, // Сверло вбуравливается в бетон
rus_verbs:вбухиваться{}, // Много денег вбухиваются в этот проект
rus_verbs:вваливаться{}, // Человек вваливается в кабинет врача
rus_verbs:ввалить{}, // Грузчики ввалили мешок в квартиру
rus_verbs:ввалиться{}, // Человек ввалился в кабинет терапевта
rus_verbs:вваривать{}, // Робот вваривает арматурину в плиту
rus_verbs:ввариваться{}, // Арматура вваривается в плиту
rus_verbs:вварить{}, // Робот вварил арматурину в плиту
rus_verbs:влезть{}, // Предприятие ввезло товар в страну
rus_verbs:ввернуть{}, // Вверни новую лампочку в люстру
rus_verbs:ввернуться{}, // Лампочка легко ввернулась в патрон
rus_verbs:ввертывать{}, // Электрик ввертывает лампочку в патрон
rus_verbs:ввертываться{}, // Лампочка легко ввертывается в патрон
rus_verbs:вверять{}, // Пациент вверяет свою жизнь в руки врача
rus_verbs:вверяться{}, // Пациент вверяется в руки врача
rus_verbs:ввести{}, // Агенство ввело своего представителя в совет директоров
rus_verbs:ввиваться{}, // полоска ввивается в косу
rus_verbs:ввинтить{}, // Отвертка ввинтила шуруп в дерево
rus_verbs:ввинтиться{}, // Шуруп ввинтился в дерево
rus_verbs:ввинчивать{}, // Рука ввинчивает саморез в стену
rus_verbs:ввинчиваться{}, // Саморез ввинчивается в стену
rus_verbs:вводить{}, // Агенство вводит своего представителя в совет директоров
rus_verbs:вводиться{}, // Представитель агенства вводится в совет директоров
// rus_verbs:ввозить{}, // Фирма ввозит в страну станки и сырье
rus_verbs:ввозиться{}, // Станки и сырье ввозятся в страну
rus_verbs:вволакивать{}, // Пойманная мышь вволакивается котиком в дом
rus_verbs:вворачивать{}, // Электрик вворачивает новую лампочку в патрон
rus_verbs:вворачиваться{}, // Новая лампочка легко вворачивается в патрон
rus_verbs:ввязаться{}, // Разведрота ввязалась в бой
rus_verbs:ввязываться{}, // Передовые части ввязываются в бой
rus_verbs:вглядеться{}, // Охранник вгляделся в темный коридор
rus_verbs:вглядываться{}, // Охранник внимательно вглядывается в монитор
rus_verbs:вгонять{}, // Эта музыка вгоняет меня в депрессию
rus_verbs:вгрызаться{}, // Зонд вгрызается в поверхность астероида
rus_verbs:вгрызться{}, // Зонд вгрызся в поверхность астероида
rus_verbs:вдаваться{}, // Вы не должны вдаваться в юридические детали
rus_verbs:вдвигать{}, // Робот вдвигает контейнер в ячейку
rus_verbs:вдвигаться{}, // Контейнер вдвигается в ячейку
rus_verbs:вдвинуть{}, // манипулятор вдвинул деталь в печь
rus_verbs:вдвинуться{}, // деталь вдвинулась в печь
rus_verbs:вдевать{}, // портниха быстро вдевает нитку в иголку
rus_verbs:вдеваться{}, // нитка быстро вдевается в игольное ушко
rus_verbs:вдеть{}, // портниха быстро вдела нитку в игольное ушко
rus_verbs:вдеться{}, // нитка быстро вделась в игольное ушко
rus_verbs:вделать{}, // мастер вделал розетку в стену
rus_verbs:вделывать{}, // мастер вделывает выключатель в стену
rus_verbs:вделываться{}, // кронштейн вделывается в стену
rus_verbs:вдергиваться{}, // нитка легко вдергивается в игольное ушко
rus_verbs:вдернуться{}, // нитка легко вдернулась в игольное ушко
rus_verbs:вдолбить{}, // Американцы обещали вдолбить страну в каменный век
rus_verbs:вдумываться{}, // Мальчик обычно не вдумывался в сюжет фильмов
rus_verbs:вдыхать{}, // мы вдыхаем в себя весь этот смог
rus_verbs:вдыхаться{}, // Весь этот смог вдыхается в легкие
rus_verbs:вернуть{}, // Книгу надо вернуть в библиотеку
rus_verbs:вернуться{}, // Дети вернулись в библиотеку
rus_verbs:вжаться{}, // Водитель вжался в кресло
rus_verbs:вживаться{}, // Актер вживается в новую роль
rus_verbs:вживить{}, // Врачи вживили стимулятор в тело пациента
rus_verbs:вживиться{}, // Стимулятор вживился в тело пациента
rus_verbs:вживлять{}, // Врачи вживляют стимулятор в тело пациента
rus_verbs:вживляться{}, // Стимулятор вживляется в тело
rus_verbs:вжиматься{}, // Видитель инстинктивно вжимается в кресло
rus_verbs:вжиться{}, // Актер вжился в свою новую роль
rus_verbs:взвиваться{}, // Воздушный шарик взвивается в небо
rus_verbs:взвинтить{}, // Кризис взвинтил цены в небо
rus_verbs:взвинтиться{}, // Цены взвинтились в небо
rus_verbs:взвинчивать{}, // Кризис взвинчивает цены в небо
rus_verbs:взвинчиваться{}, // Цены взвинчиваются в небо
rus_verbs:взвиться{}, // Шарики взвились в небо
rus_verbs:взлетать{}, // Экспериментальный аппарат взлетает в воздух
rus_verbs:взлететь{}, // Экспериментальный аппарат взлетел в небо
rus_verbs:взмывать{}, // шарики взмывают в небо
rus_verbs:взмыть{}, // Шарики взмыли в небо
rus_verbs:вильнуть{}, // Машина вильнула в левую сторону
rus_verbs:вкалывать{}, // Медсестра вкалывает иглу в вену
rus_verbs:вкалываться{}, // Игла вкалываться прямо в вену
rus_verbs:вкапывать{}, // рабочий вкапывает сваю в землю
rus_verbs:вкапываться{}, // Свая вкапывается в землю
rus_verbs:вкатить{}, // рабочие вкатили бочку в гараж
rus_verbs:вкатиться{}, // машина вкатилась в гараж
rus_verbs:вкатывать{}, // рабочик вкатывают бочку в гараж
rus_verbs:вкатываться{}, // машина вкатывается в гараж
rus_verbs:вкачать{}, // Механики вкачали в бак много топлива
rus_verbs:вкачивать{}, // Насос вкачивает топливо в бак
rus_verbs:вкачиваться{}, // Топливо вкачивается в бак
rus_verbs:вкидать{}, // Манипулятор вкидал груз в контейнер
rus_verbs:вкидывать{}, // Манипулятор вкидывает груз в контейнер
rus_verbs:вкидываться{}, // Груз вкидывается в контейнер
rus_verbs:вкладывать{}, // Инвестор вкладывает деньги в акции
rus_verbs:вкладываться{}, // Инвестор вкладывается в акции
rus_verbs:вклеивать{}, // Мальчик вклеивает картинку в тетрадь
rus_verbs:вклеиваться{}, // Картинка вклеивается в тетрадь
rus_verbs:вклеить{}, // Мальчик вклеил картинку в тетрадь
rus_verbs:вклеиться{}, // Картинка вклеилась в тетрадь
rus_verbs:вклепать{}, // Молоток вклепал заклепку в лист
rus_verbs:вклепывать{}, // Молоток вклепывает заклепку в лист
rus_verbs:вклиниваться{}, // Машина вклинивается в поток
rus_verbs:вклиниться{}, // машина вклинилась в поток
rus_verbs:включать{}, // Команда включает компьютер в сеть
rus_verbs:включаться{}, // Машина включается в глобальную сеть
rus_verbs:включить{}, // Команда включила компьютер в сеть
rus_verbs:включиться{}, // Компьютер включился в сеть
rus_verbs:вколачивать{}, // Столяр вколачивает гвоздь в доску
rus_verbs:вколачиваться{}, // Гвоздь вколачивается в доску
rus_verbs:вколотить{}, // Столяр вколотил гвоздь в доску
rus_verbs:вколоть{}, // Медсестра вколола в мышцу лекарство
rus_verbs:вкопать{}, // Рабочие вкопали сваю в землю
rus_verbs:вкрадываться{}, // Ошибка вкрадывается в расчеты
rus_verbs:вкраивать{}, // Портниха вкраивает вставку в юбку
rus_verbs:вкраиваться{}, // Вставка вкраивается в юбку
rus_verbs:вкрасться{}, // Ошибка вкралась в расчеты
rus_verbs:вкрутить{}, // Электрик вкрутил лампочку в патрон
rus_verbs:вкрутиться{}, // лампочка легко вкрутилась в патрон
rus_verbs:вкручивать{}, // Электрик вкручивает лампочку в патрон
rus_verbs:вкручиваться{}, // Лампочка легко вкручивается в патрон
rus_verbs:влазить{}, // Разъем влазит в отверствие
rus_verbs:вламывать{}, // Полиция вламывается в квартиру
rus_verbs:влетать{}, // Самолет влетает в грозовой фронт
rus_verbs:влететь{}, // Самолет влетел в грозовой фронт
rus_verbs:вливать{}, // Механик вливает масло в картер
rus_verbs:вливаться{}, // Масло вливается в картер
rus_verbs:влипать{}, // Эти неудачники постоянно влипают в разные происшествия
rus_verbs:влипнуть{}, // Эти неудачники опять влипли в неприятности
rus_verbs:влить{}, // Механик влил свежее масло в картер
rus_verbs:влиться{}, // Свежее масло влилось в бак
rus_verbs:вложить{}, // Инвесторы вложили в эти акции большие средства
rus_verbs:вложиться{}, // Инвесторы вложились в эти акции
rus_verbs:влюбиться{}, // Коля влюбился в Олю
rus_verbs:влюблять{}, // Оля постоянно влюбляла в себя мальчиков
rus_verbs:влюбляться{}, // Оля влюбляется в спортсменов
rus_verbs:вляпаться{}, // Коля вляпался в неприятность
rus_verbs:вляпываться{}, // Коля постоянно вляпывается в неприятности
rus_verbs:вменить{}, // вменить в вину
rus_verbs:вменять{}, // вменять в обязанность
rus_verbs:вмерзать{}, // Колеса вмерзают в лед
rus_verbs:вмерзнуть{}, // Колеса вмерзли в лед
rus_verbs:вмести{}, // вмести в дом
rus_verbs:вместить{}, // вместить в ёмкость
rus_verbs:вместиться{}, // Прибор не вместился в зонд
rus_verbs:вмешаться{}, // Начальник вмешался в конфликт
rus_verbs:вмешивать{}, // Не вмешивай меня в это дело
rus_verbs:вмешиваться{}, // Начальник вмешивается в переговоры
rus_verbs:вмещаться{}, // Приборы не вмещаются в корпус
rus_verbs:вминать{}, // вминать в корпус
rus_verbs:вминаться{}, // кронштейн вминается в корпус
rus_verbs:вмонтировать{}, // Конструкторы вмонтировали в корпус зонда новые приборы
rus_verbs:вмонтироваться{}, // Новые приборы легко вмонтировались в корпус зонда
rus_verbs:вмораживать{}, // Установка вмораживает сваи в грунт
rus_verbs:вмораживаться{}, // Сваи вмораживаются в грунт
rus_verbs:вморозить{}, // Установка вморозила сваи в грунт
rus_verbs:вмуровать{}, // Сейф был вмурован в стену
rus_verbs:вмуровывать{}, // вмуровывать сейф в стену
rus_verbs:вмуровываться{}, // сейф вмуровывается в бетонную стену
rus_verbs:внедрить{}, // внедрить инновацию в производство
rus_verbs:внедриться{}, // Шпион внедрился в руководство
rus_verbs:внедрять{}, // внедрять инновации в производство
rus_verbs:внедряться{}, // Шпионы внедряются в руководство
rus_verbs:внести{}, // внести коробку в дом
rus_verbs:внестись{}, // внестись в список приглашенных гостей
rus_verbs:вникать{}, // Разработчик вникает в детали задачи
rus_verbs:вникнуть{}, // Дизайнер вник в детали задачи
rus_verbs:вносить{}, // вносить новое действующее лицо в список главных героев
rus_verbs:вноситься{}, // вноситься в список главных персонажей
rus_verbs:внюхаться{}, // Пёс внюхался в ароматы леса
rus_verbs:внюхиваться{}, // Пёс внюхивается в ароматы леса
rus_verbs:вобрать{}, // вобрать в себя лучшие методы борьбы с вредителями
rus_verbs:вовлекать{}, // вовлекать трудных подростков в занятие спортом
rus_verbs:вогнать{}, // вогнал человека в тоску
rus_verbs:водворить{}, // водворить преступника в тюрьму
rus_verbs:возвернуть{}, // возвернуть в родную стихию
rus_verbs:возвернуться{}, // возвернуться в родную стихию
rus_verbs:возвести{}, // возвести число в четную степень
rus_verbs:возводить{}, // возводить число в четную степень
rus_verbs:возводиться{}, // число возводится в четную степень
rus_verbs:возвратить{}, // возвратить коров в стойло
rus_verbs:возвратиться{}, // возвратиться в родной дом
rus_verbs:возвращать{}, // возвращать коров в стойло
rus_verbs:возвращаться{}, // возвращаться в родной дом
rus_verbs:войти{}, // войти в галерею славы
rus_verbs:вонзать{}, // Коля вонзает вилку в котлету
rus_verbs:вонзаться{}, // Вилка вонзается в котлету
rus_verbs:вонзить{}, // Коля вонзил вилку в котлету
rus_verbs:вонзиться{}, // Вилка вонзилась в сочную котлету
rus_verbs:воплотить{}, // Коля воплотил свои мечты в реальность
rus_verbs:воплотиться{}, // Мечты воплотились в реальность
rus_verbs:воплощать{}, // Коля воплощает мечты в реальность
rus_verbs:воплощаться{}, // Мечты иногда воплощаются в реальность
rus_verbs:ворваться{}, // Перемены неожиданно ворвались в размеренную жизнь
rus_verbs:воспарить{}, // Душа воспарила в небо
rus_verbs:воспарять{}, // Душа воспаряет в небо
rus_verbs:врыть{}, // врыть опору в землю
rus_verbs:врыться{}, // врыться в землю
rus_verbs:всадить{}, // всадить пулю в сердце
rus_verbs:всаживать{}, // всаживать нож в бок
rus_verbs:всасывать{}, // всасывать воду в себя
rus_verbs:всасываться{}, // всасываться в ёмкость
rus_verbs:вселить{}, // вселить надежду в кого-либо
rus_verbs:вселиться{}, // вселиться в пустующее здание
rus_verbs:вселять{}, // вселять надежду в кого-то
rus_verbs:вселяться{}, // вселяться в пустующее здание
rus_verbs:вскидывать{}, // вскидывать руку в небо
rus_verbs:вскинуть{}, // вскинуть руку в небо
rus_verbs:вслушаться{}, // вслушаться в звуки
rus_verbs:вслушиваться{}, // вслушиваться в шорох
rus_verbs:всматриваться{}, // всматриваться в темноту
rus_verbs:всмотреться{}, // всмотреться в темень
rus_verbs:всовывать{}, // всовывать палец в отверстие
rus_verbs:всовываться{}, // всовываться в форточку
rus_verbs:всосать{}, // всосать жидкость в себя
rus_verbs:всосаться{}, // всосаться в кожу
rus_verbs:вставить{}, // вставить ключ в замок
rus_verbs:вставлять{}, // вставлять ключ в замок
rus_verbs:встраивать{}, // встраивать черный ход в систему защиты
rus_verbs:встраиваться{}, // встраиваться в систему безопасности
rus_verbs:встревать{}, // встревать в разговор
rus_verbs:встроить{}, // встроить секретный модуль в систему безопасности
rus_verbs:встроиться{}, // встроиться в систему безопасности
rus_verbs:встрять{}, // встрять в разговор
rus_verbs:вступать{}, // вступать в действующую армию
rus_verbs:вступить{}, // вступить в действующую армию
rus_verbs:всунуть{}, // всунуть палец в отверстие
rus_verbs:всунуться{}, // всунуться в форточку
инфинитив:всыпать{вид:соверш}, // всыпать порошок в контейнер
инфинитив:всыпать{вид:несоверш},
глагол:всыпать{вид:соверш},
глагол:всыпать{вид:несоверш},
деепричастие:всыпав{},
деепричастие:всыпая{},
прилагательное:всыпавший{ вид:соверш },
// прилагательное:всыпавший{ вид:несоверш },
прилагательное:всыпанный{},
// прилагательное:всыпающий{},
инфинитив:всыпаться{ вид:несоверш}, // всыпаться в контейнер
// инфинитив:всыпаться{ вид:соверш},
// глагол:всыпаться{ вид:соверш},
глагол:всыпаться{ вид:несоверш},
// деепричастие:всыпавшись{},
деепричастие:всыпаясь{},
// прилагательное:всыпавшийся{ вид:соверш },
// прилагательное:всыпавшийся{ вид:несоверш },
// прилагательное:всыпающийся{},
rus_verbs:вталкивать{}, // вталкивать деталь в ячейку
rus_verbs:вталкиваться{}, // вталкиваться в ячейку
rus_verbs:втаптывать{}, // втаптывать в грязь
rus_verbs:втаптываться{}, // втаптываться в грязь
rus_verbs:втаскивать{}, // втаскивать мешок в комнату
rus_verbs:втаскиваться{}, // втаскиваться в комнату
rus_verbs:втащить{}, // втащить мешок в комнату
rus_verbs:втащиться{}, // втащиться в комнату
rus_verbs:втекать{}, // втекать в бутылку
rus_verbs:втемяшивать{}, // втемяшивать в голову
rus_verbs:втемяшиваться{}, // втемяшиваться в голову
rus_verbs:втемяшить{}, // втемяшить в голову
rus_verbs:втемяшиться{}, // втемяшиться в голову
rus_verbs:втереть{}, // втереть крем в кожу
rus_verbs:втереться{}, // втереться в кожу
rus_verbs:втесаться{}, // втесаться в группу
rus_verbs:втесывать{}, // втесывать в группу
rus_verbs:втесываться{}, // втесываться в группу
rus_verbs:втечь{}, // втечь в бак
rus_verbs:втирать{}, // втирать крем в кожу
rus_verbs:втираться{}, // втираться в кожу
rus_verbs:втискивать{}, // втискивать сумку в вагон
rus_verbs:втискиваться{}, // втискиваться в переполненный вагон
rus_verbs:втиснуть{}, // втиснуть сумку в вагон
rus_verbs:втиснуться{}, // втиснуться в переполненный вагон метро
rus_verbs:втолкать{}, // втолкать коляску в лифт
rus_verbs:втолкаться{}, // втолкаться в вагон метро
rus_verbs:втолкнуть{}, // втолкнуть коляску в лифт
rus_verbs:втолкнуться{}, // втолкнуться в вагон метро
rus_verbs:втолочь{}, // втолочь в смесь
rus_verbs:втоптать{}, // втоптать цветы в землю
rus_verbs:вторгаться{}, // вторгаться в чужую зону
rus_verbs:вторгнуться{}, // вторгнуться в частную жизнь
rus_verbs:втравить{}, // втравить кого-то в неприятности
rus_verbs:втравливать{}, // втравливать кого-то в неприятности
rus_verbs:втрамбовать{}, // втрамбовать камни в землю
rus_verbs:втрамбовывать{}, // втрамбовывать камни в землю
rus_verbs:втрамбовываться{}, // втрамбовываться в землю
rus_verbs:втрескаться{}, // втрескаться в кого-то
rus_verbs:втрескиваться{}, // втрескиваться в кого-либо
rus_verbs:втыкать{}, // втыкать вилку в котлетку
rus_verbs:втыкаться{}, // втыкаться в розетку
rus_verbs:втюриваться{}, // втюриваться в кого-либо
rus_verbs:втюриться{}, // втюриться в кого-либо
rus_verbs:втягивать{}, // втягивать что-то в себя
rus_verbs:втягиваться{}, // втягиваться в себя
rus_verbs:втянуться{}, // втянуться в себя
rus_verbs:вцементировать{}, // вцементировать сваю в фундамент
rus_verbs:вчеканить{}, // вчеканить надпись в лист
rus_verbs:вчитаться{}, // вчитаться внимательнее в текст
rus_verbs:вчитываться{}, // вчитываться внимательнее в текст
rus_verbs:вчувствоваться{}, // вчувствоваться в роль
rus_verbs:вшагивать{}, // вшагивать в новую жизнь
rus_verbs:вшагнуть{}, // вшагнуть в новую жизнь
rus_verbs:вшивать{}, // вшивать заплату в рубашку
rus_verbs:вшиваться{}, // вшиваться в ткань
rus_verbs:вшить{}, // вшить заплату в ткань
rus_verbs:въедаться{}, // въедаться в мякоть
rus_verbs:въезжать{}, // въезжать в гараж
rus_verbs:въехать{}, // въехать в гараж
rus_verbs:выиграть{}, // Коля выиграл в шахматы
rus_verbs:выигрывать{}, // Коля часто выигрывает у меня в шахматы
rus_verbs:выкладывать{}, // выкладывать в общий доступ
rus_verbs:выкладываться{}, // выкладываться в общий доступ
rus_verbs:выкрасить{}, // выкрасить машину в розовый цвет
rus_verbs:выкраситься{}, // выкраситься в дерзкий розовый цвет
rus_verbs:выкрашивать{}, // выкрашивать волосы в красный цвет
rus_verbs:выкрашиваться{}, // выкрашиваться в красный цвет
rus_verbs:вылезать{}, // вылезать в открытое пространство
rus_verbs:вылезти{}, // вылезти в открытое пространство
rus_verbs:выливать{}, // выливать в бутылку
rus_verbs:выливаться{}, // выливаться в ёмкость
rus_verbs:вылить{}, // вылить отходы в канализацию
rus_verbs:вылиться{}, // Топливо вылилось в воду
rus_verbs:выложить{}, // выложить в общий доступ
rus_verbs:выпадать{}, // выпадать в осадок
rus_verbs:выпрыгивать{}, // выпрыгивать в окно
rus_verbs:выпрыгнуть{}, // выпрыгнуть в окно
rus_verbs:выродиться{}, // выродиться в жалкое подобие
rus_verbs:вырождаться{}, // вырождаться в жалкое подобие славных предков
rus_verbs:высеваться{}, // высеваться в землю
rus_verbs:высеять{}, // высеять в землю
rus_verbs:выслать{}, // выслать в страну постоянного пребывания
rus_verbs:высморкаться{}, // высморкаться в платок
rus_verbs:высморкнуться{}, // высморкнуться в платок
rus_verbs:выстреливать{}, // выстреливать в цель
rus_verbs:выстреливаться{}, // выстреливаться в цель
rus_verbs:выстрелить{}, // выстрелить в цель
rus_verbs:вытекать{}, // вытекать в озеро
rus_verbs:вытечь{}, // вытечь в воду
rus_verbs:смотреть{}, // смотреть в будущее
rus_verbs:подняться{}, // подняться в лабораторию
rus_verbs:послать{}, // послать в магазин
rus_verbs:слать{}, // слать в неизвестность
rus_verbs:добавить{}, // добавить в суп
rus_verbs:пройти{}, // пройти в лабораторию
rus_verbs:положить{}, // положить в ящик
rus_verbs:прислать{}, // прислать в полицию
rus_verbs:упасть{}, // упасть в пропасть
инфинитив:писать{ aux stress="пис^ать" }, // писать в газету
инфинитив:писать{ aux stress="п^исать" }, // писать в штанишки
глагол:писать{ aux stress="п^исать" },
глагол:писать{ aux stress="пис^ать" },
деепричастие:писая{},
прилагательное:писавший{ aux stress="п^исавший" }, // писавший в штанишки
прилагательное:писавший{ aux stress="пис^авший" }, // писавший в газету
rus_verbs:собираться{}, // собираться в поход
rus_verbs:звать{}, // звать в ресторан
rus_verbs:направиться{}, // направиться в ресторан
rus_verbs:отправиться{}, // отправиться в ресторан
rus_verbs:поставить{}, // поставить в угол
rus_verbs:целить{}, // целить в мишень
rus_verbs:попасть{}, // попасть в переплет
rus_verbs:ударить{}, // ударить в больное место
rus_verbs:закричать{}, // закричать в микрофон
rus_verbs:опустить{}, // опустить в воду
rus_verbs:принести{}, // принести в дом бездомного щенка
rus_verbs:отдать{}, // отдать в хорошие руки
rus_verbs:ходить{}, // ходить в школу
rus_verbs:уставиться{}, // уставиться в экран
rus_verbs:приходить{}, // приходить в бешенство
rus_verbs:махнуть{}, // махнуть в Италию
rus_verbs:сунуть{}, // сунуть в замочную скважину
rus_verbs:явиться{}, // явиться в расположение части
rus_verbs:уехать{}, // уехать в город
rus_verbs:целовать{}, // целовать в лобик
rus_verbs:повести{}, // повести в бой
rus_verbs:опуститься{}, // опуститься в кресло
rus_verbs:передать{}, // передать в архив
rus_verbs:побежать{}, // побежать в школу
rus_verbs:стечь{}, // стечь в воду
rus_verbs:уходить{}, // уходить добровольцем в армию
rus_verbs:привести{}, // привести в дом
rus_verbs:шагнуть{}, // шагнуть в неизвестность
rus_verbs:собраться{}, // собраться в поход
rus_verbs:заглянуть{}, // заглянуть в основу
rus_verbs:поспешить{}, // поспешить в церковь
rus_verbs:поцеловать{}, // поцеловать в лоб
rus_verbs:перейти{}, // перейти в высшую лигу
rus_verbs:поверить{}, // поверить в искренность
rus_verbs:глянуть{}, // глянуть в оглавление
rus_verbs:зайти{}, // зайти в кафетерий
rus_verbs:подобрать{}, // подобрать в лесу
rus_verbs:проходить{}, // проходить в помещение
rus_verbs:глядеть{}, // глядеть в глаза
rus_verbs:пригласить{}, // пригласить в театр
rus_verbs:позвать{}, // позвать в класс
rus_verbs:усесться{}, // усесться в кресло
rus_verbs:поступить{}, // поступить в институт
rus_verbs:лечь{}, // лечь в постель
rus_verbs:поклониться{}, // поклониться в пояс
rus_verbs:потянуться{}, // потянуться в лес
rus_verbs:колоть{}, // колоть в ягодицу
rus_verbs:присесть{}, // присесть в кресло
rus_verbs:оглядеться{}, // оглядеться в зеркало
rus_verbs:поглядеть{}, // поглядеть в зеркало
rus_verbs:превратиться{}, // превратиться в лягушку
rus_verbs:принимать{}, // принимать во внимание
rus_verbs:звонить{}, // звонить в колокола
rus_verbs:привезти{}, // привезти в гостиницу
rus_verbs:рухнуть{}, // рухнуть в пропасть
rus_verbs:пускать{}, // пускать в дело
rus_verbs:отвести{}, // отвести в больницу
rus_verbs:сойти{}, // сойти в ад
rus_verbs:набрать{}, // набрать в команду
rus_verbs:собрать{}, // собрать в кулак
rus_verbs:двигаться{}, // двигаться в каюту
rus_verbs:падать{}, // падать в область нуля
rus_verbs:полезть{}, // полезть в драку
rus_verbs:направить{}, // направить в стационар
rus_verbs:приводить{}, // приводить в чувство
rus_verbs:толкнуть{}, // толкнуть в бок
rus_verbs:кинуться{}, // кинуться в драку
rus_verbs:ткнуть{}, // ткнуть в глаз
rus_verbs:заключить{}, // заключить в объятия
rus_verbs:подниматься{}, // подниматься в небо
rus_verbs:расти{}, // расти в глубину
rus_verbs:налить{}, // налить в кружку
rus_verbs:швырнуть{}, // швырнуть в бездну
rus_verbs:прыгнуть{}, // прыгнуть в дверь
rus_verbs:промолчать{}, // промолчать в тряпочку
rus_verbs:садиться{}, // садиться в кресло
rus_verbs:лить{}, // лить в кувшин
rus_verbs:дослать{}, // дослать деталь в держатель
rus_verbs:переслать{}, // переслать в обработчик
rus_verbs:удалиться{}, // удалиться в совещательную комнату
rus_verbs:разглядывать{}, // разглядывать в бинокль
rus_verbs:повесить{}, // повесить в шкаф
инфинитив:походить{ вид:соверш }, // походить в институт
глагол:походить{ вид:соверш },
деепричастие:походив{},
// прилагательное:походивший{вид:соверш},
rus_verbs:помчаться{}, // помчаться в класс
rus_verbs:свалиться{}, // свалиться в яму
rus_verbs:сбежать{}, // сбежать в Англию
rus_verbs:стрелять{}, // стрелять в цель
rus_verbs:обращать{}, // обращать в свою веру
rus_verbs:завести{}, // завести в дом
rus_verbs:приобрести{}, // приобрести в рассрочку
rus_verbs:сбросить{}, // сбросить в яму
rus_verbs:устроиться{}, // устроиться в крупную корпорацию
rus_verbs:погрузиться{}, // погрузиться в пучину
rus_verbs:течь{}, // течь в канаву
rus_verbs:произвести{}, // произвести в звание майора
rus_verbs:метать{}, // метать в цель
rus_verbs:пустить{}, // пустить в дело
rus_verbs:полететь{}, // полететь в Европу
rus_verbs:пропустить{}, // пропустить в здание
rus_verbs:рвануть{}, // рвануть в отпуск
rus_verbs:заходить{}, // заходить в каморку
rus_verbs:нырнуть{}, // нырнуть в прорубь
rus_verbs:рвануться{}, // рвануться в атаку
rus_verbs:приподняться{}, // приподняться в воздух
rus_verbs:превращаться{}, // превращаться в крупную величину
rus_verbs:прокричать{}, // прокричать в ухо
rus_verbs:записать{}, // записать в блокнот
rus_verbs:забраться{}, // забраться в шкаф
rus_verbs:приезжать{}, // приезжать в деревню
rus_verbs:продать{}, // продать в рабство
rus_verbs:проникнуть{}, // проникнуть в центр
rus_verbs:устремиться{}, // устремиться в открытое море
rus_verbs:посадить{}, // посадить в кресло
rus_verbs:упереться{}, // упереться в пол
rus_verbs:ринуться{}, // ринуться в буфет
rus_verbs:отдавать{}, // отдавать в кадетское училище
rus_verbs:отложить{}, // отложить в долгий ящик
rus_verbs:убежать{}, // убежать в приют
rus_verbs:оценить{}, // оценить в миллион долларов
rus_verbs:поднимать{}, // поднимать в стратосферу
rus_verbs:отослать{}, // отослать в квалификационную комиссию
rus_verbs:отодвинуть{}, // отодвинуть в дальний угол
rus_verbs:торопиться{}, // торопиться в школу
rus_verbs:попадаться{}, // попадаться в руки
rus_verbs:поразить{}, // поразить в самое сердце
rus_verbs:доставить{}, // доставить в квартиру
rus_verbs:заслать{}, // заслать в тыл
rus_verbs:сослать{}, // сослать в изгнание
rus_verbs:запустить{}, // запустить в космос
rus_verbs:удариться{}, // удариться в запой
rus_verbs:ударяться{}, // ударяться в крайность
rus_verbs:шептать{}, // шептать в лицо
rus_verbs:уронить{}, // уронить в унитаз
rus_verbs:прорычать{}, // прорычать в микрофон
rus_verbs:засунуть{}, // засунуть в глотку
rus_verbs:плыть{}, // плыть в открытое море
rus_verbs:перенести{}, // перенести в духовку
rus_verbs:светить{}, // светить в лицо
rus_verbs:мчаться{}, // мчаться в ремонт
rus_verbs:стукнуть{}, // стукнуть в лоб
rus_verbs:обрушиться{}, // обрушиться в котлован
rus_verbs:поглядывать{}, // поглядывать в экран
rus_verbs:уложить{}, // уложить в кроватку
инфинитив:попадать{ вид:несоверш }, // попадать в черный список
глагол:попадать{ вид:несоверш },
прилагательное:попадающий{ вид:несоверш },
прилагательное:попадавший{ вид:несоверш },
деепричастие:попадая{},
rus_verbs:провалиться{}, // провалиться в яму
rus_verbs:жаловаться{}, // жаловаться в комиссию
rus_verbs:опоздать{}, // опоздать в школу
rus_verbs:посылать{}, // посылать в парикмахерскую
rus_verbs:погнать{}, // погнать в хлев
rus_verbs:поступать{}, // поступать в институт
rus_verbs:усадить{}, // усадить в кресло
rus_verbs:проиграть{}, // проиграть в рулетку
rus_verbs:прилететь{}, // прилететь в страну
rus_verbs:повалиться{}, // повалиться в траву
rus_verbs:огрызнуться{}, // Собака огрызнулась в ответ
rus_verbs:лезть{}, // лезть в чужие дела
rus_verbs:потащить{}, // потащить в суд
rus_verbs:направляться{}, // направляться в порт
rus_verbs:поползти{}, // поползти в другую сторону
rus_verbs:пуститься{}, // пуститься в пляс
rus_verbs:забиться{}, // забиться в нору
rus_verbs:залезть{}, // залезть в конуру
rus_verbs:сдать{}, // сдать в утиль
rus_verbs:тронуться{}, // тронуться в путь
rus_verbs:сыграть{}, // сыграть в шахматы
rus_verbs:перевернуть{}, // перевернуть в более удобную позу
rus_verbs:сжимать{}, // сжимать пальцы в кулак
rus_verbs:подтолкнуть{}, // подтолкнуть в бок
rus_verbs:отнести{}, // отнести животное в лечебницу
rus_verbs:одеться{}, // одеться в зимнюю одежду
rus_verbs:плюнуть{}, // плюнуть в колодец
rus_verbs:передавать{}, // передавать в прокуратуру
rus_verbs:отскочить{}, // отскочить в лоб
rus_verbs:призвать{}, // призвать в армию
rus_verbs:увезти{}, // увезти в деревню
rus_verbs:улечься{}, // улечься в кроватку
rus_verbs:отшатнуться{}, // отшатнуться в сторону
rus_verbs:ложиться{}, // ложиться в постель
rus_verbs:пролететь{}, // пролететь в конец
rus_verbs:класть{}, // класть в сейф
rus_verbs:доставлять{}, // доставлять в кабинет
rus_verbs:приобретать{}, // приобретать в кредит
rus_verbs:сводить{}, // сводить в театр
rus_verbs:унести{}, // унести в могилу
rus_verbs:покатиться{}, // покатиться в яму
rus_verbs:сходить{}, // сходить в магазинчик
rus_verbs:спустить{}, // спустить в канализацию
rus_verbs:проникать{}, // проникать в сердцевину
rus_verbs:метнуть{}, // метнуть в болвана гневный взгляд
rus_verbs:пожаловаться{}, // пожаловаться в администрацию
rus_verbs:стучать{}, // стучать в металлическую дверь
rus_verbs:тащить{}, // тащить в ремонт
rus_verbs:заглядывать{}, // заглядывать в ответы
rus_verbs:плюхнуться{}, // плюхнуться в стол ароматного сена
rus_verbs:увести{}, // увести в следующий кабинет
rus_verbs:успевать{}, // успевать в школу
rus_verbs:пробраться{}, // пробраться в собачью конуру
rus_verbs:подавать{}, // подавать в суд
rus_verbs:прибежать{}, // прибежать в конюшню
rus_verbs:рассмотреть{}, // рассмотреть в микроскоп
rus_verbs:пнуть{}, // пнуть в живот
rus_verbs:завернуть{}, // завернуть в декоративную пленку
rus_verbs:уезжать{}, // уезжать в деревню
rus_verbs:привлекать{}, // привлекать в свои ряды
rus_verbs:перебраться{}, // перебраться в прибрежный город
rus_verbs:долить{}, // долить в коктейль
rus_verbs:палить{}, // палить в нападающих
rus_verbs:отобрать{}, // отобрать в коллекцию
rus_verbs:улететь{}, // улететь в неизвестность
rus_verbs:выглянуть{}, // выглянуть в окно
rus_verbs:выглядывать{}, // выглядывать в окно
rus_verbs:пробираться{}, // грабитель, пробирающийся в дом
инфинитив:написать{ aux stress="напис^ать"}, // читатель, написавший в блог
глагол:написать{ aux stress="напис^ать"},
прилагательное:написавший{ aux stress="напис^авший"},
rus_verbs:свернуть{}, // свернуть в колечко
инфинитив:сползать{ вид:несоверш }, // сползать в овраг
глагол:сползать{ вид:несоверш },
прилагательное:сползающий{ вид:несоверш },
прилагательное:сползавший{ вид:несоверш },
rus_verbs:барабанить{}, // барабанить в дверь
rus_verbs:дописывать{}, // дописывать в конец
rus_verbs:меняться{}, // меняться в лучшую сторону
rus_verbs:измениться{}, // измениться в лучшую сторону
rus_verbs:изменяться{}, // изменяться в лучшую сторону
rus_verbs:вписаться{}, // вписаться в поворот
rus_verbs:вписываться{}, // вписываться в повороты
rus_verbs:переработать{}, // переработать в удобрение
rus_verbs:перерабатывать{}, // перерабатывать в удобрение
rus_verbs:уползать{}, // уползать в тень
rus_verbs:заползать{}, // заползать в нору
rus_verbs:перепрятать{}, // перепрятать в укромное место
rus_verbs:заталкивать{}, // заталкивать в вагон
rus_verbs:преобразовывать{}, // преобразовывать в список
инфинитив:конвертировать{ вид:несоверш }, // конвертировать в список
глагол:конвертировать{ вид:несоверш },
инфинитив:конвертировать{ вид:соверш },
глагол:конвертировать{ вид:соверш },
деепричастие:конвертировав{},
деепричастие:конвертируя{},
rus_verbs:изорвать{}, // Он изорвал газету в клочки.
rus_verbs:выходить{}, // Окна выходят в сад.
rus_verbs:говорить{}, // Он говорил в защиту своего отца.
rus_verbs:вырастать{}, // Он вырастает в большого художника.
rus_verbs:вывести{}, // Он вывел детей в сад.
// инфинитив:всыпать{ вид:соверш }, инфинитив:всыпать{ вид:несоверш },
// глагол:всыпать{ вид:соверш }, глагол:всыпать{ вид:несоверш }, // Он всыпал в воду две ложки соли.
// прилагательное:раненый{}, // Он был ранен в левую руку.
// прилагательное:одетый{}, // Он был одет в толстое осеннее пальто.
rus_verbs:бухнуться{}, // Он бухнулся в воду.
rus_verbs:склонять{}, // склонять защиту в свою пользу
rus_verbs:впиться{}, // Пиявка впилась в тело.
rus_verbs:сходиться{}, // Интеллигенты начала века часто сходились в разные союзы
rus_verbs:сохранять{}, // сохранить данные в файл
rus_verbs:собирать{}, // собирать игрушки в ящик
rus_verbs:упаковывать{}, // упаковывать вещи в чемодан
rus_verbs:обращаться{}, // Обращайтесь ко мне в любое время
rus_verbs:стрельнуть{}, // стрельни в толпу!
rus_verbs:пулять{}, // пуляй в толпу
rus_verbs:пульнуть{}, // пульни в толпу
rus_verbs:становиться{}, // Становитесь в очередь.
rus_verbs:вписать{}, // Юля вписала свое имя в список.
rus_verbs:вписывать{}, // Мы вписывали свои имена в список
прилагательное:видный{}, // Планета Марс видна в обычный бинокль
rus_verbs:пойти{}, // Девочка рано пошла в школу
rus_verbs:отойти{}, // Эти обычаи отошли в историю.
rus_verbs:бить{}, // Холодный ветер бил ему в лицо.
rus_verbs:входить{}, // Это входит в его обязанности.
rus_verbs:принять{}, // меня приняли в пионеры
rus_verbs:уйти{}, // Правительство РФ ушло в отставку
rus_verbs:допустить{}, // Япония была допущена в Организацию Объединённых Наций в 1956 году.
rus_verbs:посвятить{}, // Я посвятил друга в свою тайну.
инфинитив:экспортировать{ вид:несоверш }, глагол:экспортировать{ вид:несоверш }, // экспортировать нефть в страны Востока
rus_verbs:взглянуть{}, // Я не смел взглянуть ему в глаза.
rus_verbs:идти{}, // Я иду гулять в парк.
rus_verbs:вскочить{}, // Я вскочил в трамвай и помчался в институт.
rus_verbs:получить{}, // Эту мебель мы получили в наследство от родителей.
rus_verbs:везти{}, // Учитель везёт детей в лагерь.
rus_verbs:качать{}, // Судно качает во все стороны.
rus_verbs:заезжать{}, // Сегодня вечером я заезжал в магазин за книгами.
rus_verbs:связать{}, // Свяжите свои вещи в узелок.
rus_verbs:пронести{}, // Пронесите стол в дверь.
rus_verbs:вынести{}, // Надо вынести примечания в конец.
rus_verbs:устроить{}, // Она устроила сына в школу.
rus_verbs:угодить{}, // Она угодила головой в дверь.
rus_verbs:отвернуться{}, // Она резко отвернулась в сторону.
rus_verbs:рассматривать{}, // Она рассматривала сцену в бинокль.
rus_verbs:обратить{}, // Война обратила город в развалины.
rus_verbs:сойтись{}, // Мы сошлись в школьные годы.
rus_verbs:приехать{}, // Мы приехали в положенный час.
rus_verbs:встать{}, // Дети встали в круг.
rus_verbs:впасть{}, // Из-за болезни он впал в нужду.
rus_verbs:придти{}, // придти в упадок
rus_verbs:заявить{}, // Надо заявить в милицию о краже.
rus_verbs:заявлять{}, // заявлять в полицию
rus_verbs:ехать{}, // Мы будем ехать в Орёл
rus_verbs:окрашиваться{}, // окрашиваться в красный цвет
rus_verbs:решить{}, // Дело решено в пользу истца.
rus_verbs:сесть{}, // Она села в кресло
rus_verbs:посмотреть{}, // Она посмотрела на себя в зеркало.
rus_verbs:влезать{}, // он влезает в мою квартирку
rus_verbs:попасться{}, // в мою ловушку попалась мышь
rus_verbs:лететь{}, // Мы летим в Орёл
ГЛ_ИНФ(брать), // он берет в свою правую руку очень тяжелый шершавый камень
ГЛ_ИНФ(взять), // Коля взял в руку камень
ГЛ_ИНФ(поехать), // поехать в круиз
ГЛ_ИНФ(подать), // подать в отставку
инфинитив:засыпать{ вид:соверш }, глагол:засыпать{ вид:соверш }, // засыпать песок в ящик
инфинитив:засыпать{ вид:несоверш переходность:переходный }, глагол:засыпать{ вид:несоверш переходность:переходный }, // засыпать песок в ящик
ГЛ_ИНФ(впадать), прилагательное:впадающий{}, прилагательное:впадавший{}, деепричастие:впадая{}, // впадать в море
ГЛ_ИНФ(постучать) // постучать в дверь
}
// Чтобы разрешить связывание в паттернах типа: уйти в BEA Systems
fact гл_предл
{
if context { Гл_В_Вин предлог:в{} @regex("[a-z]+[0-9]*") }
then return true
}
fact гл_предл
{
if context { Гл_В_Вин предлог:в{} *:*{ падеж:вин } }
then return true
}
fact гл_предл
{
if context { глагол:подвывать{} предлог:в{} существительное:такт{ падеж:вин } }
then return true
}
#endregion Винительный
// Все остальные варианты по умолчанию запрещаем.
fact гл_предл
{
if context { * предлог:в{} *:*{ падеж:предл } }
then return false,-3
}
fact гл_предл
{
if context { * предлог:в{} *:*{ падеж:мест } }
then return false,-3
}
fact гл_предл
{
if context { * предлог:в{} *:*{ падеж:вин } }
then return false,-4
}
fact гл_предл
{
if context { * предлог:в{} * }
then return false,-5
}
#endregion Предлог_В
#region Предлог_НА
// ------------------- С ПРЕДЛОГОМ 'НА' ---------------------------
#region ПРЕДЛОЖНЫЙ
// НА+предложный падеж:
// ЛЕЖАТЬ НА СТОЛЕ
#region VerbList
wordentry_set Гл_НА_Предл=
{
rus_verbs:заслушать{}, // Вопрос заслушали на сессии облсовета
rus_verbs:ПРОСТУПАТЬ{}, // На лбу, носу и щеке проступало черное пятно кровоподтека. (ПРОСТУПАТЬ/ПРОСТУПИТЬ)
rus_verbs:ПРОСТУПИТЬ{}, //
rus_verbs:ВИДНЕТЬСЯ{}, // На другой стороне Океана виднелась полоска суши, окружавшая нижний ярус планеты. (ВИДНЕТЬСЯ)
rus_verbs:ЗАВИСАТЬ{}, // Машина умела зависать в воздухе на любой высоте (ЗАВИСАТЬ)
rus_verbs:ЗАМЕРЕТЬ{}, // Скользнув по траве, он замер на боку (ЗАМЕРЕТЬ, локатив)
rus_verbs:ЗАМИРАТЬ{}, //
rus_verbs:ЗАКРЕПИТЬ{}, // Он вручил ей лишний кинжал, который она воткнула в рубаху и закрепила на подоле. (ЗАКРЕПИТЬ)
rus_verbs:УПОЛЗТИ{}, // Зверь завизжал и попытался уползти на двух невредимых передних ногах. (УПОЛЗТИ/УПОЛЗАТЬ)
rus_verbs:УПОЛЗАТЬ{}, //
rus_verbs:БОЛТАТЬСЯ{}, // Тело его будет болтаться на пространственных ветрах, пока не сгниет веревка. (БОЛТАТЬСЯ)
rus_verbs:РАЗВЕРНУТЬ{}, // Филиппины разрешат США развернуть военные базы на своей территории (РАЗВЕРНУТЬ)
rus_verbs:ПОЛУЧИТЬ{}, // Я пытался узнать секреты и получить советы на официальном русскоязычном форуме (ПОЛУЧИТЬ)
rus_verbs:ЗАСИЯТЬ{}, // Он активировал управление, и на экране снова засияло изображение полумесяца. (ЗАСИЯТЬ)
rus_verbs:ВЗОРВАТЬСЯ{}, // Смертник взорвался на предвыборном митинге в Пакистане (ВЗОРВАТЬСЯ)
rus_verbs:искриться{},
rus_verbs:ОДЕРЖИВАТЬ{}, // На выборах в иранский парламент победу одерживают противники действующего президента (ОДЕРЖИВАТЬ)
rus_verbs:ПРЕСЕЧЬ{}, // На Украине пресекли дерзкий побег заключенных на вертолете (ПРЕСЕЧЬ)
rus_verbs:УЛЕТЕТЬ{}, // Голый норвежец улетел на лыжах с трамплина на 60 метров (УЛЕТЕТЬ)
rus_verbs:ПРОХОДИТЬ{}, // укрывающийся в лесу американский подросток проходил инициацию на охоте, выпив кружку крови первого убитого им оленя (ПРОХОДИТЬ)
rus_verbs:СУЩЕСТВОВАТЬ{}, // На Марсе существовали условия для жизни (СУЩЕСТВОВАТЬ)
rus_verbs:УКАЗАТЬ{}, // Победу в Лиге чемпионов укажут на часах (УКАЗАТЬ)
rus_verbs:отвести{}, // отвести душу на людях
rus_verbs:сходиться{}, // Оба профессора сходились на том, что в черепной коробке динозавра
rus_verbs:сойтись{},
rus_verbs:ОБНАРУЖИТЬ{}, // Доказательство наличия подповерхностного океана на Европе обнаружено на её поверхности (ОБНАРУЖИТЬ)
rus_verbs:НАБЛЮДАТЬСЯ{}, // Редкий зодиакальный свет вскоре будет наблюдаться на ночном небе (НАБЛЮДАТЬСЯ)
rus_verbs:ДОСТИГНУТЬ{}, // На всех аварийных реакторах достигнуто состояние так называемой холодной остановки (ДОСТИГНУТЬ/ДОСТИЧЬ)
глагол:ДОСТИЧЬ{},
инфинитив:ДОСТИЧЬ{},
rus_verbs:завершить{}, // Российские биатлонисты завершили чемпионат мира на мажорной ноте
rus_verbs:РАСКЛАДЫВАТЬ{},
rus_verbs:ФОКУСИРОВАТЬСЯ{}, // Инвесторы предпочитают фокусироваться на среднесрочных ожиданиях (ФОКУСИРОВАТЬСЯ)
rus_verbs:ВОСПРИНИМАТЬ{}, // как несерьезно воспринимали его на выборах мэра (ВОСПРИНИМАТЬ)
rus_verbs:БУШЕВАТЬ{}, // на территории Тверской области бушевала гроза , в результате которой произошло отключение электроснабжения в ряде муниципальных образований региона (БУШЕВАТЬ)
rus_verbs:УЧАСТИТЬСЯ{}, // В последние месяцы в зоне ответственности бундесвера на севере Афганистана участились случаи обстрелов полевых лагерей немецких миротворцев (УЧАСТИТЬСЯ)
rus_verbs:ВЫИГРАТЬ{}, // Почему женская сборная России не может выиграть медаль на чемпионате мира (ВЫИГРАТЬ)
rus_verbs:ПРОПАСТЬ{}, // Пропавшим на прогулке актером заинтересовались следователи (ПРОПАСТЬ)
rus_verbs:УБИТЬ{}, // Силовики убили двух боевиков на административной границе Ингушетии и Чечни (УБИТЬ)
rus_verbs:подпрыгнуть{}, // кобель нелепо подпрыгнул на трех ногах , а его хозяин отправил струю пива мимо рта
rus_verbs:подпрыгивать{},
rus_verbs:высветиться{}, // на компьютере высветится твоя подпись
rus_verbs:фигурировать{}, // его портрет фигурирует на страницах печати и телеэкранах
rus_verbs:действовать{}, // выявленный контрабандный канал действовал на постоянной основе
rus_verbs:СОХРАНИТЬСЯ{}, // На рынке международных сделок IPO сохранится высокая активность (СОХРАНИТЬСЯ НА)
rus_verbs:ПРОЙТИ{}, // Необычный конкурс прошёл на севере Швеции (ПРОЙТИ НА предл)
rus_verbs:НАЧАТЬСЯ{}, // На северо-востоке США началась сильная снежная буря. (НАЧАТЬСЯ НА предл)
rus_verbs:ВОЗНИКНУТЬ{}, // Конфликт возник на почве совместной коммерческой деятельности по выращиванию овощей и зелени (ВОЗНИКНУТЬ НА)
rus_verbs:СВЕТИТЬСЯ{}, // она по-прежнему светится на лицах людей (СВЕТИТЬСЯ НА предл)
rus_verbs:ОРГАНИЗОВАТЬ{}, // Власти Москвы намерены организовать масленичные гуляния на 100 площадках (ОРГАНИЗОВАТЬ НА предл)
rus_verbs:ИМЕТЬ{}, // Имея власть на низовом уровне, оказывать самое непосредственное и определяющее влияние на верховную власть (ИМЕТЬ НА предл)
rus_verbs:ОПРОБОВАТЬ{}, // Опробовать и отточить этот инструмент на местных и региональных выборах (ОПРОБОВАТЬ, ОТТОЧИТЬ НА предл)
rus_verbs:ОТТОЧИТЬ{},
rus_verbs:ДОЛОЖИТЬ{}, // Участникам совещания предложено подготовить по этому вопросу свои предложения и доложить на повторной встрече (ДОЛОЖИТЬ НА предл)
rus_verbs:ОБРАЗОВЫВАТЬСЯ{}, // Солевые и пылевые бури , образующиеся на поверхности обнаженной площади моря , уничтожают урожаи и растительность (ОБРАЗОВЫВАТЬСЯ НА)
rus_verbs:СОБРАТЬ{}, // использует собранные на местном рынке депозиты (СОБРАТЬ НА предл)
инфинитив:НАХОДИТЬСЯ{ вид:несоверш}, // находившихся на борту самолета (НАХОДИТЬСЯ НА предл)
глагол:НАХОДИТЬСЯ{ вид:несоверш },
прилагательное:находившийся{ вид:несоверш },
прилагательное:находящийся{ вид:несоверш },
деепричастие:находясь{},
rus_verbs:ГОТОВИТЬ{}, // пищу готовят сами на примусах (ГОТОВИТЬ НА предл)
rus_verbs:РАЗДАТЬСЯ{}, // Они сообщили о сильном хлопке , который раздался на территории нефтебазы (РАЗДАТЬСЯ НА)
rus_verbs:ПОДСКАЛЬЗЫВАТЬСЯ{}, // подскальзываться на той же апельсиновой корке (ПОДСКАЛЬЗЫВАТЬСЯ НА)
rus_verbs:СКРЫТЬСЯ{}, // Германия: латвиец ограбил магазин и попытался скрыться на такси (СКРЫТЬСЯ НА предл)
rus_verbs:ВЫРАСТИТЬ{}, // Пациенту вырастили новый нос на руке (ВЫРАСТИТЬ НА)
rus_verbs:ПРОДЕМОНСТРИРОВАТЬ{}, // Они хотят подчеркнуть эмоциональную тонкость оппозиционера и на этом фоне продемонстрировать бездушность российской власти (ПРОДЕМОНСТРИРОВАТЬ НА предл)
rus_verbs:ОСУЩЕСТВЛЯТЬСЯ{}, // первичный анализ смеси запахов может осуществляться уже на уровне рецепторных нейронов благодаря механизму латерального торможения (ОСУЩЕСТВЛЯТЬСЯ НА)
rus_verbs:ВЫДЕЛЯТЬСЯ{}, // Ягоды брусники, резко выделяющиеся своим красным цветом на фоне зелёной листвы, поедаются животными и птицами (ВЫДЕЛЯТЬСЯ НА)
rus_verbs:РАСКРЫТЬ{}, // На Украине раскрыто крупное мошенничество в сфере туризма (РАСКРЫТЬ НА)
rus_verbs:ОБЖАРИВАТЬСЯ{}, // Омлет обжаривается на сливочном масле с одной стороны, пока он почти полностью не загустеет (ОБЖАРИВАТЬСЯ НА)
rus_verbs:ПРИГОТОВЛЯТЬ{}, // Яичница — блюдо европейской кухни, приготовляемое на сковороде из разбитых яиц (ПРИГОТОВЛЯТЬ НА)
rus_verbs:РАССАДИТЬ{}, // Женька рассадил игрушки на скамеечке (РАССАДИТЬ НА)
rus_verbs:ОБОЖДАТЬ{}, // обожди Анжелу на остановке троллейбуса (ОБОЖДАТЬ НА)
rus_verbs:УЧИТЬСЯ{}, // Марина учится на факультете журналистики (УЧИТЬСЯ НА предл)
rus_verbs:раскладываться{}, // Созревшие семенные экземпляры раскладывают на солнце или в теплом месте, где они делаются мягкими (РАСКЛАДЫВАТЬСЯ В, НА)
rus_verbs:ПОСЛУШАТЬ{}, // Послушайте друзей и врагов на расстоянии! (ПОСЛУШАТЬ НА)
rus_verbs:ВЕСТИСЬ{}, // На стороне противника всю ночь велась перегруппировка сил. (ВЕСТИСЬ НА)
rus_verbs:ПОИНТЕРЕСОВАТЬСЯ{}, // корреспондент поинтересовался у людей на улице (ПОИНТЕРЕСОВАТЬСЯ НА)
rus_verbs:ОТКРЫВАТЬСЯ{}, // Российские биржи открываются на негативном фоне (ОТКРЫВАТЬСЯ НА)
rus_verbs:СХОДИТЬ{}, // Вы сходите на следующей остановке? (СХОДИТЬ НА)
rus_verbs:ПОГИБНУТЬ{}, // Её отец погиб на войне. (ПОГИБНУТЬ НА)
rus_verbs:ВЫЙТИ{}, // Книга выйдет на будущей неделе. (ВЫЙТИ НА предл)
rus_verbs:НЕСТИСЬ{}, // Корабль несётся на всех парусах. (НЕСТИСЬ НА предл)
rus_verbs:вкалывать{}, // Папа вкалывает на работе, чтобы прокормить семью (вкалывать на)
rus_verbs:доказать{}, // разработчики доказали на практике применимость данного подхода к обсчету сцен (доказать на, применимость к)
rus_verbs:хулиганить{}, // дозволять кому-то хулиганить на кладбище (хулиганить на)
глагол:вычитать{вид:соверш}, инфинитив:вычитать{вид:соверш}, // вычитать на сайте (вычитать на сайте)
деепричастие:вычитав{},
rus_verbs:аккомпанировать{}, // он аккомпанировал певцу на губной гармошке (аккомпанировать на)
rus_verbs:набрать{}, // статья с заголовком, набранным на компьютере
rus_verbs:сделать{}, // книга с иллюстрацией, сделанной на компьютере
rus_verbs:развалиться{}, // Антонио развалился на диване
rus_verbs:улечься{}, // Антонио улегся на полу
rus_verbs:зарубить{}, // Заруби себе на носу.
rus_verbs:ценить{}, // Его ценят на заводе.
rus_verbs:вернуться{}, // Отец вернулся на закате.
rus_verbs:шить{}, // Вы умеете шить на машинке?
rus_verbs:бить{}, // Скот бьют на бойне.
rus_verbs:выехать{}, // Мы выехали на рассвете.
rus_verbs:валяться{}, // На полу валяется бумага.
rus_verbs:разложить{}, // она разложила полотенце на песке
rus_verbs:заниматься{}, // я занимаюсь на тренажере
rus_verbs:позаниматься{},
rus_verbs:порхать{}, // порхать на лугу
rus_verbs:пресекать{}, // пресекать на корню
rus_verbs:изъясняться{}, // изъясняться на непонятном языке
rus_verbs:развесить{}, // развесить на столбах
rus_verbs:обрасти{}, // обрасти на южной части
rus_verbs:откладываться{}, // откладываться на стенках артерий
rus_verbs:уносить{}, // уносить на носилках
rus_verbs:проплыть{}, // проплыть на плоту
rus_verbs:подъезжать{}, // подъезжать на повозках
rus_verbs:пульсировать{}, // пульсировать на лбу
rus_verbs:рассесться{}, // птицы расселись на ветках
rus_verbs:застопориться{}, // застопориться на первом пункте
rus_verbs:изловить{}, // изловить на окраинах
rus_verbs:покататься{}, // покататься на машинках
rus_verbs:залопотать{}, // залопотать на неизвестном языке
rus_verbs:растягивать{}, // растягивать на станке
rus_verbs:поделывать{}, // поделывать на пляже
rus_verbs:подстеречь{}, // подстеречь на площадке
rus_verbs:проектировать{}, // проектировать на компьютере
rus_verbs:притулиться{}, // притулиться на кушетке
rus_verbs:дозволять{}, // дозволять кому-то хулиганить на кладбище
rus_verbs:пострелять{}, // пострелять на испытательном полигоне
rus_verbs:засиживаться{}, // засиживаться на работе
rus_verbs:нежиться{}, // нежиться на солнышке
rus_verbs:притомиться{}, // притомиться на рабочем месте
rus_verbs:поселяться{}, // поселяться на чердаке
rus_verbs:потягиваться{}, // потягиваться на земле
rus_verbs:отлеживаться{}, // отлеживаться на койке
rus_verbs:протаранить{}, // протаранить на танке
rus_verbs:гарцевать{}, // гарцевать на коне
rus_verbs:облупиться{}, // облупиться на носу
rus_verbs:оговорить{}, // оговорить на собеседовании
rus_verbs:зарегистрироваться{}, // зарегистрироваться на сайте
rus_verbs:отпечатать{}, // отпечатать на картоне
rus_verbs:сэкономить{}, // сэкономить на мелочах
rus_verbs:покатать{}, // покатать на пони
rus_verbs:колесить{}, // колесить на старой машине
rus_verbs:понастроить{}, // понастроить на участках
rus_verbs:поджарить{}, // поджарить на костре
rus_verbs:узнаваться{}, // узнаваться на фотографии
rus_verbs:отощать{}, // отощать на казенных харчах
rus_verbs:редеть{}, // редеть на макушке
rus_verbs:оглашать{}, // оглашать на общем собрании
rus_verbs:лопотать{}, // лопотать на иврите
rus_verbs:пригреть{}, // пригреть на груди
rus_verbs:консультироваться{}, // консультироваться на форуме
rus_verbs:приноситься{}, // приноситься на одежде
rus_verbs:сушиться{}, // сушиться на балконе
rus_verbs:наследить{}, // наследить на полу
rus_verbs:нагреться{}, // нагреться на солнце
rus_verbs:рыбачить{}, // рыбачить на озере
rus_verbs:прокатить{}, // прокатить на выборах
rus_verbs:запинаться{}, // запинаться на ровном месте
rus_verbs:отрубиться{}, // отрубиться на мягкой подушке
rus_verbs:заморозить{}, // заморозить на улице
rus_verbs:промерзнуть{}, // промерзнуть на открытом воздухе
rus_verbs:просохнуть{}, // просохнуть на батарее
rus_verbs:развозить{}, // развозить на велосипеде
rus_verbs:прикорнуть{}, // прикорнуть на диванчике
rus_verbs:отпечататься{}, // отпечататься на коже
rus_verbs:выявлять{}, // выявлять на таможне
rus_verbs:расставлять{}, // расставлять на башнях
rus_verbs:прокрутить{}, // прокрутить на пальце
rus_verbs:умываться{}, // умываться на улице
rus_verbs:пересказывать{}, // пересказывать на страницах романа
rus_verbs:удалять{}, // удалять на пуховике
rus_verbs:хозяйничать{}, // хозяйничать на складе
rus_verbs:оперировать{}, // оперировать на поле боя
rus_verbs:поносить{}, // поносить на голове
rus_verbs:замурлыкать{}, // замурлыкать на коленях
rus_verbs:передвигать{}, // передвигать на тележке
rus_verbs:прочертить{}, // прочертить на земле
rus_verbs:колдовать{}, // колдовать на кухне
rus_verbs:отвозить{}, // отвозить на казенном транспорте
rus_verbs:трахать{}, // трахать на природе
rus_verbs:мастерить{}, // мастерить на кухне
rus_verbs:ремонтировать{}, // ремонтировать на коленке
rus_verbs:развезти{}, // развезти на велосипеде
rus_verbs:робеть{}, // робеть на сцене
инфинитив:реализовать{ вид:несоверш }, инфинитив:реализовать{ вид:соверш }, // реализовать на сайте
глагол:реализовать{ вид:несоверш }, глагол:реализовать{ вид:соверш },
деепричастие:реализовав{}, деепричастие:реализуя{},
rus_verbs:покаяться{}, // покаяться на смертном одре
rus_verbs:специализироваться{}, // специализироваться на тестировании
rus_verbs:попрыгать{}, // попрыгать на батуте
rus_verbs:переписывать{}, // переписывать на столе
rus_verbs:расписывать{}, // расписывать на доске
rus_verbs:зажимать{}, // зажимать на запястье
rus_verbs:практиковаться{}, // практиковаться на мышах
rus_verbs:уединиться{}, // уединиться на чердаке
rus_verbs:подохнуть{}, // подохнуть на чужбине
rus_verbs:приподниматься{}, // приподниматься на руках
rus_verbs:уродиться{}, // уродиться на полях
rus_verbs:продолжиться{}, // продолжиться на улице
rus_verbs:посапывать{}, // посапывать на диване
rus_verbs:ободрать{}, // ободрать на спине
rus_verbs:скрючиться{}, // скрючиться на песке
rus_verbs:тормознуть{}, // тормознуть на перекрестке
rus_verbs:лютовать{}, // лютовать на хуторе
rus_verbs:зарегистрировать{}, // зарегистрировать на сайте
rus_verbs:переждать{}, // переждать на вершине холма
rus_verbs:доминировать{}, // доминировать на территории
rus_verbs:публиковать{}, // публиковать на сайте
rus_verbs:морщить{}, // морщить на лбу
rus_verbs:сконцентрироваться{}, // сконцентрироваться на главном
rus_verbs:подрабатывать{}, // подрабатывать на рынке
rus_verbs:репетировать{}, // репетировать на заднем дворе
rus_verbs:подвернуть{}, // подвернуть на брусчатке
rus_verbs:зашелестеть{}, // зашелестеть на ветру
rus_verbs:расчесывать{}, // расчесывать на спине
rus_verbs:одевать{}, // одевать на рынке
rus_verbs:испечь{}, // испечь на углях
rus_verbs:сбрить{}, // сбрить на затылке
rus_verbs:согреться{}, // согреться на печке
rus_verbs:замаячить{}, // замаячить на горизонте
rus_verbs:пересчитывать{}, // пересчитывать на пальцах
rus_verbs:галдеть{}, // галдеть на крыльце
rus_verbs:переплыть{}, // переплыть на плоту
rus_verbs:передохнуть{}, // передохнуть на скамейке
rus_verbs:прижиться{}, // прижиться на ферме
rus_verbs:переправляться{}, // переправляться на плотах
rus_verbs:накупить{}, // накупить на блошином рынке
rus_verbs:проторчать{}, // проторчать на виду
rus_verbs:мокнуть{}, // мокнуть на улице
rus_verbs:застукать{}, // застукать на камбузе
rus_verbs:завязывать{}, // завязывать на ботинках
rus_verbs:повисать{}, // повисать на ветке
rus_verbs:подвизаться{}, // подвизаться на государственной службе
rus_verbs:кормиться{}, // кормиться на болоте
rus_verbs:покурить{}, // покурить на улице
rus_verbs:зимовать{}, // зимовать на болотах
rus_verbs:застегивать{}, // застегивать на гимнастерке
rus_verbs:поигрывать{}, // поигрывать на гитаре
rus_verbs:погореть{}, // погореть на махинациях с землей
rus_verbs:кувыркаться{}, // кувыркаться на батуте
rus_verbs:похрапывать{}, // похрапывать на диване
rus_verbs:пригревать{}, // пригревать на груди
rus_verbs:завязнуть{}, // завязнуть на болоте
rus_verbs:шастать{}, // шастать на втором этаже
rus_verbs:заночевать{}, // заночевать на сеновале
rus_verbs:отсиживаться{}, // отсиживаться на чердаке
rus_verbs:мчать{}, // мчать на байке
rus_verbs:сгнить{}, // сгнить на урановых рудниках
rus_verbs:тренировать{}, // тренировать на манекенах
rus_verbs:повеселиться{}, // повеселиться на празднике
rus_verbs:измучиться{}, // измучиться на болоте
rus_verbs:увянуть{}, // увянуть на подоконнике
rus_verbs:раскрутить{}, // раскрутить на оси
rus_verbs:выцвести{}, // выцвести на солнечном свету
rus_verbs:изготовлять{}, // изготовлять на коленке
rus_verbs:гнездиться{}, // гнездиться на вершине дерева
rus_verbs:разогнаться{}, // разогнаться на мотоцикле
rus_verbs:излагаться{}, // излагаться на страницах доклада
rus_verbs:сконцентрировать{}, // сконцентрировать на левом фланге
rus_verbs:расчесать{}, // расчесать на макушке
rus_verbs:плавиться{}, // плавиться на солнце
rus_verbs:редактировать{}, // редактировать на ноутбуке
rus_verbs:подскакивать{}, // подскакивать на месте
rus_verbs:покупаться{}, // покупаться на рынке
rus_verbs:промышлять{}, // промышлять на мелководье
rus_verbs:приобретаться{}, // приобретаться на распродажах
rus_verbs:наигрывать{}, // наигрывать на банджо
rus_verbs:маневрировать{}, // маневрировать на флангах
rus_verbs:запечатлеться{}, // запечатлеться на записях камер
rus_verbs:укрывать{}, // укрывать на чердаке
rus_verbs:подорваться{}, // подорваться на фугасе
rus_verbs:закрепиться{}, // закрепиться на занятых позициях
rus_verbs:громыхать{}, // громыхать на кухне
инфинитив:подвигаться{ вид:соверш }, глагол:подвигаться{ вид:соверш }, // подвигаться на полу
деепричастие:подвигавшись{},
rus_verbs:добываться{}, // добываться на территории Анголы
rus_verbs:приплясывать{}, // приплясывать на сцене
rus_verbs:доживать{}, // доживать на больничной койке
rus_verbs:отпраздновать{}, // отпраздновать на работе
rus_verbs:сгубить{}, // сгубить на корню
rus_verbs:схоронить{}, // схоронить на кладбище
rus_verbs:тускнеть{}, // тускнеть на солнце
rus_verbs:скопить{}, // скопить на счету
rus_verbs:помыть{}, // помыть на своем этаже
rus_verbs:пороть{}, // пороть на конюшне
rus_verbs:наличествовать{}, // наличествовать на складе
rus_verbs:нащупывать{}, // нащупывать на полке
rus_verbs:змеиться{}, // змеиться на дне
rus_verbs:пожелтеть{}, // пожелтеть на солнце
rus_verbs:заостриться{}, // заостриться на конце
rus_verbs:свезти{}, // свезти на поле
rus_verbs:прочувствовать{}, // прочувствовать на своей шкуре
rus_verbs:подкрутить{}, // подкрутить на приборной панели
rus_verbs:рубиться{}, // рубиться на мечах
rus_verbs:сиживать{}, // сиживать на крыльце
rus_verbs:тараторить{}, // тараторить на иностранном языке
rus_verbs:теплеть{}, // теплеть на сердце
rus_verbs:покачаться{}, // покачаться на ветке
rus_verbs:сосредоточиваться{}, // сосредоточиваться на главной задаче
rus_verbs:развязывать{}, // развязывать на ботинках
rus_verbs:подвозить{}, // подвозить на мотороллере
rus_verbs:вышивать{}, // вышивать на рубашке
rus_verbs:скупать{}, // скупать на открытом рынке
rus_verbs:оформлять{}, // оформлять на встрече
rus_verbs:распускаться{}, // распускаться на клумбах
rus_verbs:прогореть{}, // прогореть на спекуляциях
rus_verbs:приползти{}, // приползти на коленях
rus_verbs:загореть{}, // загореть на пляже
rus_verbs:остудить{}, // остудить на балконе
rus_verbs:нарвать{}, // нарвать на поляне
rus_verbs:издохнуть{}, // издохнуть на болоте
rus_verbs:разгружать{}, // разгружать на дороге
rus_verbs:произрастать{}, // произрастать на болотах
rus_verbs:разуться{}, // разуться на коврике
rus_verbs:сооружать{}, // сооружать на площади
rus_verbs:зачитывать{}, // зачитывать на митинге
rus_verbs:уместиться{}, // уместиться на ладони
rus_verbs:закупить{}, // закупить на рынке
rus_verbs:горланить{}, // горланить на улице
rus_verbs:экономить{}, // экономить на спичках
rus_verbs:исправлять{}, // исправлять на доске
rus_verbs:расслабляться{}, // расслабляться на лежаке
rus_verbs:скапливаться{}, // скапливаться на крыше
rus_verbs:сплетничать{}, // сплетничать на скамеечке
rus_verbs:отъезжать{}, // отъезжать на лимузине
rus_verbs:отчитывать{}, // отчитывать на собрании
rus_verbs:сфокусировать{}, // сфокусировать на удаленной точке
rus_verbs:потчевать{}, // потчевать на лаврах
rus_verbs:окопаться{}, // окопаться на окраине
rus_verbs:загорать{}, // загорать на пляже
rus_verbs:обгореть{}, // обгореть на солнце
rus_verbs:распознавать{}, // распознавать на фотографии
rus_verbs:заплетаться{}, // заплетаться на макушке
rus_verbs:перегреться{}, // перегреться на жаре
rus_verbs:подметать{}, // подметать на крыльце
rus_verbs:нарисоваться{}, // нарисоваться на горизонте
rus_verbs:проскакивать{}, // проскакивать на экране
rus_verbs:попивать{}, // попивать на балконе чай
rus_verbs:отплывать{}, // отплывать на лодке
rus_verbs:чирикать{}, // чирикать на ветках
rus_verbs:скупить{}, // скупить на оптовых базах
rus_verbs:наколоть{}, // наколоть на коже картинку
rus_verbs:созревать{}, // созревать на ветке
rus_verbs:проколоться{}, // проколоться на мелочи
rus_verbs:крутнуться{}, // крутнуться на заднем колесе
rus_verbs:переночевать{}, // переночевать на постоялом дворе
rus_verbs:концентрироваться{}, // концентрироваться на фильтре
rus_verbs:одичать{}, // одичать на хуторе
rus_verbs:спасаться{}, // спасаются на лодке
rus_verbs:доказываться{}, // доказываться на страницах книги
rus_verbs:познаваться{}, // познаваться на ринге
rus_verbs:замыкаться{}, // замыкаться на металлическом предмете
rus_verbs:заприметить{}, // заприметить на пригорке
rus_verbs:продержать{}, // продержать на морозе
rus_verbs:форсировать{}, // форсировать на плотах
rus_verbs:сохнуть{}, // сохнуть на солнце
rus_verbs:выявить{}, // выявить на поверхности
rus_verbs:заседать{}, // заседать на кафедре
rus_verbs:расплачиваться{}, // расплачиваться на выходе
rus_verbs:светлеть{}, // светлеть на горизонте
rus_verbs:залепетать{}, // залепетать на незнакомом языке
rus_verbs:подсчитывать{}, // подсчитывать на пальцах
rus_verbs:зарыть{}, // зарыть на пустыре
rus_verbs:сформироваться{}, // сформироваться на месте
rus_verbs:развертываться{}, // развертываться на площадке
rus_verbs:набивать{}, // набивать на манекенах
rus_verbs:замерзать{}, // замерзать на ветру
rus_verbs:схватывать{}, // схватывать на лету
rus_verbs:перевестись{}, // перевестись на Руси
rus_verbs:смешивать{}, // смешивать на блюдце
rus_verbs:прождать{}, // прождать на входе
rus_verbs:мерзнуть{}, // мерзнуть на ветру
rus_verbs:растирать{}, // растирать на коже
rus_verbs:переспать{}, // переспал на сеновале
rus_verbs:рассекать{}, // рассекать на скутере
rus_verbs:опровергнуть{}, // опровергнуть на высшем уровне
rus_verbs:дрыхнуть{}, // дрыхнуть на диване
rus_verbs:распять{}, // распять на кресте
rus_verbs:запечься{}, // запечься на костре
rus_verbs:застилать{}, // застилать на балконе
rus_verbs:сыскаться{}, // сыскаться на огороде
rus_verbs:разориться{}, // разориться на продаже спичек
rus_verbs:переделать{}, // переделать на станке
rus_verbs:разъяснять{}, // разъяснять на страницах газеты
rus_verbs:поседеть{}, // поседеть на висках
rus_verbs:протащить{}, // протащить на спине
rus_verbs:осуществиться{}, // осуществиться на деле
rus_verbs:селиться{}, // селиться на окраине
rus_verbs:оплачивать{}, // оплачивать на первой кассе
rus_verbs:переворачивать{}, // переворачивать на сковородке
rus_verbs:упражняться{}, // упражняться на батуте
rus_verbs:испробовать{}, // испробовать на себе
rus_verbs:разгладиться{}, // разгладиться на спине
rus_verbs:рисоваться{}, // рисоваться на стекле
rus_verbs:продрогнуть{}, // продрогнуть на морозе
rus_verbs:пометить{}, // пометить на доске
rus_verbs:приютить{}, // приютить на чердаке
rus_verbs:избирать{}, // избирать на первых свободных выборах
rus_verbs:затеваться{}, // затеваться на матче
rus_verbs:уплывать{}, // уплывать на катере
rus_verbs:замерцать{}, // замерцать на рекламном щите
rus_verbs:фиксироваться{}, // фиксироваться на достигнутом уровне
rus_verbs:запираться{}, // запираться на чердаке
rus_verbs:загубить{}, // загубить на корню
rus_verbs:развеяться{}, // развеяться на природе
rus_verbs:съезжаться{}, // съезжаться на лимузинах
rus_verbs:потанцевать{}, // потанцевать на могиле
rus_verbs:дохнуть{}, // дохнуть на солнце
rus_verbs:припарковаться{}, // припарковаться на газоне
rus_verbs:отхватить{}, // отхватить на распродаже
rus_verbs:остывать{}, // остывать на улице
rus_verbs:переваривать{}, // переваривать на высокой ветке
rus_verbs:подвесить{}, // подвесить на веревке
rus_verbs:хвастать{}, // хвастать на работе
rus_verbs:отрабатывать{}, // отрабатывать на уборке урожая
rus_verbs:разлечься{}, // разлечься на полу
rus_verbs:очертить{}, // очертить на полу
rus_verbs:председательствовать{}, // председательствовать на собрании
rus_verbs:сконфузиться{}, // сконфузиться на сцене
rus_verbs:выявляться{}, // выявляться на ринге
rus_verbs:крутануться{}, // крутануться на заднем колесе
rus_verbs:караулить{}, // караулить на входе
rus_verbs:перечислять{}, // перечислять на пальцах
rus_verbs:обрабатывать{}, // обрабатывать на станке
rus_verbs:настигать{}, // настигать на берегу
rus_verbs:разгуливать{}, // разгуливать на берегу
rus_verbs:насиловать{}, // насиловать на пляже
rus_verbs:поредеть{}, // поредеть на макушке
rus_verbs:учитывать{}, // учитывать на балансе
rus_verbs:зарождаться{}, // зарождаться на большой глубине
rus_verbs:распространять{}, // распространять на сайтах
rus_verbs:пировать{}, // пировать на вершине холма
rus_verbs:начертать{}, // начертать на стене
rus_verbs:расцветать{}, // расцветать на подоконнике
rus_verbs:умнеть{}, // умнеть на глазах
rus_verbs:царствовать{}, // царствовать на окраине
rus_verbs:закрутиться{}, // закрутиться на работе
rus_verbs:отработать{}, // отработать на шахте
rus_verbs:полечь{}, // полечь на поле брани
rus_verbs:щебетать{}, // щебетать на ветке
rus_verbs:подчеркиваться{}, // подчеркиваться на сайте
rus_verbs:посеять{}, // посеять на другом поле
rus_verbs:замечаться{}, // замечаться на пастбище
rus_verbs:просчитать{}, // просчитать на пальцах
rus_verbs:голосовать{}, // голосовать на трассе
rus_verbs:маяться{}, // маяться на пляже
rus_verbs:сколотить{}, // сколотить на службе
rus_verbs:обретаться{}, // обретаться на чужбине
rus_verbs:обливаться{}, // обливаться на улице
rus_verbs:катать{}, // катать на лошадке
rus_verbs:припрятать{}, // припрятать на теле
rus_verbs:запаниковать{}, // запаниковать на экзамене
инфинитив:слетать{ вид:соверш }, глагол:слетать{ вид:соверш }, // слетать на частном самолете
деепричастие:слетав{},
rus_verbs:срубить{}, // срубить денег на спекуляциях
rus_verbs:зажигаться{}, // зажигаться на улице
rus_verbs:жарить{}, // жарить на углях
rus_verbs:накапливаться{}, // накапливаться на счету
rus_verbs:распуститься{}, // распуститься на грядке
rus_verbs:рассаживаться{}, // рассаживаться на местах
rus_verbs:странствовать{}, // странствовать на лошади
rus_verbs:осматриваться{}, // осматриваться на месте
rus_verbs:разворачивать{}, // разворачивать на завоеванной территории
rus_verbs:согревать{}, // согревать на вершине горы
rus_verbs:заскучать{}, // заскучать на вахте
rus_verbs:перекусить{}, // перекусить на бегу
rus_verbs:приплыть{}, // приплыть на тримаране
rus_verbs:зажигать{}, // зажигать на танцах
rus_verbs:закопать{}, // закопать на поляне
rus_verbs:стирать{}, // стирать на берегу
rus_verbs:подстерегать{}, // подстерегать на подходе
rus_verbs:погулять{}, // погулять на свадьбе
rus_verbs:огласить{}, // огласить на митинге
rus_verbs:разбогатеть{}, // разбогатеть на прииске
rus_verbs:грохотать{}, // грохотать на чердаке
rus_verbs:расположить{}, // расположить на границе
rus_verbs:реализоваться{}, // реализоваться на новой работе
rus_verbs:застывать{}, // застывать на морозе
rus_verbs:запечатлеть{}, // запечатлеть на пленке
rus_verbs:тренироваться{}, // тренироваться на манекене
rus_verbs:поспорить{}, // поспорить на совещании
rus_verbs:затягивать{}, // затягивать на поясе
rus_verbs:зиждиться{}, // зиждиться на твердой основе
rus_verbs:построиться{}, // построиться на песке
rus_verbs:надрываться{}, // надрываться на работе
rus_verbs:закипать{}, // закипать на плите
rus_verbs:затонуть{}, // затонуть на мелководье
rus_verbs:побыть{}, // побыть на фазенде
rus_verbs:сгорать{}, // сгорать на солнце
инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать на улице
деепричастие:пописав{ aux stress="поп^исав" },
rus_verbs:подраться{}, // подраться на сцене
rus_verbs:заправить{}, // заправить на последней заправке
rus_verbs:обозначаться{}, // обозначаться на карте
rus_verbs:просиживать{}, // просиживать на берегу
rus_verbs:начертить{}, // начертить на листке
rus_verbs:тормозить{}, // тормозить на льду
rus_verbs:затевать{}, // затевать на космической базе
rus_verbs:задерживать{}, // задерживать на таможне
rus_verbs:прилетать{}, // прилетать на частном самолете
rus_verbs:полулежать{}, // полулежать на травке
rus_verbs:ерзать{}, // ерзать на табуретке
rus_verbs:покопаться{}, // покопаться на складе
rus_verbs:подвезти{}, // подвезти на машине
rus_verbs:полежать{}, // полежать на водном матрасе
rus_verbs:стыть{}, // стыть на улице
rus_verbs:стынуть{}, // стынуть на улице
rus_verbs:скреститься{}, // скреститься на груди
rus_verbs:припарковать{}, // припарковать на стоянке
rus_verbs:здороваться{}, // здороваться на кафедре
rus_verbs:нацарапать{}, // нацарапать на парте
rus_verbs:откопать{}, // откопать на поляне
rus_verbs:смастерить{}, // смастерить на коленках
rus_verbs:довезти{}, // довезти на машине
rus_verbs:избивать{}, // избивать на крыше
rus_verbs:сварить{}, // сварить на костре
rus_verbs:истребить{}, // истребить на корню
rus_verbs:раскопать{}, // раскопать на болоте
rus_verbs:попить{}, // попить на кухне
rus_verbs:заправлять{}, // заправлять на базе
rus_verbs:кушать{}, // кушать на кухне
rus_verbs:замолкать{}, // замолкать на половине фразы
rus_verbs:измеряться{}, // измеряться на весах
rus_verbs:сбываться{}, // сбываться на самом деле
rus_verbs:изображаться{}, // изображается на сцене
rus_verbs:фиксировать{}, // фиксировать на данной высоте
rus_verbs:ослаблять{}, // ослаблять на шее
rus_verbs:зреть{}, // зреть на грядке
rus_verbs:зеленеть{}, // зеленеть на грядке
rus_verbs:критиковать{}, // критиковать на страницах газеты
rus_verbs:облететь{}, // облететь на самолете
rus_verbs:заразиться{}, // заразиться на работе
rus_verbs:рассеять{}, // рассеять на территории
rus_verbs:печься{}, // печься на костре
rus_verbs:поспать{}, // поспать на земле
rus_verbs:сплетаться{}, // сплетаться на макушке
rus_verbs:удерживаться{}, // удерживаться на расстоянии
rus_verbs:помешаться{}, // помешаться на чистоте
rus_verbs:ликвидировать{}, // ликвидировать на полигоне
rus_verbs:проваляться{}, // проваляться на диване
rus_verbs:лечиться{}, // лечиться на дому
rus_verbs:обработать{}, // обработать на станке
rus_verbs:защелкнуть{}, // защелкнуть на руках
rus_verbs:разносить{}, // разносить на одежде
rus_verbs:чесать{}, // чесать на груди
rus_verbs:наладить{}, // наладить на конвейере выпуск
rus_verbs:отряхнуться{}, // отряхнуться на улице
rus_verbs:разыгрываться{}, // разыгрываться на скачках
rus_verbs:обеспечиваться{}, // обеспечиваться на выгодных условиях
rus_verbs:греться{}, // греться на вокзале
rus_verbs:засидеться{}, // засидеться на одном месте
rus_verbs:материализоваться{}, // материализоваться на границе
rus_verbs:рассеиваться{}, // рассеиваться на высоте вершин
rus_verbs:перевозить{}, // перевозить на платформе
rus_verbs:поиграть{}, // поиграть на скрипке
rus_verbs:потоптаться{}, // потоптаться на одном месте
rus_verbs:переправиться{}, // переправиться на плоту
rus_verbs:забрезжить{}, // забрезжить на горизонте
rus_verbs:завывать{}, // завывать на опушке
rus_verbs:заваривать{}, // заваривать на кухоньке
rus_verbs:перемещаться{}, // перемещаться на спасательном плоту
инфинитив:писаться{ aux stress="пис^аться" }, глагол:писаться{ aux stress="пис^аться" }, // писаться на бланке
rus_verbs:праздновать{}, // праздновать на улицах
rus_verbs:обучить{}, // обучить на корте
rus_verbs:орудовать{}, // орудовать на складе
rus_verbs:подрасти{}, // подрасти на глядке
rus_verbs:шелестеть{}, // шелестеть на ветру
rus_verbs:раздеваться{}, // раздеваться на публике
rus_verbs:пообедать{}, // пообедать на газоне
rus_verbs:жрать{}, // жрать на помойке
rus_verbs:исполняться{}, // исполняться на флейте
rus_verbs:похолодать{}, // похолодать на улице
rus_verbs:гнить{}, // гнить на каторге
rus_verbs:прослушать{}, // прослушать на концерте
rus_verbs:совещаться{}, // совещаться на заседании
rus_verbs:покачивать{}, // покачивать на волнах
rus_verbs:отсидеть{}, // отсидеть на гаупвахте
rus_verbs:формировать{}, // формировать на секретной базе
rus_verbs:захрапеть{}, // захрапеть на кровати
rus_verbs:объехать{}, // объехать на попутке
rus_verbs:поселить{}, // поселить на верхних этажах
rus_verbs:заворочаться{}, // заворочаться на сене
rus_verbs:напрятать{}, // напрятать на теле
rus_verbs:очухаться{}, // очухаться на земле
rus_verbs:полистать{}, // полистать на досуге
rus_verbs:завертеть{}, // завертеть на шесте
rus_verbs:печатать{}, // печатать на ноуте
rus_verbs:отыскаться{}, // отыскаться на складе
rus_verbs:зафиксировать{}, // зафиксировать на пленке
rus_verbs:расстилаться{}, // расстилаться на столе
rus_verbs:заместить{}, // заместить на посту
rus_verbs:угасать{}, // угасать на неуправляемом корабле
rus_verbs:сразить{}, // сразить на ринге
rus_verbs:расплываться{}, // расплываться на жаре
rus_verbs:сосчитать{}, // сосчитать на пальцах
rus_verbs:сгуститься{}, // сгуститься на небольшой высоте
rus_verbs:цитировать{}, // цитировать на плите
rus_verbs:ориентироваться{}, // ориентироваться на местности
rus_verbs:расширить{}, // расширить на другом конце
rus_verbs:обтереть{}, // обтереть на стоянке
rus_verbs:подстрелить{}, // подстрелить на охоте
rus_verbs:растереть{}, // растереть на твердой поверхности
rus_verbs:подавлять{}, // подавлять на первом этапе
rus_verbs:смешиваться{}, // смешиваться на поверхности
// инфинитив:вычитать{ aux stress="в^ычитать" }, глагол:вычитать{ aux stress="в^ычитать" }, // вычитать на сайте
// деепричастие:вычитав{},
rus_verbs:сократиться{}, // сократиться на втором этапе
rus_verbs:занервничать{}, // занервничать на экзамене
rus_verbs:соприкоснуться{}, // соприкоснуться на трассе
rus_verbs:обозначить{}, // обозначить на плане
rus_verbs:обучаться{}, // обучаться на производстве
rus_verbs:снизиться{}, // снизиться на большой высоте
rus_verbs:простудиться{}, // простудиться на ветру
rus_verbs:поддерживаться{}, // поддерживается на встрече
rus_verbs:уплыть{}, // уплыть на лодочке
rus_verbs:резвиться{}, // резвиться на песочке
rus_verbs:поерзать{}, // поерзать на скамеечке
rus_verbs:похвастаться{}, // похвастаться на встрече
rus_verbs:знакомиться{}, // знакомиться на уроке
rus_verbs:проплывать{}, // проплывать на катере
rus_verbs:засесть{}, // засесть на чердаке
rus_verbs:подцепить{}, // подцепить на дискотеке
rus_verbs:обыскать{}, // обыскать на входе
rus_verbs:оправдаться{}, // оправдаться на суде
rus_verbs:раскрываться{}, // раскрываться на сцене
rus_verbs:одеваться{}, // одеваться на вещевом рынке
rus_verbs:засветиться{}, // засветиться на фотографиях
rus_verbs:употребляться{}, // употребляться на птицефабриках
rus_verbs:грабить{}, // грабить на пустыре
rus_verbs:гонять{}, // гонять на повышенных оборотах
rus_verbs:развеваться{}, // развеваться на древке
rus_verbs:основываться{}, // основываться на безусловных фактах
rus_verbs:допрашивать{}, // допрашивать на базе
rus_verbs:проработать{}, // проработать на стройке
rus_verbs:сосредоточить{}, // сосредоточить на месте
rus_verbs:сочинять{}, // сочинять на ходу
rus_verbs:ползать{}, // ползать на камне
rus_verbs:раскинуться{}, // раскинуться на пустыре
rus_verbs:уставать{}, // уставать на работе
rus_verbs:укрепить{}, // укрепить на конце
rus_verbs:образовывать{}, // образовывать на открытом воздухе взрывоопасную смесь
rus_verbs:одобрять{}, // одобрять на словах
rus_verbs:приговорить{}, // приговорить на заседании тройки
rus_verbs:чернеть{}, // чернеть на свету
rus_verbs:гнуть{}, // гнуть на станке
rus_verbs:размещаться{}, // размещаться на бирже
rus_verbs:соорудить{}, // соорудить на даче
rus_verbs:пастись{}, // пастись на лугу
rus_verbs:формироваться{}, // формироваться на дне
rus_verbs:таить{}, // таить на дне
rus_verbs:приостановиться{}, // приостановиться на середине
rus_verbs:топтаться{}, // топтаться на месте
rus_verbs:громить{}, // громить на подступах
rus_verbs:вычислить{}, // вычислить на бумажке
rus_verbs:заказывать{}, // заказывать на сайте
rus_verbs:осуществить{}, // осуществить на практике
rus_verbs:обосноваться{}, // обосноваться на верхушке
rus_verbs:пытать{}, // пытать на электрическом стуле
rus_verbs:совершиться{}, // совершиться на заседании
rus_verbs:свернуться{}, // свернуться на медленном огне
rus_verbs:пролетать{}, // пролетать на дельтаплане
rus_verbs:сбыться{}, // сбыться на самом деле
rus_verbs:разговориться{}, // разговориться на уроке
rus_verbs:разворачиваться{}, // разворачиваться на перекрестке
rus_verbs:преподнести{}, // преподнести на блюдечке
rus_verbs:напечатать{}, // напечатать на лазернике
rus_verbs:прорвать{}, // прорвать на периферии
rus_verbs:раскачиваться{}, // раскачиваться на доске
rus_verbs:задерживаться{}, // задерживаться на старте
rus_verbs:угощать{}, // угощать на вечеринке
rus_verbs:шарить{}, // шарить на столе
rus_verbs:увеличивать{}, // увеличивать на первом этапе
rus_verbs:рехнуться{}, // рехнуться на старости лет
rus_verbs:расцвести{}, // расцвести на грядке
rus_verbs:закипеть{}, // закипеть на плите
rus_verbs:подлететь{}, // подлететь на параплане
rus_verbs:рыться{}, // рыться на свалке
rus_verbs:добираться{}, // добираться на попутках
rus_verbs:продержаться{}, // продержаться на вершине
rus_verbs:разыскивать{}, // разыскивать на выставках
rus_verbs:освобождать{}, // освобождать на заседании
rus_verbs:передвигаться{}, // передвигаться на самокате
rus_verbs:проявиться{}, // проявиться на свету
rus_verbs:заскользить{}, // заскользить на льду
rus_verbs:пересказать{}, // пересказать на сцене студенческого театра
rus_verbs:протестовать{}, // протестовать на улице
rus_verbs:указываться{}, // указываться на табличках
rus_verbs:прискакать{}, // прискакать на лошадке
rus_verbs:копошиться{}, // копошиться на свежем воздухе
rus_verbs:подсчитать{}, // подсчитать на бумажке
rus_verbs:разволноваться{}, // разволноваться на экзамене
rus_verbs:завертеться{}, // завертеться на полу
rus_verbs:ознакомиться{}, // ознакомиться на ходу
rus_verbs:ржать{}, // ржать на уроке
rus_verbs:раскинуть{}, // раскинуть на грядках
rus_verbs:разгромить{}, // разгромить на ринге
rus_verbs:подслушать{}, // подслушать на совещании
rus_verbs:описываться{}, // описываться на страницах книги
rus_verbs:качаться{}, // качаться на стуле
rus_verbs:усилить{}, // усилить на флангах
rus_verbs:набросать{}, // набросать на клочке картона
rus_verbs:расстреливать{}, // расстреливать на подходе
rus_verbs:запрыгать{}, // запрыгать на одной ноге
rus_verbs:сыскать{}, // сыскать на чужбине
rus_verbs:подтвердиться{}, // подтвердиться на практике
rus_verbs:плескаться{}, // плескаться на мелководье
rus_verbs:расширяться{}, // расширяться на конце
rus_verbs:подержать{}, // подержать на солнце
rus_verbs:планироваться{}, // планироваться на общем собрании
rus_verbs:сгинуть{}, // сгинуть на чужбине
rus_verbs:замкнуться{}, // замкнуться на точке
rus_verbs:закачаться{}, // закачаться на ветру
rus_verbs:перечитывать{}, // перечитывать на ходу
rus_verbs:перелететь{}, // перелететь на дельтаплане
rus_verbs:оживать{}, // оживать на солнце
rus_verbs:женить{}, // женить на богатой невесте
rus_verbs:заглохнуть{}, // заглохнуть на старте
rus_verbs:копаться{}, // копаться на полу
rus_verbs:развлекаться{}, // развлекаться на дискотеке
rus_verbs:печататься{}, // печататься на струйном принтере
rus_verbs:обрываться{}, // обрываться на полуслове
rus_verbs:ускакать{}, // ускакать на лошадке
rus_verbs:подписывать{}, // подписывать на столе
rus_verbs:добывать{}, // добывать на выработке
rus_verbs:скопиться{}, // скопиться на выходе
rus_verbs:повстречать{}, // повстречать на пути
rus_verbs:поцеловаться{}, // поцеловаться на площади
rus_verbs:растянуть{}, // растянуть на столе
rus_verbs:подаваться{}, // подаваться на благотворительном обеде
rus_verbs:повстречаться{}, // повстречаться на митинге
rus_verbs:примоститься{}, // примоститься на ступеньках
rus_verbs:отразить{}, // отразить на страницах доклада
rus_verbs:пояснять{}, // пояснять на страницах приложения
rus_verbs:накормить{}, // накормить на кухне
rus_verbs:поужинать{}, // поужинать на веранде
инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть на митинге
деепричастие:спев{},
инфинитив:спеть{ вид:несоверш }, глагол:спеть{ вид:несоверш },
rus_verbs:топить{}, // топить на мелководье
rus_verbs:освоить{}, // освоить на практике
rus_verbs:распластаться{}, // распластаться на травке
rus_verbs:отплыть{}, // отплыть на старом каяке
rus_verbs:улетать{}, // улетать на любом самолете
rus_verbs:отстаивать{}, // отстаивать на корте
rus_verbs:осуждать{}, // осуждать на словах
rus_verbs:переговорить{}, // переговорить на обеде
rus_verbs:укрыть{}, // укрыть на чердаке
rus_verbs:томиться{}, // томиться на привязи
rus_verbs:сжигать{}, // сжигать на полигоне
rus_verbs:позавтракать{}, // позавтракать на лоне природы
rus_verbs:функционировать{}, // функционирует на солнечной энергии
rus_verbs:разместить{}, // разместить на сайте
rus_verbs:пронести{}, // пронести на теле
rus_verbs:нашарить{}, // нашарить на столе
rus_verbs:корчиться{}, // корчиться на полу
rus_verbs:распознать{}, // распознать на снимке
rus_verbs:повеситься{}, // повеситься на шнуре
rus_verbs:обозначиться{}, // обозначиться на картах
rus_verbs:оступиться{}, // оступиться на скользком льду
rus_verbs:подносить{}, // подносить на блюдечке
rus_verbs:расстелить{}, // расстелить на газоне
rus_verbs:обсуждаться{}, // обсуждаться на собрании
rus_verbs:расписаться{}, // расписаться на бланке
rus_verbs:плестись{}, // плестись на привязи
rus_verbs:объявиться{}, // объявиться на сцене
rus_verbs:повышаться{}, // повышаться на первом датчике
rus_verbs:разрабатывать{}, // разрабатывать на заводе
rus_verbs:прерывать{}, // прерывать на середине
rus_verbs:каяться{}, // каяться на публике
rus_verbs:освоиться{}, // освоиться на лошади
rus_verbs:подплыть{}, // подплыть на плоту
rus_verbs:оскорбить{}, // оскорбить на митинге
rus_verbs:торжествовать{}, // торжествовать на пьедестале
rus_verbs:поправлять{}, // поправлять на одежде
rus_verbs:отражать{}, // отражать на картине
rus_verbs:дремать{}, // дремать на кушетке
rus_verbs:применяться{}, // применяться на производстве стали
rus_verbs:поражать{}, // поражать на большой дистанции
rus_verbs:расстрелять{}, // расстрелять на окраине хутора
rus_verbs:рассчитать{}, // рассчитать на калькуляторе
rus_verbs:записывать{}, // записывать на ленте
rus_verbs:перебирать{}, // перебирать на ладони
rus_verbs:разбиться{}, // разбиться на катере
rus_verbs:поискать{}, // поискать на ферме
rus_verbs:прятать{}, // прятать на заброшенном складе
rus_verbs:пропеть{}, // пропеть на эстраде
rus_verbs:замелькать{}, // замелькать на экране
rus_verbs:грустить{}, // грустить на веранде
rus_verbs:крутить{}, // крутить на оси
rus_verbs:подготовить{}, // подготовить на конспиративной квартире
rus_verbs:различать{}, // различать на картинке
rus_verbs:киснуть{}, // киснуть на чужбине
rus_verbs:оборваться{}, // оборваться на полуслове
rus_verbs:запутаться{}, // запутаться на простейшем тесте
rus_verbs:общаться{}, // общаться на уроке
rus_verbs:производиться{}, // производиться на фабрике
rus_verbs:сочинить{}, // сочинить на досуге
rus_verbs:давить{}, // давить на лице
rus_verbs:разработать{}, // разработать на секретном предприятии
rus_verbs:качать{}, // качать на качелях
rus_verbs:тушить{}, // тушить на крыше пожар
rus_verbs:охранять{}, // охранять на территории базы
rus_verbs:приметить{}, // приметить на взгорке
rus_verbs:скрыть{}, // скрыть на теле
rus_verbs:удерживать{}, // удерживать на руке
rus_verbs:усвоить{}, // усвоить на уроке
rus_verbs:растаять{}, // растаять на солнечной стороне
rus_verbs:красоваться{}, // красоваться на виду
rus_verbs:сохраняться{}, // сохраняться на холоде
rus_verbs:лечить{}, // лечить на дому
rus_verbs:прокатиться{}, // прокатиться на уницикле
rus_verbs:договариваться{}, // договариваться на нейтральной территории
rus_verbs:качнуться{}, // качнуться на одной ноге
rus_verbs:опубликовать{}, // опубликовать на сайте
rus_verbs:отражаться{}, // отражаться на поверхности воды
rus_verbs:обедать{}, // обедать на веранде
rus_verbs:посидеть{}, // посидеть на лавочке
rus_verbs:сообщаться{}, // сообщаться на официальном сайте
rus_verbs:свершиться{}, // свершиться на заседании
rus_verbs:ночевать{}, // ночевать на даче
rus_verbs:темнеть{}, // темнеть на свету
rus_verbs:гибнуть{}, // гибнуть на территории полигона
rus_verbs:усиливаться{}, // усиливаться на территории округа
rus_verbs:проживать{}, // проживать на даче
rus_verbs:исследовать{}, // исследовать на большой глубине
rus_verbs:обитать{}, // обитать на громадной глубине
rus_verbs:сталкиваться{}, // сталкиваться на большой высоте
rus_verbs:таиться{}, // таиться на большой глубине
rus_verbs:спасать{}, // спасать на пожаре
rus_verbs:сказываться{}, // сказываться на общем результате
rus_verbs:заблудиться{}, // заблудиться на стройке
rus_verbs:пошарить{}, // пошарить на полках
rus_verbs:планировать{}, // планировать на бумаге
rus_verbs:ранить{}, // ранить на полигоне
rus_verbs:хлопать{}, // хлопать на сцене
rus_verbs:основать{}, // основать на горе новый монастырь
rus_verbs:отбить{}, // отбить на столе
rus_verbs:отрицать{}, // отрицать на заседании комиссии
rus_verbs:устоять{}, // устоять на ногах
rus_verbs:отзываться{}, // отзываться на страницах отчёта
rus_verbs:притормозить{}, // притормозить на обочине
rus_verbs:читаться{}, // читаться на лице
rus_verbs:заиграть{}, // заиграть на саксофоне
rus_verbs:зависнуть{}, // зависнуть на игровой площадке
rus_verbs:сознаться{}, // сознаться на допросе
rus_verbs:выясняться{}, // выясняться на очной ставке
rus_verbs:наводить{}, // наводить на столе порядок
rus_verbs:покоиться{}, // покоиться на кладбище
rus_verbs:значиться{}, // значиться на бейджике
rus_verbs:съехать{}, // съехать на санках
rus_verbs:познакомить{}, // познакомить на свадьбе
rus_verbs:завязать{}, // завязать на спине
rus_verbs:грохнуть{}, // грохнуть на площади
rus_verbs:разъехаться{}, // разъехаться на узкой дороге
rus_verbs:столпиться{}, // столпиться на крыльце
rus_verbs:порыться{}, // порыться на полках
rus_verbs:ослабить{}, // ослабить на шее
rus_verbs:оправдывать{}, // оправдывать на суде
rus_verbs:обнаруживаться{}, // обнаруживаться на складе
rus_verbs:спастись{}, // спастись на дереве
rus_verbs:прерваться{}, // прерваться на полуслове
rus_verbs:строиться{}, // строиться на пустыре
rus_verbs:познать{}, // познать на практике
rus_verbs:путешествовать{}, // путешествовать на поезде
rus_verbs:побеждать{}, // побеждать на ринге
rus_verbs:рассматриваться{}, // рассматриваться на заседании
rus_verbs:продаваться{}, // продаваться на открытом рынке
rus_verbs:разместиться{}, // разместиться на базе
rus_verbs:завыть{}, // завыть на холме
rus_verbs:настигнуть{}, // настигнуть на окраине
rus_verbs:укрыться{}, // укрыться на чердаке
rus_verbs:расплакаться{}, // расплакаться на заседании комиссии
rus_verbs:заканчивать{}, // заканчивать на последнем задании
rus_verbs:пролежать{}, // пролежать на столе
rus_verbs:громоздиться{}, // громоздиться на полу
rus_verbs:замерзнуть{}, // замерзнуть на открытом воздухе
rus_verbs:поскользнуться{}, // поскользнуться на льду
rus_verbs:таскать{}, // таскать на спине
rus_verbs:просматривать{}, // просматривать на сайте
rus_verbs:обдумать{}, // обдумать на досуге
rus_verbs:гадать{}, // гадать на кофейной гуще
rus_verbs:останавливать{}, // останавливать на выходе
rus_verbs:обозначать{}, // обозначать на странице
rus_verbs:долететь{}, // долететь на спортивном байке
rus_verbs:тесниться{}, // тесниться на чердачке
rus_verbs:хоронить{}, // хоронить на частном кладбище
rus_verbs:установиться{}, // установиться на юге
rus_verbs:прикидывать{}, // прикидывать на клочке бумаги
rus_verbs:затаиться{}, // затаиться на дереве
rus_verbs:раздобыть{}, // раздобыть на складе
rus_verbs:перебросить{}, // перебросить на вертолетах
rus_verbs:захватывать{}, // захватывать на базе
rus_verbs:сказаться{}, // сказаться на итоговых оценках
rus_verbs:покачиваться{}, // покачиваться на волнах
rus_verbs:крутиться{}, // крутиться на кухне
rus_verbs:помещаться{}, // помещаться на полке
rus_verbs:питаться{}, // питаться на помойке
rus_verbs:отдохнуть{}, // отдохнуть на загородной вилле
rus_verbs:кататься{}, // кататься на велике
rus_verbs:поработать{}, // поработать на стройке
rus_verbs:ограбить{}, // ограбить на пустыре
rus_verbs:зарабатывать{}, // зарабатывать на бирже
rus_verbs:преуспеть{}, // преуспеть на ниве искусства
rus_verbs:заерзать{}, // заерзать на стуле
rus_verbs:разъяснить{}, // разъяснить на полях
rus_verbs:отчеканить{}, // отчеканить на медной пластине
rus_verbs:торговать{}, // торговать на рынке
rus_verbs:поколебаться{}, // поколебаться на пороге
rus_verbs:прикинуть{}, // прикинуть на бумажке
rus_verbs:рассечь{}, // рассечь на тупом конце
rus_verbs:посмеяться{}, // посмеяться на переменке
rus_verbs:остыть{}, // остыть на морозном воздухе
rus_verbs:запереться{}, // запереться на чердаке
rus_verbs:обогнать{}, // обогнать на повороте
rus_verbs:подтянуться{}, // подтянуться на турнике
rus_verbs:привозить{}, // привозить на машине
rus_verbs:подбирать{}, // подбирать на полу
rus_verbs:уничтожать{}, // уничтожать на подходе
rus_verbs:притаиться{}, // притаиться на вершине
rus_verbs:плясать{}, // плясать на костях
rus_verbs:поджидать{}, // поджидать на вокзале
rus_verbs:закончить{}, // Мы закончили игру на самом интересном месте (САМ не может быть первым прилагательным в цепочке!)
rus_verbs:смениться{}, // смениться на посту
rus_verbs:посчитать{}, // посчитать на пальцах
rus_verbs:прицелиться{}, // прицелиться на бегу
rus_verbs:нарисовать{}, // нарисовать на стене
rus_verbs:прыгать{}, // прыгать на сцене
rus_verbs:повертеть{}, // повертеть на пальце
rus_verbs:попрощаться{}, // попрощаться на панихиде
инфинитив:просыпаться{ вид:соверш }, глагол:просыпаться{ вид:соверш }, // просыпаться на диване
rus_verbs:разобрать{}, // разобрать на столе
rus_verbs:помереть{}, // помереть на чужбине
rus_verbs:различить{}, // различить на нечеткой фотографии
rus_verbs:рисовать{}, // рисовать на доске
rus_verbs:проследить{}, // проследить на экране
rus_verbs:задремать{}, // задремать на диване
rus_verbs:ругаться{}, // ругаться на людях
rus_verbs:сгореть{}, // сгореть на работе
rus_verbs:зазвучать{}, // зазвучать на коротких волнах
rus_verbs:задохнуться{}, // задохнуться на вершине горы
rus_verbs:порождать{}, // порождать на поверхности небольшую рябь
rus_verbs:отдыхать{}, // отдыхать на курорте
rus_verbs:образовать{}, // образовать на дне толстый слой
rus_verbs:поправиться{}, // поправиться на дармовых харчах
rus_verbs:отмечать{}, // отмечать на календаре
rus_verbs:реять{}, // реять на флагштоке
rus_verbs:ползти{}, // ползти на коленях
rus_verbs:продавать{}, // продавать на аукционе
rus_verbs:сосредоточиться{}, // сосредоточиться на основной задаче
rus_verbs:рыскать{}, // мышки рыскали на кухне
rus_verbs:расстегнуть{}, // расстегнуть на куртке все пуговицы
rus_verbs:напасть{}, // напасть на территории другого государства
rus_verbs:издать{}, // издать на западе
rus_verbs:оставаться{}, // оставаться на страже порядка
rus_verbs:появиться{}, // наконец появиться на экране
rus_verbs:лежать{}, // лежать на столе
rus_verbs:ждать{}, // ждать на берегу
инфинитив:писать{aux stress="пис^ать"}, // писать на бумаге
глагол:писать{aux stress="пис^ать"},
rus_verbs:оказываться{}, // оказываться на полу
rus_verbs:поставить{}, // поставить на столе
rus_verbs:держать{}, // держать на крючке
rus_verbs:выходить{}, // выходить на остановке
rus_verbs:заговорить{}, // заговорить на китайском языке
rus_verbs:ожидать{}, // ожидать на стоянке
rus_verbs:закричать{}, // закричал на минарете муэдзин
rus_verbs:простоять{}, // простоять на посту
rus_verbs:продолжить{}, // продолжить на первом этаже
rus_verbs:ощутить{}, // ощутить на себе влияние кризиса
rus_verbs:состоять{}, // состоять на учете
rus_verbs:готовиться{},
инфинитив:акклиматизироваться{вид:несоверш}, // альпинисты готовятся акклиматизироваться на новой высоте
глагол:акклиматизироваться{вид:несоверш},
rus_verbs:арестовать{}, // грабители были арестованы на месте преступления
rus_verbs:схватить{}, // грабители были схвачены на месте преступления
инфинитив:атаковать{ вид:соверш }, // взвод был атакован на границе
глагол:атаковать{ вид:соверш },
прилагательное:атакованный{ вид:соверш },
прилагательное:атаковавший{ вид:соверш },
rus_verbs:базировать{}, // установка будет базирована на границе
rus_verbs:базироваться{}, // установка базируется на границе
rus_verbs:барахтаться{}, // дети барахтались на мелководье
rus_verbs:браконьерить{}, // Охотники браконьерили ночью на реке
rus_verbs:браконьерствовать{}, // Охотники ночью браконьерствовали на реке
rus_verbs:бренчать{}, // парень что-то бренчал на гитаре
rus_verbs:бренькать{}, // парень что-то бренькает на гитаре
rus_verbs:начать{}, // Рынок акций РФ начал торги на отрицательной территории.
rus_verbs:буксовать{}, // Колеса буксуют на льду
rus_verbs:вертеться{}, // Непоседливый ученик много вертится на стуле
rus_verbs:взвести{}, // Боец взвел на оружии предохранитель
rus_verbs:вилять{}, // Машина сильно виляла на дороге
rus_verbs:висеть{}, // Яблоко висит на ветке
rus_verbs:возлежать{}, // возлежать на лежанке
rus_verbs:подниматься{}, // Мы поднимаемся на лифте
rus_verbs:подняться{}, // Мы поднимемся на лифте
rus_verbs:восседать{}, // Коля восседает на лошади
rus_verbs:воссиять{}, // Луна воссияла на небе
rus_verbs:воцариться{}, // Мир воцарился на всей земле
rus_verbs:воцаряться{}, // Мир воцаряется на всей земле
rus_verbs:вращать{}, // вращать на поясе
rus_verbs:вращаться{}, // вращаться на поясе
rus_verbs:встретить{}, // встретить друга на улице
rus_verbs:встретиться{}, // встретиться на занятиях
rus_verbs:встречать{}, // встречать на занятиях
rus_verbs:въебывать{}, // въебывать на работе
rus_verbs:въезжать{}, // въезжать на автомобиле
rus_verbs:въехать{}, // въехать на автомобиле
rus_verbs:выгорать{}, // ткань выгорает на солнце
rus_verbs:выгореть{}, // ткань выгорела на солнце
rus_verbs:выгравировать{}, // выгравировать на табличке надпись
rus_verbs:выжить{}, // выжить на необитаемом острове
rus_verbs:вылежаться{}, // помидоры вылежались на солнце
rus_verbs:вылеживаться{}, // вылеживаться на солнце
rus_verbs:выместить{}, // выместить на ком-то злобу
rus_verbs:вымещать{}, // вымещать на ком-то свое раздражение
rus_verbs:вымещаться{}, // вымещаться на ком-то
rus_verbs:выращивать{}, // выращивать на грядке помидоры
rus_verbs:выращиваться{}, // выращиваться на грядке
инфинитив:вырезать{вид:соверш}, // вырезать на доске надпись
глагол:вырезать{вид:соверш},
инфинитив:вырезать{вид:несоверш},
глагол:вырезать{вид:несоверш},
rus_verbs:вырисоваться{}, // вырисоваться на графике
rus_verbs:вырисовываться{}, // вырисовываться на графике
rus_verbs:высаживать{}, // высаживать на необитаемом острове
rus_verbs:высаживаться{}, // высаживаться на острове
rus_verbs:высвечивать{}, // высвечивать на дисплее температуру
rus_verbs:высвечиваться{}, // высвечиваться на дисплее
rus_verbs:выстроить{}, // выстроить на фундаменте
rus_verbs:выстроиться{}, // выстроиться на плацу
rus_verbs:выстудить{}, // выстудить на морозе
rus_verbs:выстудиться{}, // выстудиться на морозе
rus_verbs:выстужать{}, // выстужать на морозе
rus_verbs:выстуживать{}, // выстуживать на морозе
rus_verbs:выстуживаться{}, // выстуживаться на морозе
rus_verbs:выстукать{}, // выстукать на клавиатуре
rus_verbs:выстукивать{}, // выстукивать на клавиатуре
rus_verbs:выстукиваться{}, // выстукиваться на клавиатуре
rus_verbs:выступать{}, // выступать на сцене
rus_verbs:выступить{}, // выступить на сцене
rus_verbs:выстучать{}, // выстучать на клавиатуре
rus_verbs:выстывать{}, // выстывать на морозе
rus_verbs:выстыть{}, // выстыть на морозе
rus_verbs:вытатуировать{}, // вытатуировать на руке якорь
rus_verbs:говорить{}, // говорить на повышенных тонах
rus_verbs:заметить{}, // заметить на берегу
rus_verbs:стоять{}, // твёрдо стоять на ногах
rus_verbs:оказаться{}, // оказаться на передовой линии
rus_verbs:почувствовать{}, // почувствовать на своей шкуре
rus_verbs:остановиться{}, // остановиться на первом пункте
rus_verbs:показаться{}, // показаться на горизонте
rus_verbs:чувствовать{}, // чувствовать на своей шкуре
rus_verbs:искать{}, // искать на открытом пространстве
rus_verbs:иметься{}, // иметься на складе
rus_verbs:клясться{}, // клясться на Коране
rus_verbs:прервать{}, // прервать на полуслове
rus_verbs:играть{}, // играть на чувствах
rus_verbs:спуститься{}, // спуститься на парашюте
rus_verbs:понадобиться{}, // понадобиться на экзамене
rus_verbs:служить{}, // служить на флоте
rus_verbs:подобрать{}, // подобрать на улице
rus_verbs:появляться{}, // появляться на сцене
rus_verbs:селить{}, // селить на чердаке
rus_verbs:поймать{}, // поймать на границе
rus_verbs:увидать{}, // увидать на опушке
rus_verbs:подождать{}, // подождать на перроне
rus_verbs:прочесть{}, // прочесть на полях
rus_verbs:тонуть{}, // тонуть на мелководье
rus_verbs:ощущать{}, // ощущать на коже
rus_verbs:отметить{}, // отметить на полях
rus_verbs:показывать{}, // показывать на графике
rus_verbs:разговаривать{}, // разговаривать на иностранном языке
rus_verbs:прочитать{}, // прочитать на сайте
rus_verbs:попробовать{}, // попробовать на практике
rus_verbs:замечать{}, // замечать на коже грязь
rus_verbs:нести{}, // нести на плечах
rus_verbs:носить{}, // носить на голове
rus_verbs:гореть{}, // гореть на работе
rus_verbs:застыть{}, // застыть на пороге
инфинитив:жениться{ вид:соверш }, // жениться на королеве
глагол:жениться{ вид:соверш },
прилагательное:женатый{},
прилагательное:женившийся{},
rus_verbs:спрятать{}, // спрятать на чердаке
rus_verbs:развернуться{}, // развернуться на плацу
rus_verbs:строить{}, // строить на песке
rus_verbs:устроить{}, // устроить на даче тестральный вечер
rus_verbs:настаивать{}, // настаивать на выполнении приказа
rus_verbs:находить{}, // находить на берегу
rus_verbs:мелькнуть{}, // мелькнуть на экране
rus_verbs:очутиться{}, // очутиться на опушке леса
инфинитив:использовать{вид:соверш}, // использовать на работе
глагол:использовать{вид:соверш},
инфинитив:использовать{вид:несоверш},
глагол:использовать{вид:несоверш},
прилагательное:использованный{},
прилагательное:использующий{},
прилагательное:использовавший{},
rus_verbs:лететь{}, // лететь на воздушном шаре
rus_verbs:смеяться{}, // смеяться на сцене
rus_verbs:ездить{}, // ездить на мопеде
rus_verbs:заснуть{}, // заснуть на диване
rus_verbs:застать{}, // застать на рабочем месте
rus_verbs:очнуться{}, // очнуться на больничной койке
rus_verbs:разглядеть{}, // разглядеть на фотографии
rus_verbs:обойти{}, // обойти на вираже
rus_verbs:удержаться{}, // удержаться на троне
rus_verbs:побывать{}, // побывать на другой планете
rus_verbs:заняться{}, // заняться на выходных делом
rus_verbs:вянуть{}, // вянуть на солнце
rus_verbs:постоять{}, // постоять на голове
rus_verbs:приобрести{}, // приобрести на распродаже
rus_verbs:попасться{}, // попасться на краже
rus_verbs:продолжаться{}, // продолжаться на земле
rus_verbs:открывать{}, // открывать на арене
rus_verbs:создавать{}, // создавать на сцене
rus_verbs:обсуждать{}, // обсуждать на кухне
rus_verbs:отыскать{}, // отыскать на полу
rus_verbs:уснуть{}, // уснуть на диване
rus_verbs:задержаться{}, // задержаться на работе
rus_verbs:курить{}, // курить на свежем воздухе
rus_verbs:приподняться{}, // приподняться на локтях
rus_verbs:установить{}, // установить на вершине
rus_verbs:запереть{}, // запереть на балконе
rus_verbs:синеть{}, // синеть на воздухе
rus_verbs:убивать{}, // убивать на нейтральной территории
rus_verbs:скрываться{}, // скрываться на даче
rus_verbs:родить{}, // родить на полу
rus_verbs:описать{}, // описать на страницах книги
rus_verbs:перехватить{}, // перехватить на подлете
rus_verbs:скрывать{}, // скрывать на даче
rus_verbs:сменить{}, // сменить на посту
rus_verbs:мелькать{}, // мелькать на экране
rus_verbs:присутствовать{}, // присутствовать на мероприятии
rus_verbs:украсть{}, // украсть на рынке
rus_verbs:победить{}, // победить на ринге
rus_verbs:упомянуть{}, // упомянуть на страницах романа
rus_verbs:плыть{}, // плыть на старой лодке
rus_verbs:повиснуть{}, // повиснуть на перекладине
rus_verbs:нащупать{}, // нащупать на дне
rus_verbs:затихнуть{}, // затихнуть на дне
rus_verbs:построить{}, // построить на участке
rus_verbs:поддерживать{}, // поддерживать на поверхности
rus_verbs:заработать{}, // заработать на бирже
rus_verbs:провалиться{}, // провалиться на экзамене
rus_verbs:сохранить{}, // сохранить на диске
rus_verbs:располагаться{}, // располагаться на софе
rus_verbs:поклясться{}, // поклясться на библии
rus_verbs:сражаться{}, // сражаться на арене
rus_verbs:спускаться{}, // спускаться на дельтаплане
rus_verbs:уничтожить{}, // уничтожить на подступах
rus_verbs:изучить{}, // изучить на практике
rus_verbs:рождаться{}, // рождаться на праздниках
rus_verbs:прилететь{}, // прилететь на самолете
rus_verbs:догнать{}, // догнать на перекрестке
rus_verbs:изобразить{}, // изобразить на бумаге
rus_verbs:проехать{}, // проехать на тракторе
rus_verbs:приготовить{}, // приготовить на масле
rus_verbs:споткнуться{}, // споткнуться на полу
rus_verbs:собирать{}, // собирать на берегу
rus_verbs:отсутствовать{}, // отсутствовать на тусовке
rus_verbs:приземлиться{}, // приземлиться на военном аэродроме
rus_verbs:сыграть{}, // сыграть на трубе
rus_verbs:прятаться{}, // прятаться на даче
rus_verbs:спрятаться{}, // спрятаться на чердаке
rus_verbs:провозгласить{}, // провозгласить на митинге
rus_verbs:изложить{}, // изложить на бумаге
rus_verbs:использоваться{}, // использоваться на практике
rus_verbs:замяться{}, // замяться на входе
rus_verbs:раздаваться{}, // Крик ягуара раздается на краю болота
rus_verbs:сверкнуть{}, // сверкнуть на солнце
rus_verbs:сверкать{}, // сверкать на свету
rus_verbs:задержать{}, // задержать на митинге
rus_verbs:осечься{}, // осечься на первом слове
rus_verbs:хранить{}, // хранить на банковском счету
rus_verbs:шутить{}, // шутить на уроке
rus_verbs:кружиться{}, // кружиться на балу
rus_verbs:чертить{}, // чертить на доске
rus_verbs:отразиться{}, // отразиться на оценках
rus_verbs:греть{}, // греть на солнце
rus_verbs:рассуждать{}, // рассуждать на страницах своей книги
rus_verbs:окружать{}, // окружать на острове
rus_verbs:сопровождать{}, // сопровождать на охоте
rus_verbs:заканчиваться{}, // заканчиваться на самом интересном месте
rus_verbs:содержаться{}, // содержаться на приусадебном участке
rus_verbs:поселиться{}, // поселиться на даче
rus_verbs:запеть{}, // запеть на сцене
инфинитив:провозить{ вид:несоверш }, // провозить на теле
глагол:провозить{ вид:несоверш },
прилагательное:провезенный{},
прилагательное:провозивший{вид:несоверш},
прилагательное:провозящий{вид:несоверш},
деепричастие:провозя{},
rus_verbs:мочить{}, // мочить на месте
rus_verbs:преследовать{}, // преследовать на территории другого штата
rus_verbs:пролететь{}, // пролетел на параплане
rus_verbs:драться{}, // драться на рапирах
rus_verbs:просидеть{}, // просидеть на занятиях
rus_verbs:убираться{}, // убираться на балконе
rus_verbs:таять{}, // таять на солнце
rus_verbs:проверять{}, // проверять на полиграфе
rus_verbs:убеждать{}, // убеждать на примере
rus_verbs:скользить{}, // скользить на льду
rus_verbs:приобретать{}, // приобретать на распродаже
rus_verbs:летать{}, // летать на метле
rus_verbs:толпиться{}, // толпиться на перроне
rus_verbs:плавать{}, // плавать на надувном матрасе
rus_verbs:описывать{}, // описывать на страницах повести
rus_verbs:пробыть{}, // пробыть на солнце слишком долго
rus_verbs:застрять{}, // застрять на верхнем этаже
rus_verbs:метаться{}, // метаться на полу
rus_verbs:сжечь{}, // сжечь на костре
rus_verbs:расслабиться{}, // расслабиться на кушетке
rus_verbs:услыхать{}, // услыхать на рынке
rus_verbs:удержать{}, // удержать на прежнем уровне
rus_verbs:образоваться{}, // образоваться на дне
rus_verbs:рассмотреть{}, // рассмотреть на поверхности чипа
rus_verbs:уезжать{}, // уезжать на попутке
rus_verbs:похоронить{}, // похоронить на закрытом кладбище
rus_verbs:настоять{}, // настоять на пересмотре оценок
rus_verbs:растянуться{}, // растянуться на горячем песке
rus_verbs:покрутить{}, // покрутить на шесте
rus_verbs:обнаружиться{}, // обнаружиться на болоте
rus_verbs:гулять{}, // гулять на свадьбе
rus_verbs:утонуть{}, // утонуть на курорте
rus_verbs:храниться{}, // храниться на депозите
rus_verbs:танцевать{}, // танцевать на свадьбе
rus_verbs:трудиться{}, // трудиться на заводе
инфинитив:засыпать{переходность:непереходный вид:несоверш}, // засыпать на кровати
глагол:засыпать{переходность:непереходный вид:несоверш},
деепричастие:засыпая{переходность:непереходный вид:несоверш},
прилагательное:засыпавший{переходность:непереходный вид:несоверш},
прилагательное:засыпающий{ вид:несоверш переходность:непереходный }, // ребенок, засыпающий на руках
rus_verbs:сушить{}, // сушить на открытом воздухе
rus_verbs:зашевелиться{}, // зашевелиться на чердаке
rus_verbs:обдумывать{}, // обдумывать на досуге
rus_verbs:докладывать{}, // докладывать на научной конференции
rus_verbs:промелькнуть{}, // промелькнуть на экране
// прилагательное:находящийся{ вид:несоверш }, // колонна, находящаяся на ничейной территории
прилагательное:написанный{}, // слово, написанное на заборе
rus_verbs:умещаться{}, // компьютер, умещающийся на ладони
rus_verbs:открыть{}, // книга, открытая на последней странице
rus_verbs:спать{}, // йог, спящий на гвоздях
rus_verbs:пробуксовывать{}, // колесо, пробуксовывающее на обледенелом асфальте
rus_verbs:забуксовать{}, // колесо, забуксовавшее на обледенелом асфальте
rus_verbs:отобразиться{}, // удивление, отобразившееся на лице
rus_verbs:увидеть{}, // на полу я увидел чьи-то следы
rus_verbs:видеть{}, // на полу я вижу чьи-то следы
rus_verbs:оставить{}, // Мел оставил на доске белый след.
rus_verbs:оставлять{}, // Мел оставляет на доске белый след.
rus_verbs:встречаться{}, // встречаться на лекциях
rus_verbs:познакомиться{}, // познакомиться на занятиях
rus_verbs:устроиться{}, // она устроилась на кровати
rus_verbs:ложиться{}, // ложись на полу
rus_verbs:останавливаться{}, // останавливаться на достигнутом
rus_verbs:спотыкаться{}, // спотыкаться на ровном месте
rus_verbs:распечатать{}, // распечатать на бумаге
rus_verbs:распечатывать{}, // распечатывать на бумаге
rus_verbs:просмотреть{}, // просмотреть на бумаге
rus_verbs:закрепляться{}, // закрепляться на плацдарме
rus_verbs:погреться{}, // погреться на солнышке
rus_verbs:мешать{}, // Он мешал краски на палитре.
rus_verbs:занять{}, // Он занял первое место на соревнованиях.
rus_verbs:заговариваться{}, // Он заговаривался иногда на уроках.
деепричастие:женившись{ вид:соверш },
rus_verbs:везти{}, // Он везёт песок на тачке.
прилагательное:казненный{}, // Он был казнён на электрическом стуле.
rus_verbs:прожить{}, // Он безвыездно прожил всё лето на даче.
rus_verbs:принести{}, // Официантка принесла нам обед на подносе.
rus_verbs:переписать{}, // Перепишите эту рукопись на машинке.
rus_verbs:идти{}, // Поезд идёт на малой скорости.
rus_verbs:петь{}, // птички поют на рассвете
rus_verbs:смотреть{}, // Смотри на обороте.
rus_verbs:прибрать{}, // прибрать на столе
rus_verbs:прибраться{}, // прибраться на столе
rus_verbs:растить{}, // растить капусту на огороде
rus_verbs:тащить{}, // тащить ребенка на руках
rus_verbs:убирать{}, // убирать на столе
rus_verbs:простыть{}, // Я простыл на морозе.
rus_verbs:сиять{}, // ясные звезды мирно сияли на безоблачном весеннем небе.
rus_verbs:проводиться{}, // такие эксперименты не проводятся на воде
rus_verbs:достать{}, // Я не могу достать до яблок на верхних ветках.
rus_verbs:расплыться{}, // Чернила расплылись на плохой бумаге.
rus_verbs:вскочить{}, // У него вскочил прыщ на носу.
rus_verbs:свить{}, // У нас на балконе воробей свил гнездо.
rus_verbs:оторваться{}, // У меня на пальто оторвалась пуговица.
rus_verbs:восходить{}, // Солнце восходит на востоке.
rus_verbs:блестеть{}, // Снег блестит на солнце.
rus_verbs:побить{}, // Рысак побил всех лошадей на скачках.
rus_verbs:литься{}, // Реки крови льются на войне.
rus_verbs:держаться{}, // Ребёнок уже твёрдо держится на ногах.
rus_verbs:клубиться{}, // Пыль клубится на дороге.
инфинитив:написать{ aux stress="напис^ать" }, // Ты должен написать статью на английском языке
глагол:написать{ aux stress="напис^ать" }, // Он написал статью на русском языке.
// глагол:находиться{вид:несоверш}, // мой поезд находится на первом пути
// инфинитив:находиться{вид:несоверш},
rus_verbs:жить{}, // Было интересно жить на курорте.
rus_verbs:повидать{}, // Он много повидал на своём веку.
rus_verbs:разъезжаться{}, // Ноги разъезжаются не только на льду.
rus_verbs:расположиться{}, // Оба села расположились на берегу реки.
rus_verbs:объясняться{}, // Они объясняются на иностранном языке.
rus_verbs:прощаться{}, // Они долго прощались на вокзале.
rus_verbs:работать{}, // Она работает на ткацкой фабрике.
rus_verbs:купить{}, // Она купила молоко на рынке.
rus_verbs:поместиться{}, // Все книги поместились на полке.
глагол:проводить{вид:несоверш}, инфинитив:проводить{вид:несоверш}, // Нужно проводить теорию на практике.
rus_verbs:пожить{}, // Недолго она пожила на свете.
rus_verbs:краснеть{}, // Небо краснеет на закате.
rus_verbs:бывать{}, // На Волге бывает сильное волнение.
rus_verbs:ехать{}, // Мы туда ехали на автобусе.
rus_verbs:провести{}, // Мы провели месяц на даче.
rus_verbs:поздороваться{}, // Мы поздоровались при встрече на улице.
rus_verbs:расти{}, // Арбузы растут теперь не только на юге.
ГЛ_ИНФ(сидеть), // три больших пса сидят на траве
ГЛ_ИНФ(сесть), // три больших пса сели на траву
ГЛ_ИНФ(перевернуться), // На дороге перевернулся автомобиль
ГЛ_ИНФ(повезти), // я повезу тебя на машине
ГЛ_ИНФ(отвезти), // мы отвезем тебя на такси
ГЛ_ИНФ(пить), // пить на кухне чай
ГЛ_ИНФ(найти), // найти на острове
ГЛ_ИНФ(быть), // на этих костях есть следы зубов
ГЛ_ИНФ(высадиться), // помощники высадились на острове
ГЛ_ИНФ(делать),прилагательное:делающий{}, прилагательное:делавший{}, деепричастие:делая{}, // смотрю фильм о том, что пираты делали на необитаемом острове
ГЛ_ИНФ(случиться), // это случилось на опушке леса
ГЛ_ИНФ(продать),
ГЛ_ИНФ(есть) // кошки ели мой корм на песчаном берегу
}
#endregion VerbList
// Чтобы разрешить связывание в паттернах типа: смотреть на youtube
fact гл_предл
{
if context { Гл_НА_Предл предлог:в{} @regex("[a-z]+[0-9]*") }
then return true
}
fact гл_предл
{
if context { Гл_НА_Предл предлог:на{} *:*{падеж:предл} }
then return true
}
// локатив
fact гл_предл
{
if context { Гл_НА_Предл предлог:на{} *:*{падеж:мест} }
then return true
}
#endregion ПРЕДЛОЖНЫЙ
#region ВИНИТЕЛЬНЫЙ
// НА+винительный падеж:
// ЗАБИРАТЬСЯ НА ВЕРШИНУ ГОРЫ
#region VerbList
wordentry_set Гл_НА_Вин=
{
rus_verbs:переметнуться{}, // Ее взгляд растерянно переметнулся на Лили.
rus_verbs:отогнать{}, // Водитель отогнал машину на стоянку.
rus_verbs:фапать{}, // Не фапай на желтяк и не перебивай.
rus_verbs:умножить{}, // Умножьте это количество примерно на 10.
//rus_verbs:умножать{},
rus_verbs:откатить{}, // Откатил Шпак валун на шлях и перекрыл им дорогу.
rus_verbs:откатывать{},
rus_verbs:доносить{}, // Вот и побежали на вас доносить.
rus_verbs:донести{},
rus_verbs:разбирать{}, // Ворованные автомобили злоумышленники разбирали на запчасти и продавали.
безлич_глагол:хватит{}, // - На одну атаку хватит.
rus_verbs:скупиться{}, // Он сражался за жизнь, не скупясь на хитрости и усилия, и пока этот стиль давал неплохие результаты.
rus_verbs:поскупиться{}, // Не поскупись на похвалы!
rus_verbs:подыматься{},
rus_verbs:транспортироваться{},
rus_verbs:бахнуть{}, // Бахнуть стакан на пол
rus_verbs:РАЗДЕЛИТЬ{}, // Президентские выборы разделили Венесуэлу на два непримиримых лагеря (РАЗДЕЛИТЬ)
rus_verbs:НАЦЕЛИВАТЬСЯ{}, // Невдалеке пролетел кондор, нацеливаясь на бизонью тушу. (НАЦЕЛИВАТЬСЯ)
rus_verbs:ВЫПЛЕСНУТЬ{}, // Низкий вибрирующий гул напоминал вулкан, вот-вот готовый выплеснуть на земную твердь потоки раскаленной лавы. (ВЫПЛЕСНУТЬ)
rus_verbs:ИСЧЕЗНУТЬ{}, // Оно фыркнуло и исчезло в лесу на другой стороне дороги (ИСЧЕЗНУТЬ)
rus_verbs:ВЫЗВАТЬ{}, // вызвать своего брата на поединок. (ВЫЗВАТЬ)
rus_verbs:ПОБРЫЗГАТЬ{}, // Матрос побрызгал немного фимиама на крошечный огонь (ПОБРЫЗГАТЬ/БРЫЗГАТЬ/БРЫЗНУТЬ/КАПНУТЬ/КАПАТЬ/ПОКАПАТЬ)
rus_verbs:БРЫЗГАТЬ{},
rus_verbs:БРЫЗНУТЬ{},
rus_verbs:КАПНУТЬ{},
rus_verbs:КАПАТЬ{},
rus_verbs:ПОКАПАТЬ{},
rus_verbs:ПООХОТИТЬСЯ{}, // Мы можем когда-нибудь вернуться и поохотиться на него. (ПООХОТИТЬСЯ/ОХОТИТЬСЯ)
rus_verbs:ОХОТИТЬСЯ{}, //
rus_verbs:ПОПАСТЬСЯ{}, // Не думал я, что они попадутся на это (ПОПАСТЬСЯ/НАРВАТЬСЯ/НАТОЛКНУТЬСЯ)
rus_verbs:НАРВАТЬСЯ{}, //
rus_verbs:НАТОЛКНУТЬСЯ{}, //
rus_verbs:ВЫСЛАТЬ{}, // Он выслал разведчиков на большое расстояние от основного отряда. (ВЫСЛАТЬ)
прилагательное:ПОХОЖИЙ{}, // Ты не выглядишь похожим на индейца (ПОХОЖИЙ)
rus_verbs:РАЗОРВАТЬ{}, // Через минуту он был мертв и разорван на части. (РАЗОРВАТЬ)
rus_verbs:СТОЛКНУТЬ{}, // Только быстрыми выпадами копья он сумел столкнуть их обратно на карниз. (СТОЛКНУТЬ/СТАЛКИВАТЬ)
rus_verbs:СТАЛКИВАТЬ{}, //
rus_verbs:СПУСТИТЬ{}, // Я побежал к ним, но они к тому времени спустили лодку на воду (СПУСТИТЬ)
rus_verbs:ПЕРЕБРАСЫВАТЬ{}, // Сирия перебрасывает на юг страны воинские подкрепления (ПЕРЕБРАСЫВАТЬ, ПЕРЕБРОСИТЬ, НАБРАСЫВАТЬ, НАБРОСИТЬ)
rus_verbs:ПЕРЕБРОСИТЬ{}, //
rus_verbs:НАБРАСЫВАТЬ{}, //
rus_verbs:НАБРОСИТЬ{}, //
rus_verbs:СВЕРНУТЬ{}, // Он вывел машину на бульвар и поехал на восток, а затем свернул на юг. (СВЕРНУТЬ/СВОРАЧИВАТЬ/ПОВЕРНУТЬ/ПОВОРАЧИВАТЬ)
rus_verbs:СВОРАЧИВАТЬ{}, // //
rus_verbs:ПОВЕРНУТЬ{}, //
rus_verbs:ПОВОРАЧИВАТЬ{}, //
rus_verbs:наорать{},
rus_verbs:ПРОДВИНУТЬСЯ{}, // Полк продвинется на десятки километров (ПРОДВИНУТЬСЯ)
rus_verbs:БРОСАТЬ{}, // Он бросает обещания на ветер (БРОСАТЬ)
rus_verbs:ОДОЛЖИТЬ{}, // Я вам одолжу книгу на десять дней (ОДОЛЖИТЬ)
rus_verbs:перегнать{}, // Скот нужно перегнать с этого пастбища на другое
rus_verbs:перегонять{},
rus_verbs:выгонять{},
rus_verbs:выгнать{},
rus_verbs:СВОДИТЬСЯ{}, // сейчас панели кузовов расходятся по десяткам покрасочных постов и потом сводятся вновь на общий конвейер (СВОДИТЬСЯ)
rus_verbs:ПОЖЕРТВОВАТЬ{}, // Бывший функционер компартии Эстонии пожертвовал деньги на расследования преступлений коммунизма (ПОЖЕРТВОВАТЬ)
rus_verbs:ПРОВЕРЯТЬ{}, // Школьников будут принудительно проверять на курение (ПРОВЕРЯТЬ)
rus_verbs:ОТПУСТИТЬ{}, // Приставы отпустят должников на отдых (ОТПУСТИТЬ)
rus_verbs:использоваться{}, // имеющийся у государства денежный запас активно используется на поддержание рынка акций
rus_verbs:назначаться{}, // назначаться на пост
rus_verbs:наблюдать{}, // Судья , долго наблюдавший в трубу , вдруг вскричал
rus_verbs:ШПИОНИТЬ{}, // Канадского офицера, шпионившего на Россию, приговорили к 20 годам тюрьмы (ШПИОНИТЬ НА вин)
rus_verbs:ЗАПЛАНИРОВАТЬ{}, // все деньги , запланированные на сейсмоукрепление домов на Камчатке (ЗАПЛАНИРОВАТЬ НА)
// rus_verbs:ПОХОДИТЬ{}, // больше походил на обвинительную речь , адресованную руководству республики (ПОХОДИТЬ НА)
rus_verbs:ДЕЙСТВОВАТЬ{}, // выявленный контрабандный канал действовал на постоянной основе (ДЕЙСТВОВАТЬ НА)
rus_verbs:ПЕРЕДАТЬ{}, // после чего должно быть передано на рассмотрение суда (ПЕРЕДАТЬ НА вин)
rus_verbs:НАЗНАЧИТЬСЯ{}, // Зимой на эту должность пытался назначиться народный депутат (НАЗНАЧИТЬСЯ НА)
rus_verbs:РЕШИТЬСЯ{}, // Франция решилась на одностороннее и рискованное военное вмешательство (РЕШИТЬСЯ НА)
rus_verbs:ОРИЕНТИРОВАТЬ{}, // Этот браузер полностью ориентирован на планшеты и сенсорный ввод (ОРИЕНТИРОВАТЬ НА вин)
rus_verbs:ЗАВЕСТИ{}, // на Витьку завели дело (ЗАВЕСТИ НА)
rus_verbs:ОБРУШИТЬСЯ{}, // В Северной Осетии на воинскую часть обрушилась снежная лавина (ОБРУШИТЬСЯ В, НА)
rus_verbs:НАСТРАИВАТЬСЯ{}, // гетеродин, настраивающийся на волну (НАСТРАИВАТЬСЯ НА)
rus_verbs:СУЩЕСТВОВАТЬ{}, // Он существует на средства родителей. (СУЩЕСТВОВАТЬ НА)
прилагательное:способный{}, // Он способен на убийство. (СПОСОБНЫЙ НА)
rus_verbs:посыпаться{}, // на Нину посыпались снежинки
инфинитив:нарезаться{ вид:несоверш }, // Урожай собирают механически или вручную, стебли нарезаются на куски и быстро транспортируются на перерабатывающий завод.
глагол:нарезаться{ вид:несоверш },
rus_verbs:пожаловать{}, // скандально известный певец пожаловал к нам на передачу
rus_verbs:показать{}, // Вадим показал на Колю
rus_verbs:съехаться{}, // Финалисты съехались на свои игры в Лос-Анжелес. (СЪЕХАТЬСЯ НА, В)
rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА)
rus_verbs:упасть{}, // В Таиланде на автобус с российскими туристами упал башенный кран (УПАСТЬ В, НА)
прилагательное:тугой{}, // Бабушка туга на ухо. (ТУГОЙ НА)
rus_verbs:свисать{}, // Волосы свисают на лоб. (свисать на)
rus_verbs:ЦЕНИТЬСЯ{}, // Всякая рабочая рука ценилась на вес золота. (ЦЕНИТЬСЯ НА)
rus_verbs:ШУМЕТЬ{}, // Вы шумите на весь дом! (ШУМЕТЬ НА)
rus_verbs:протянуться{}, // Дорога протянулась на сотни километров. (протянуться на)
rus_verbs:РАССЧИТАТЬ{}, // Книга рассчитана на массового читателя. (РАССЧИТАТЬ НА)
rus_verbs:СОРИЕНТИРОВАТЬ{}, // мы сориентировали процесс на повышение котировок (СОРИЕНТИРОВАТЬ НА)
rus_verbs:рыкнуть{}, // рыкнуть на остальных членов стаи (рыкнуть на)
rus_verbs:оканчиваться{}, // оканчиваться на звонкую согласную (оканчиваться на)
rus_verbs:выехать{}, // посигналить нарушителю, выехавшему на встречную полосу (выехать на)
rus_verbs:прийтись{}, // Пятое число пришлось на субботу.
rus_verbs:крениться{}, // корабль кренился на правый борт (крениться на)
rus_verbs:приходиться{}, // основной налоговый гнет приходится на средний бизнес (приходиться на)
rus_verbs:верить{}, // верить людям на слово (верить на слово)
rus_verbs:выезжать{}, // Завтра вся семья выезжает на новую квартиру.
rus_verbs:записать{}, // Запишите меня на завтрашний приём к доктору.
rus_verbs:пасть{}, // Жребий пал на меня.
rus_verbs:ездить{}, // Вчера мы ездили на оперу.
rus_verbs:влезть{}, // Мальчик влез на дерево.
rus_verbs:выбежать{}, // Мальчик выбежал из комнаты на улицу.
rus_verbs:разбиться{}, // окно разбилось на мелкие осколки
rus_verbs:бежать{}, // я бегу на урок
rus_verbs:сбегаться{}, // сбегаться на происшествие
rus_verbs:присылать{}, // присылать на испытание
rus_verbs:надавить{}, // надавить на педать
rus_verbs:внести{}, // внести законопроект на рассмотрение
rus_verbs:вносить{}, // вносить законопроект на рассмотрение
rus_verbs:поворачиваться{}, // поворачиваться на 180 градусов
rus_verbs:сдвинуть{}, // сдвинуть на несколько сантиметров
rus_verbs:опубликовать{}, // С.Митрохин опубликовал компромат на думских подельников Гудкова
rus_verbs:вырасти{}, // Официальный курс доллара вырос на 26 копеек.
rus_verbs:оглядываться{}, // оглядываться на девушек
rus_verbs:расходиться{}, // расходиться на отдых
rus_verbs:поскакать{}, // поскакать на службу
rus_verbs:прыгать{}, // прыгать на сцену
rus_verbs:приглашать{}, // приглашать на обед
rus_verbs:рваться{}, // Кусок ткани рвется на части
rus_verbs:понестись{}, // понестись на волю
rus_verbs:распространяться{}, // распространяться на всех жителей штата
инфинитив:просыпаться{ вид:соверш }, глагол:просыпаться{ вид:соверш }, // просыпаться на пол
инфинитив:просыпаться{ вид:несоверш }, глагол:просыпаться{ вид:несоверш },
деепричастие:просыпавшись{}, деепричастие:просыпаясь{},
rus_verbs:заехать{}, // заехать на пандус
rus_verbs:разобрать{}, // разобрать на составляющие
rus_verbs:опускаться{}, // опускаться на колени
rus_verbs:переехать{}, // переехать на конспиративную квартиру
rus_verbs:закрывать{}, // закрывать глаза на действия конкурентов
rus_verbs:поместить{}, // поместить на поднос
rus_verbs:отходить{}, // отходить на подготовленные позиции
rus_verbs:сыпаться{}, // сыпаться на плечи
rus_verbs:отвезти{}, // отвезти на занятия
rus_verbs:накинуть{}, // накинуть на плечи
rus_verbs:отлететь{}, // отлететь на пол
rus_verbs:закинуть{}, // закинуть на чердак
rus_verbs:зашипеть{}, // зашипеть на собаку
rus_verbs:прогреметь{}, // прогреметь на всю страну
rus_verbs:повалить{}, // повалить на стол
rus_verbs:опереть{}, // опереть на фундамент
rus_verbs:забросить{}, // забросить на антресоль
rus_verbs:подействовать{}, // подействовать на материал
rus_verbs:разделять{}, // разделять на части
rus_verbs:прикрикнуть{}, // прикрикнуть на детей
rus_verbs:разложить{}, // разложить на множители
rus_verbs:провожать{}, // провожать на работу
rus_verbs:катить{}, // катить на стройку
rus_verbs:наложить{}, // наложить запрет на проведение операций с недвижимостью
rus_verbs:сохранять{}, // сохранять на память
rus_verbs:злиться{}, // злиться на друга
rus_verbs:оборачиваться{}, // оборачиваться на свист
rus_verbs:сползти{}, // сползти на землю
rus_verbs:записывать{}, // записывать на ленту
rus_verbs:загнать{}, // загнать на дерево
rus_verbs:забормотать{}, // забормотать на ухо
rus_verbs:протиснуться{}, // протиснуться на самый край
rus_verbs:заторопиться{}, // заторопиться на вручение премии
rus_verbs:гаркнуть{}, // гаркнуть на шалунов
rus_verbs:навалиться{}, // навалиться на виновника всей толпой
rus_verbs:проскользнуть{}, // проскользнуть на крышу дома
rus_verbs:подтянуть{}, // подтянуть на палубу
rus_verbs:скатиться{}, // скатиться на двойки
rus_verbs:давить{}, // давить на жалость
rus_verbs:намекнуть{}, // намекнуть на новые обстоятельства
rus_verbs:замахнуться{}, // замахнуться на святое
rus_verbs:заменить{}, // заменить на свежую салфетку
rus_verbs:свалить{}, // свалить на землю
rus_verbs:стекать{}, // стекать на оголенные провода
rus_verbs:увеличиваться{}, // увеличиваться на сотню процентов
rus_verbs:развалиться{}, // развалиться на части
rus_verbs:сердиться{}, // сердиться на товарища
rus_verbs:обронить{}, // обронить на пол
rus_verbs:подсесть{}, // подсесть на наркоту
rus_verbs:реагировать{}, // реагировать на импульсы
rus_verbs:отпускать{}, // отпускать на волю
rus_verbs:прогнать{}, // прогнать на рабочее место
rus_verbs:ложить{}, // ложить на стол
rus_verbs:рвать{}, // рвать на части
rus_verbs:разлететься{}, // разлететься на кусочки
rus_verbs:превышать{}, // превышать на существенную величину
rus_verbs:сбиться{}, // сбиться на рысь
rus_verbs:пристроиться{}, // пристроиться на хорошую работу
rus_verbs:удрать{}, // удрать на пастбище
rus_verbs:толкать{}, // толкать на преступление
rus_verbs:посматривать{}, // посматривать на экран
rus_verbs:набирать{}, // набирать на судно
rus_verbs:отступать{}, // отступать на дерево
rus_verbs:подуть{}, // подуть на молоко
rus_verbs:плеснуть{}, // плеснуть на голову
rus_verbs:соскользнуть{}, // соскользнуть на землю
rus_verbs:затаить{}, // затаить на кого-то обиду
rus_verbs:обижаться{}, // обижаться на Колю
rus_verbs:смахнуть{}, // смахнуть на пол
rus_verbs:застегнуть{}, // застегнуть на все пуговицы
rus_verbs:спускать{}, // спускать на землю
rus_verbs:греметь{}, // греметь на всю округу
rus_verbs:скосить{}, // скосить на соседа глаз
rus_verbs:отважиться{}, // отважиться на прыжок
rus_verbs:литься{}, // литься на землю
rus_verbs:порвать{}, // порвать на тряпки
rus_verbs:проследовать{}, // проследовать на сцену
rus_verbs:надевать{}, // надевать на голову
rus_verbs:проскочить{}, // проскочить на красный свет
rus_verbs:прилечь{}, // прилечь на диванчик
rus_verbs:разделиться{}, // разделиться на небольшие группы
rus_verbs:завыть{}, // завыть на луну
rus_verbs:переносить{}, // переносить на другую машину
rus_verbs:наговорить{}, // наговорить на сотню рублей
rus_verbs:намекать{}, // намекать на новые обстоятельства
rus_verbs:нападать{}, // нападать на охранников
rus_verbs:убегать{}, // убегать на другое место
rus_verbs:тратить{}, // тратить на развлечения
rus_verbs:присаживаться{}, // присаживаться на корточки
rus_verbs:переместиться{}, // переместиться на вторую линию
rus_verbs:завалиться{}, // завалиться на диван
rus_verbs:удалиться{}, // удалиться на покой
rus_verbs:уменьшаться{}, // уменьшаться на несколько процентов
rus_verbs:обрушить{}, // обрушить на голову
rus_verbs:резать{}, // резать на части
rus_verbs:умчаться{}, // умчаться на юг
rus_verbs:навернуться{}, // навернуться на камень
rus_verbs:примчаться{}, // примчаться на матч
rus_verbs:издавать{}, // издавать на собственные средства
rus_verbs:переключить{}, // переключить на другой язык
rus_verbs:отправлять{}, // отправлять на пенсию
rus_verbs:залечь{}, // залечь на дно
rus_verbs:установиться{}, // установиться на диск
rus_verbs:направлять{}, // направлять на дополнительное обследование
rus_verbs:разрезать{}, // разрезать на части
rus_verbs:оскалиться{}, // оскалиться на прохожего
rus_verbs:рычать{}, // рычать на пьяных
rus_verbs:погружаться{}, // погружаться на дно
rus_verbs:опираться{}, // опираться на костыли
rus_verbs:поторопиться{}, // поторопиться на учебу
rus_verbs:сдвинуться{}, // сдвинуться на сантиметр
rus_verbs:увеличить{}, // увеличить на процент
rus_verbs:опускать{}, // опускать на землю
rus_verbs:созвать{}, // созвать на митинг
rus_verbs:делить{}, // делить на части
rus_verbs:пробиться{}, // пробиться на заключительную часть
rus_verbs:простираться{}, // простираться на много миль
rus_verbs:забить{}, // забить на учебу
rus_verbs:переложить{}, // переложить на чужие плечи
rus_verbs:грохнуться{}, // грохнуться на землю
rus_verbs:прорваться{}, // прорваться на сцену
rus_verbs:разлить{}, // разлить на землю
rus_verbs:укладываться{}, // укладываться на ночевку
rus_verbs:уволить{}, // уволить на пенсию
rus_verbs:наносить{}, // наносить на кожу
rus_verbs:набежать{}, // набежать на берег
rus_verbs:заявиться{}, // заявиться на стрельбище
rus_verbs:налиться{}, // налиться на крышку
rus_verbs:надвигаться{}, // надвигаться на берег
rus_verbs:распустить{}, // распустить на каникулы
rus_verbs:переключиться{}, // переключиться на другую задачу
rus_verbs:чихнуть{}, // чихнуть на окружающих
rus_verbs:шлепнуться{}, // шлепнуться на спину
rus_verbs:устанавливать{}, // устанавливать на крышу
rus_verbs:устанавливаться{}, // устанавливаться на крышу
rus_verbs:устраиваться{}, // устраиваться на работу
rus_verbs:пропускать{}, // пропускать на стадион
инфинитив:сбегать{ вид:соверш }, глагол:сбегать{ вид:соверш }, // сбегать на фильм
инфинитив:сбегать{ вид:несоверш }, глагол:сбегать{ вид:несоверш },
деепричастие:сбегав{}, деепричастие:сбегая{},
rus_verbs:показываться{}, // показываться на глаза
rus_verbs:прибегать{}, // прибегать на урок
rus_verbs:съездить{}, // съездить на ферму
rus_verbs:прославиться{}, // прославиться на всю страну
rus_verbs:опрокинуться{}, // опрокинуться на спину
rus_verbs:насыпать{}, // насыпать на землю
rus_verbs:употреблять{}, // употреблять на корм скоту
rus_verbs:пристроить{}, // пристроить на работу
rus_verbs:заворчать{}, // заворчать на вошедшего
rus_verbs:завязаться{}, // завязаться на поставщиков
rus_verbs:сажать{}, // сажать на стул
rus_verbs:напрашиваться{}, // напрашиваться на жесткие ответные меры
rus_verbs:заменять{}, // заменять на исправную
rus_verbs:нацепить{}, // нацепить на голову
rus_verbs:сыпать{}, // сыпать на землю
rus_verbs:закрываться{}, // закрываться на ремонт
rus_verbs:распространиться{}, // распространиться на всю популяцию
rus_verbs:поменять{}, // поменять на велосипед
rus_verbs:пересесть{}, // пересесть на велосипеды
rus_verbs:подоспеть{}, // подоспеть на разбор
rus_verbs:шипеть{}, // шипеть на собак
rus_verbs:поделить{}, // поделить на части
rus_verbs:подлететь{}, // подлететь на расстояние выстрела
rus_verbs:нажимать{}, // нажимать на все кнопки
rus_verbs:распасться{}, // распасться на части
rus_verbs:приволочь{}, // приволочь на диван
rus_verbs:пожить{}, // пожить на один доллар
rus_verbs:устремляться{}, // устремляться на свободу
rus_verbs:смахивать{}, // смахивать на пол
rus_verbs:забежать{}, // забежать на обед
rus_verbs:увеличиться{}, // увеличиться на существенную величину
rus_verbs:прокрасться{}, // прокрасться на склад
rus_verbs:пущать{}, // пущать на постой
rus_verbs:отклонить{}, // отклонить на несколько градусов
rus_verbs:насмотреться{}, // насмотреться на безобразия
rus_verbs:настроить{}, // настроить на короткие волны
rus_verbs:уменьшиться{}, // уменьшиться на пару сантиметров
rus_verbs:поменяться{}, // поменяться на другую книжку
rus_verbs:расколоться{}, // расколоться на части
rus_verbs:разлиться{}, // разлиться на землю
rus_verbs:срываться{}, // срываться на жену
rus_verbs:осудить{}, // осудить на пожизненное заключение
rus_verbs:передвинуть{}, // передвинуть на первое место
rus_verbs:допускаться{}, // допускаться на полигон
rus_verbs:задвинуть{}, // задвинуть на полку
rus_verbs:повлиять{}, // повлиять на оценку
rus_verbs:отбавлять{}, // отбавлять на осмотр
rus_verbs:сбрасывать{}, // сбрасывать на землю
rus_verbs:накинуться{}, // накинуться на случайных прохожих
rus_verbs:пролить{}, // пролить на кожу руки
rus_verbs:затащить{}, // затащить на сеновал
rus_verbs:перебежать{}, // перебежать на сторону противника
rus_verbs:наливать{}, // наливать на скатерть
rus_verbs:пролезть{}, // пролезть на сцену
rus_verbs:откладывать{}, // откладывать на черный день
rus_verbs:распадаться{}, // распадаться на небольшие фрагменты
rus_verbs:перечислить{}, // перечислить на счет
rus_verbs:закачаться{}, // закачаться на верхний уровень
rus_verbs:накрениться{}, // накрениться на правый борт
rus_verbs:подвинуться{}, // подвинуться на один уровень
rus_verbs:разнести{}, // разнести на мелкие кусочки
rus_verbs:зажить{}, // зажить на широкую ногу
rus_verbs:оглохнуть{}, // оглохнуть на правое ухо
rus_verbs:посетовать{}, // посетовать на бюрократизм
rus_verbs:уводить{}, // уводить на осмотр
rus_verbs:ускакать{}, // ускакать на забег
rus_verbs:посветить{}, // посветить на стену
rus_verbs:разрываться{}, // разрываться на части
rus_verbs:побросать{}, // побросать на землю
rus_verbs:карабкаться{}, // карабкаться на скалу
rus_verbs:нахлынуть{}, // нахлынуть на кого-то
rus_verbs:разлетаться{}, // разлетаться на мелкие осколочки
rus_verbs:среагировать{}, // среагировать на сигнал
rus_verbs:претендовать{}, // претендовать на приз
rus_verbs:дунуть{}, // дунуть на одуванчик
rus_verbs:переводиться{}, // переводиться на другую работу
rus_verbs:перевезти{}, // перевезти на другую площадку
rus_verbs:топать{}, // топать на урок
rus_verbs:относить{}, // относить на склад
rus_verbs:сбивать{}, // сбивать на землю
rus_verbs:укладывать{}, // укладывать на спину
rus_verbs:укатить{}, // укатить на отдых
rus_verbs:убирать{}, // убирать на полку
rus_verbs:опасть{}, // опасть на землю
rus_verbs:ронять{}, // ронять на снег
rus_verbs:пялиться{}, // пялиться на тело
rus_verbs:глазеть{}, // глазеть на тело
rus_verbs:снижаться{}, // снижаться на безопасную высоту
rus_verbs:запрыгнуть{}, // запрыгнуть на платформу
rus_verbs:разбиваться{}, // разбиваться на главы
rus_verbs:сгодиться{}, // сгодиться на фарш
rus_verbs:перескочить{}, // перескочить на другую страницу
rus_verbs:нацелиться{}, // нацелиться на главную добычу
rus_verbs:заезжать{}, // заезжать на бордюр
rus_verbs:забираться{}, // забираться на крышу
rus_verbs:проорать{}, // проорать на всё село
rus_verbs:сбежаться{}, // сбежаться на шум
rus_verbs:сменять{}, // сменять на хлеб
rus_verbs:мотать{}, // мотать на ус
rus_verbs:раскалываться{}, // раскалываться на две половинки
rus_verbs:коситься{}, // коситься на режиссёра
rus_verbs:плевать{}, // плевать на законы
rus_verbs:ссылаться{}, // ссылаться на авторитетное мнение
rus_verbs:наставить{}, // наставить на путь истинный
rus_verbs:завывать{}, // завывать на Луну
rus_verbs:опаздывать{}, // опаздывать на совещание
rus_verbs:залюбоваться{}, // залюбоваться на пейзаж
rus_verbs:повергнуть{}, // повергнуть на землю
rus_verbs:надвинуть{}, // надвинуть на лоб
rus_verbs:стекаться{}, // стекаться на площадь
rus_verbs:обозлиться{}, // обозлиться на тренера
rus_verbs:оттянуть{}, // оттянуть на себя
rus_verbs:истратить{}, // истратить на дешевых шлюх
rus_verbs:вышвырнуть{}, // вышвырнуть на улицу
rus_verbs:затолкать{}, // затолкать на верхнюю полку
rus_verbs:заскочить{}, // заскочить на огонек
rus_verbs:проситься{}, // проситься на улицу
rus_verbs:натыкаться{}, // натыкаться на борщевик
rus_verbs:обрушиваться{}, // обрушиваться на митингующих
rus_verbs:переписать{}, // переписать на чистовик
rus_verbs:переноситься{}, // переноситься на другое устройство
rus_verbs:напроситься{}, // напроситься на обидный ответ
rus_verbs:натягивать{}, // натягивать на ноги
rus_verbs:кидаться{}, // кидаться на прохожих
rus_verbs:откликаться{}, // откликаться на призыв
rus_verbs:поспевать{}, // поспевать на балет
rus_verbs:обратиться{}, // обратиться на кафедру
rus_verbs:полюбоваться{}, // полюбоваться на бюст
rus_verbs:таращиться{}, // таращиться на мустангов
rus_verbs:напороться{}, // напороться на колючки
rus_verbs:раздать{}, // раздать на руки
rus_verbs:дивиться{}, // дивиться на танцовщиц
rus_verbs:назначать{}, // назначать на ответственнейший пост
rus_verbs:кидать{}, // кидать на балкон
rus_verbs:нахлобучить{}, // нахлобучить на башку
rus_verbs:увлекать{}, // увлекать на луг
rus_verbs:ругнуться{}, // ругнуться на животину
rus_verbs:переселиться{}, // переселиться на хутор
rus_verbs:разрывать{}, // разрывать на части
rus_verbs:утащить{}, // утащить на дерево
rus_verbs:наставлять{}, // наставлять на путь
rus_verbs:соблазнить{}, // соблазнить на обмен
rus_verbs:накладывать{}, // накладывать на рану
rus_verbs:набрести{}, // набрести на грибную поляну
rus_verbs:наведываться{}, // наведываться на прежнюю работу
rus_verbs:погулять{}, // погулять на чужие деньги
rus_verbs:уклоняться{}, // уклоняться на два градуса влево
rus_verbs:слезать{}, // слезать на землю
rus_verbs:клевать{}, // клевать на мотыля
// rus_verbs:назначаться{}, // назначаться на пост
rus_verbs:напялить{}, // напялить на голову
rus_verbs:натянуться{}, // натянуться на рамку
rus_verbs:разгневаться{}, // разгневаться на придворных
rus_verbs:эмигрировать{}, // эмигрировать на Кипр
rus_verbs:накатить{}, // накатить на основу
rus_verbs:пригнать{}, // пригнать на пастбище
rus_verbs:обречь{}, // обречь на мучения
rus_verbs:сокращаться{}, // сокращаться на четверть
rus_verbs:оттеснить{}, // оттеснить на пристань
rus_verbs:подбить{}, // подбить на аферу
rus_verbs:заманить{}, // заманить на дерево
инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать на кустик
// деепричастие:пописав{ aux stress="поп^исать" },
rus_verbs:посходить{}, // посходить на перрон
rus_verbs:налечь{}, // налечь на мясцо
rus_verbs:отбирать{}, // отбирать на флот
rus_verbs:нашептывать{}, // нашептывать на ухо
rus_verbs:откладываться{}, // откладываться на будущее
rus_verbs:залаять{}, // залаять на грабителя
rus_verbs:настроиться{}, // настроиться на прием
rus_verbs:разбивать{}, // разбивать на куски
rus_verbs:пролиться{}, // пролиться на почву
rus_verbs:сетовать{}, // сетовать на объективные трудности
rus_verbs:подвезти{}, // подвезти на митинг
rus_verbs:припереться{}, // припереться на праздник
rus_verbs:подталкивать{}, // подталкивать на прыжок
rus_verbs:прорываться{}, // прорываться на сцену
rus_verbs:снижать{}, // снижать на несколько процентов
rus_verbs:нацелить{}, // нацелить на танк
rus_verbs:расколоть{}, // расколоть на два куска
rus_verbs:увозить{}, // увозить на обкатку
rus_verbs:оседать{}, // оседать на дно
rus_verbs:съедать{}, // съедать на ужин
rus_verbs:навлечь{}, // навлечь на себя
rus_verbs:равняться{}, // равняться на лучших
rus_verbs:сориентироваться{}, // сориентироваться на местности
rus_verbs:снизить{}, // снизить на несколько процентов
rus_verbs:перенестись{}, // перенестись на много лет назад
rus_verbs:завезти{}, // завезти на склад
rus_verbs:проложить{}, // проложить на гору
rus_verbs:понадеяться{}, // понадеяться на удачу
rus_verbs:заступить{}, // заступить на вахту
rus_verbs:засеменить{}, // засеменить на выход
rus_verbs:запирать{}, // запирать на ключ
rus_verbs:скатываться{}, // скатываться на землю
rus_verbs:дробить{}, // дробить на части
rus_verbs:разваливаться{}, // разваливаться на кусочки
rus_verbs:завозиться{}, // завозиться на склад
rus_verbs:нанимать{}, // нанимать на дневную работу
rus_verbs:поспеть{}, // поспеть на концерт
rus_verbs:променять{}, // променять на сытость
rus_verbs:переправить{}, // переправить на север
rus_verbs:налетать{}, // налетать на силовое поле
rus_verbs:затворить{}, // затворить на замок
rus_verbs:подогнать{}, // подогнать на пристань
rus_verbs:наехать{}, // наехать на камень
rus_verbs:распевать{}, // распевать на разные голоса
rus_verbs:разносить{}, // разносить на клочки
rus_verbs:преувеличивать{}, // преувеличивать на много килограммов
rus_verbs:хромать{}, // хромать на одну ногу
rus_verbs:телеграфировать{}, // телеграфировать на базу
rus_verbs:порезать{}, // порезать на лоскуты
rus_verbs:порваться{}, // порваться на части
rus_verbs:загонять{}, // загонять на дерево
rus_verbs:отбывать{}, // отбывать на место службы
rus_verbs:усаживаться{}, // усаживаться на трон
rus_verbs:накопить{}, // накопить на квартиру
rus_verbs:зыркнуть{}, // зыркнуть на визитера
rus_verbs:копить{}, // копить на машину
rus_verbs:помещать{}, // помещать на верхнюю грань
rus_verbs:сползать{}, // сползать на снег
rus_verbs:попроситься{}, // попроситься на улицу
rus_verbs:перетащить{}, // перетащить на чердак
rus_verbs:растащить{}, // растащить на сувениры
rus_verbs:ниспадать{}, // ниспадать на землю
rus_verbs:сфотографировать{}, // сфотографировать на память
rus_verbs:нагонять{}, // нагонять на конкурентов страх
rus_verbs:покушаться{}, // покушаться на понтифика
rus_verbs:покуситься{},
rus_verbs:наняться{}, // наняться на службу
rus_verbs:просачиваться{}, // просачиваться на поверхность
rus_verbs:пускаться{}, // пускаться на ветер
rus_verbs:отваживаться{}, // отваживаться на прыжок
rus_verbs:досадовать{}, // досадовать на объективные трудности
rus_verbs:унестись{}, // унестись на небо
rus_verbs:ухудшаться{}, // ухудшаться на несколько процентов
rus_verbs:насадить{}, // насадить на копьё
rus_verbs:нагрянуть{}, // нагрянуть на праздник
rus_verbs:зашвырнуть{}, // зашвырнуть на полку
rus_verbs:грешить{}, // грешить на постояльцев
rus_verbs:просочиться{}, // просочиться на поверхность
rus_verbs:надоумить{}, // надоумить на глупость
rus_verbs:намотать{}, // намотать на шпиндель
rus_verbs:замкнуть{}, // замкнуть на корпус
rus_verbs:цыкнуть{}, // цыкнуть на детей
rus_verbs:переворачиваться{}, // переворачиваться на спину
rus_verbs:соваться{}, // соваться на площать
rus_verbs:отлучиться{}, // отлучиться на обед
rus_verbs:пенять{}, // пенять на себя
rus_verbs:нарезать{}, // нарезать на ломтики
rus_verbs:поставлять{}, // поставлять на Кипр
rus_verbs:залезать{}, // залезать на балкон
rus_verbs:отлучаться{}, // отлучаться на обед
rus_verbs:сбиваться{}, // сбиваться на шаг
rus_verbs:таращить{}, // таращить глаза на вошедшего
rus_verbs:прошмыгнуть{}, // прошмыгнуть на кухню
rus_verbs:опережать{}, // опережать на пару сантиметров
rus_verbs:переставить{}, // переставить на стол
rus_verbs:раздирать{}, // раздирать на части
rus_verbs:затвориться{}, // затвориться на засовы
rus_verbs:материться{}, // материться на кого-то
rus_verbs:наскочить{}, // наскочить на риф
rus_verbs:набираться{}, // набираться на борт
rus_verbs:покрикивать{}, // покрикивать на помощников
rus_verbs:заменяться{}, // заменяться на более новый
rus_verbs:подсадить{}, // подсадить на верхнюю полку
rus_verbs:проковылять{}, // проковылять на кухню
rus_verbs:прикатить{}, // прикатить на старт
rus_verbs:залететь{}, // залететь на чужую территорию
rus_verbs:загрузить{}, // загрузить на конвейер
rus_verbs:уплывать{}, // уплывать на материк
rus_verbs:опозорить{}, // опозорить на всю деревню
rus_verbs:провоцировать{}, // провоцировать на ответную агрессию
rus_verbs:забивать{}, // забивать на учебу
rus_verbs:набегать{}, // набегать на прибрежные деревни
rus_verbs:запираться{}, // запираться на ключ
rus_verbs:фотографировать{}, // фотографировать на мыльницу
rus_verbs:подымать{}, // подымать на недосягаемую высоту
rus_verbs:съезжаться{}, // съезжаться на симпозиум
rus_verbs:отвлекаться{}, // отвлекаться на игру
rus_verbs:проливать{}, // проливать на брюки
rus_verbs:спикировать{}, // спикировать на зазевавшегося зайца
rus_verbs:уползти{}, // уползти на вершину холма
rus_verbs:переместить{}, // переместить на вторую палубу
rus_verbs:превысить{}, // превысить на несколько метров
rus_verbs:передвинуться{}, // передвинуться на соседнюю клетку
rus_verbs:спровоцировать{}, // спровоцировать на бросок
rus_verbs:сместиться{}, // сместиться на соседнюю клетку
rus_verbs:заготовить{}, // заготовить на зиму
rus_verbs:плеваться{}, // плеваться на пол
rus_verbs:переселить{}, // переселить на север
rus_verbs:напирать{}, // напирать на дверь
rus_verbs:переезжать{}, // переезжать на другой этаж
rus_verbs:приподнимать{}, // приподнимать на несколько сантиметров
rus_verbs:трогаться{}, // трогаться на красный свет
rus_verbs:надвинуться{}, // надвинуться на глаза
rus_verbs:засмотреться{}, // засмотреться на купальники
rus_verbs:убыть{}, // убыть на фронт
rus_verbs:передвигать{}, // передвигать на второй уровень
rus_verbs:отвозить{}, // отвозить на свалку
rus_verbs:обрекать{}, // обрекать на гибель
rus_verbs:записываться{}, // записываться на танцы
rus_verbs:настраивать{}, // настраивать на другой диапазон
rus_verbs:переписывать{}, // переписывать на диск
rus_verbs:израсходовать{}, // израсходовать на гонки
rus_verbs:обменять{}, // обменять на перспективного игрока
rus_verbs:трубить{}, // трубить на всю округу
rus_verbs:набрасываться{}, // набрасываться на жертву
rus_verbs:чихать{}, // чихать на правила
rus_verbs:наваливаться{}, // наваливаться на рычаг
rus_verbs:сподобиться{}, // сподобиться на повторный анализ
rus_verbs:намазать{}, // намазать на хлеб
rus_verbs:прореагировать{}, // прореагировать на вызов
rus_verbs:зачислить{}, // зачислить на факультет
rus_verbs:наведаться{}, // наведаться на склад
rus_verbs:откидываться{}, // откидываться на спинку кресла
rus_verbs:захромать{}, // захромать на левую ногу
rus_verbs:перекочевать{}, // перекочевать на другой берег
rus_verbs:накатываться{}, // накатываться на песчаный берег
rus_verbs:приостановить{}, // приостановить на некоторое время
rus_verbs:запрятать{}, // запрятать на верхнюю полочку
rus_verbs:прихрамывать{}, // прихрамывать на правую ногу
rus_verbs:упорхнуть{}, // упорхнуть на свободу
rus_verbs:расстегивать{}, // расстегивать на пальто
rus_verbs:напуститься{}, // напуститься на бродягу
rus_verbs:накатывать{}, // накатывать на оригинал
rus_verbs:наезжать{}, // наезжать на простофилю
rus_verbs:тявкнуть{}, // тявкнуть на подошедшего человека
rus_verbs:отрядить{}, // отрядить на починку
rus_verbs:положиться{}, // положиться на главаря
rus_verbs:опрокидывать{}, // опрокидывать на голову
rus_verbs:поторапливаться{}, // поторапливаться на рейс
rus_verbs:налагать{}, // налагать на заемщика
rus_verbs:скопировать{}, // скопировать на диск
rus_verbs:опадать{}, // опадать на землю
rus_verbs:купиться{}, // купиться на посулы
rus_verbs:гневаться{}, // гневаться на слуг
rus_verbs:слететься{}, // слететься на раздачу
rus_verbs:убавить{}, // убавить на два уровня
rus_verbs:спихнуть{}, // спихнуть на соседа
rus_verbs:накричать{}, // накричать на ребенка
rus_verbs:приберечь{}, // приберечь на ужин
rus_verbs:приклеить{}, // приклеить на ветровое стекло
rus_verbs:ополчиться{}, // ополчиться на посредников
rus_verbs:тратиться{}, // тратиться на сувениры
rus_verbs:слетаться{}, // слетаться на свет
rus_verbs:доставляться{}, // доставляться на базу
rus_verbs:поплевать{}, // поплевать на руки
rus_verbs:огрызаться{}, // огрызаться на замечание
rus_verbs:попереться{}, // попереться на рынок
rus_verbs:растягиваться{}, // растягиваться на полу
rus_verbs:повергать{}, // повергать на землю
rus_verbs:ловиться{}, // ловиться на мотыля
rus_verbs:наседать{}, // наседать на обороняющихся
rus_verbs:развалить{}, // развалить на кирпичи
rus_verbs:разломить{}, // разломить на несколько частей
rus_verbs:примерить{}, // примерить на себя
rus_verbs:лепиться{}, // лепиться на стену
rus_verbs:скопить{}, // скопить на старость
rus_verbs:затратить{}, // затратить на ликвидацию последствий
rus_verbs:притащиться{}, // притащиться на гулянку
rus_verbs:осерчать{}, // осерчать на прислугу
rus_verbs:натравить{}, // натравить на медведя
rus_verbs:ссыпать{}, // ссыпать на землю
rus_verbs:подвозить{}, // подвозить на пристань
rus_verbs:мобилизовать{}, // мобилизовать на сборы
rus_verbs:смотаться{}, // смотаться на работу
rus_verbs:заглядеться{}, // заглядеться на девчонок
rus_verbs:таскаться{}, // таскаться на работу
rus_verbs:разгружать{}, // разгружать на транспортер
rus_verbs:потреблять{}, // потреблять на кондиционирование
инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять на базу
деепричастие:сгоняв{},
rus_verbs:посылаться{}, // посылаться на разведку
rus_verbs:окрыситься{}, // окрыситься на кого-то
rus_verbs:отлить{}, // отлить на сковороду
rus_verbs:шикнуть{}, // шикнуть на детишек
rus_verbs:уповать{}, // уповать на бескорысную помощь
rus_verbs:класться{}, // класться на стол
rus_verbs:поковылять{}, // поковылять на выход
rus_verbs:навевать{}, // навевать на собравшихся скуку
rus_verbs:накладываться{}, // накладываться на грунтовку
rus_verbs:наноситься{}, // наноситься на чистую кожу
// rus_verbs:запланировать{}, // запланировать на среду
rus_verbs:кувыркнуться{}, // кувыркнуться на землю
rus_verbs:гавкнуть{}, // гавкнуть на хозяина
rus_verbs:перестроиться{}, // перестроиться на новый лад
rus_verbs:расходоваться{}, // расходоваться на образование
rus_verbs:дуться{}, // дуться на бабушку
rus_verbs:перетаскивать{}, // перетаскивать на рабочий стол
rus_verbs:издаться{}, // издаться на деньги спонсоров
rus_verbs:смещаться{}, // смещаться на несколько миллиметров
rus_verbs:зазывать{}, // зазывать на новогоднюю распродажу
rus_verbs:пикировать{}, // пикировать на окопы
rus_verbs:чертыхаться{}, // чертыхаться на мешающихся детей
rus_verbs:зудить{}, // зудить на ухо
rus_verbs:подразделяться{}, // подразделяться на группы
rus_verbs:изливаться{}, // изливаться на землю
rus_verbs:помочиться{}, // помочиться на траву
rus_verbs:примерять{}, // примерять на себя
rus_verbs:разрядиться{}, // разрядиться на землю
rus_verbs:мотнуться{}, // мотнуться на крышу
rus_verbs:налегать{}, // налегать на весла
rus_verbs:зацокать{}, // зацокать на куриц
rus_verbs:наниматься{}, // наниматься на корабль
rus_verbs:сплевывать{}, // сплевывать на землю
rus_verbs:настучать{}, // настучать на саботажника
rus_verbs:приземляться{}, // приземляться на брюхо
rus_verbs:наталкиваться{}, // наталкиваться на объективные трудности
rus_verbs:посигналить{}, // посигналить нарушителю, выехавшему на встречную полосу
rus_verbs:серчать{}, // серчать на нерасторопную помощницу
rus_verbs:сваливать{}, // сваливать на подоконник
rus_verbs:засобираться{}, // засобираться на работу
rus_verbs:распилить{}, // распилить на одинаковые бруски
//rus_verbs:умножать{}, // умножать на константу
rus_verbs:копировать{}, // копировать на диск
rus_verbs:накрутить{}, // накрутить на руку
rus_verbs:навалить{}, // навалить на телегу
rus_verbs:натолкнуть{}, // натолкнуть на свежую мысль
rus_verbs:шлепаться{}, // шлепаться на бетон
rus_verbs:ухлопать{}, // ухлопать на скупку произведений искусства
rus_verbs:замахиваться{}, // замахиваться на авторитетнейшее мнение
rus_verbs:посягнуть{}, // посягнуть на святое
rus_verbs:разменять{}, // разменять на мелочь
rus_verbs:откатываться{}, // откатываться на заранее подготовленные позиции
rus_verbs:усаживать{}, // усаживать на скамейку
rus_verbs:натаскать{}, // натаскать на поиск наркотиков
rus_verbs:зашикать{}, // зашикать на кошку
rus_verbs:разломать{}, // разломать на равные части
rus_verbs:приглашаться{}, // приглашаться на сцену
rus_verbs:присягать{}, // присягать на верность
rus_verbs:запрограммировать{}, // запрограммировать на постоянную уборку
rus_verbs:расщедриться{}, // расщедриться на новый компьютер
rus_verbs:насесть{}, // насесть на двоечников
rus_verbs:созывать{}, // созывать на собрание
rus_verbs:позариться{}, // позариться на чужое добро
rus_verbs:перекидываться{}, // перекидываться на соседние здания
rus_verbs:наползать{}, // наползать на неповрежденную ткань
rus_verbs:изрубить{}, // изрубить на мелкие кусочки
rus_verbs:наворачиваться{}, // наворачиваться на глаза
rus_verbs:раскричаться{}, // раскричаться на всю округу
rus_verbs:переползти{}, // переползти на светлую сторону
rus_verbs:уполномочить{}, // уполномочить на разведовательную операцию
rus_verbs:мочиться{}, // мочиться на трупы убитых врагов
rus_verbs:радировать{}, // радировать на базу
rus_verbs:промотать{}, // промотать на начало
rus_verbs:заснять{}, // заснять на видео
rus_verbs:подбивать{}, // подбивать на матч-реванш
rus_verbs:наплевать{}, // наплевать на справедливость
rus_verbs:подвывать{}, // подвывать на луну
rus_verbs:расплескать{}, // расплескать на пол
rus_verbs:польститься{}, // польститься на бесплатный сыр
rus_verbs:помчать{}, // помчать на работу
rus_verbs:съезжать{}, // съезжать на обочину
rus_verbs:нашептать{}, // нашептать кому-то на ухо
rus_verbs:наклеить{}, // наклеить на доску объявлений
rus_verbs:завозить{}, // завозить на склад
rus_verbs:заявляться{}, // заявляться на любимую работу
rus_verbs:наглядеться{}, // наглядеться на воробьев
rus_verbs:хлопнуться{}, // хлопнуться на живот
rus_verbs:забредать{}, // забредать на поляну
rus_verbs:посягать{}, // посягать на исконные права собственности
rus_verbs:сдвигать{}, // сдвигать на одну позицию
rus_verbs:спрыгивать{}, // спрыгивать на землю
rus_verbs:сдвигаться{}, // сдвигаться на две позиции
rus_verbs:разделать{}, // разделать на орехи
rus_verbs:разлагать{}, // разлагать на элементарные элементы
rus_verbs:обрушивать{}, // обрушивать на головы врагов
rus_verbs:натечь{}, // натечь на пол
rus_verbs:политься{}, // вода польется на землю
rus_verbs:успеть{}, // Они успеют на поезд.
инфинитив:мигрировать{ вид:несоверш }, глагол:мигрировать{ вид:несоверш },
деепричастие:мигрируя{},
инфинитив:мигрировать{ вид:соверш }, глагол:мигрировать{ вид:соверш },
деепричастие:мигрировав{},
rus_verbs:двинуться{}, // Мы скоро двинемся на дачу.
rus_verbs:подойти{}, // Он не подойдёт на должность секретаря.
rus_verbs:потянуть{}, // Он не потянет на директора.
rus_verbs:тянуть{}, // Он не тянет на директора.
rus_verbs:перескакивать{}, // перескакивать с одного примера на другой
rus_verbs:жаловаться{}, // Он жалуется на нездоровье.
rus_verbs:издать{}, // издать на деньги спонсоров
rus_verbs:показаться{}, // показаться на глаза
rus_verbs:высаживать{}, // высаживать на необитаемый остров
rus_verbs:вознестись{}, // вознестись на самую вершину славы
rus_verbs:залить{}, // залить на youtube
rus_verbs:закачать{}, // закачать на youtube
rus_verbs:сыграть{}, // сыграть на деньги
rus_verbs:экстраполировать{}, // Формулу можно экстраполировать на случай нескольких переменных
инфинитив:экстраполироваться{ вид:несоверш}, // Ситуация легко экстраполируется на случай нескольких переменных
глагол:экстраполироваться{ вид:несоверш},
инфинитив:экстраполироваться{ вид:соверш},
глагол:экстраполироваться{ вид:соверш},
деепричастие:экстраполируясь{},
инфинитив:акцентировать{вид:соверш}, // оратор акцентировал внимание слушателей на новый аспект проблемы
глагол:акцентировать{вид:соверш},
инфинитив:акцентировать{вид:несоверш},
глагол:акцентировать{вид:несоверш},
прилагательное:акцентировавший{вид:несоверш},
//прилагательное:акцентировавший{вид:соверш},
прилагательное:акцентирующий{},
деепричастие:акцентировав{},
деепричастие:акцентируя{},
rus_verbs:бабахаться{}, // он бабахался на пол
rus_verbs:бабахнуться{}, // мальчил бабахнулся на асфальт
rus_verbs:батрачить{}, // Крестьяне батрачили на хозяина
rus_verbs:бахаться{}, // Наездники бахались на землю
rus_verbs:бахнуться{}, // Наездник опять бахнулся на землю
rus_verbs:благословить{}, // батюшка благословил отрока на подвиг
rus_verbs:благословлять{}, // батюшка благословляет отрока на подвиг
rus_verbs:блевануть{}, // Он блеванул на землю
rus_verbs:блевать{}, // Он блюет на землю
rus_verbs:бухнуться{}, // Наездник бухнулся на землю
rus_verbs:валить{}, // Ветер валил деревья на землю
rus_verbs:спилить{}, // Спиленное дерево валится на землю
rus_verbs:ввезти{}, // Предприятие ввезло товар на таможню
rus_verbs:вдохновить{}, // Фильм вдохновил мальчика на поход в лес
rus_verbs:вдохновиться{}, // Мальчик вдохновился на поход
rus_verbs:вдохновлять{}, // Фильм вдохновляет на поход в лес
rus_verbs:вестись{}, // Не ведись на эти уловки!
rus_verbs:вешать{}, // Гости вешают одежду на вешалку
rus_verbs:вешаться{}, // Одежда вешается на вешалки
rus_verbs:вещать{}, // радиостанция вещает на всю страну
rus_verbs:взбираться{}, // Туристы взбираются на заросший лесом холм
rus_verbs:взбредать{}, // Что иногда взбредает на ум
rus_verbs:взбрести{}, // Что-то взбрело на ум
rus_verbs:взвалить{}, // Мама взвалила на свои плечи всё домашнее хозяйство
rus_verbs:взваливаться{}, // Все домашнее хозяйство взваливается на мамины плечи
rus_verbs:взваливать{}, // Не надо взваливать всё на мои плечи
rus_verbs:взглянуть{}, // Кошка взглянула на мышку
rus_verbs:взгромождать{}, // Мальчик взгромождает стул на стол
rus_verbs:взгромождаться{}, // Мальчик взгромождается на стол
rus_verbs:взгромоздить{}, // Мальчик взгромоздил стул на стол
rus_verbs:взгромоздиться{}, // Мальчик взгромоздился на стул
rus_verbs:взирать{}, // Очевидцы взирали на непонятный объект
rus_verbs:взлетать{}, // Фабрика фейерверков взлетает на воздух
rus_verbs:взлететь{}, // Фабрика фейерверков взлетела на воздух
rus_verbs:взобраться{}, // Туристы взобрались на гору
rus_verbs:взойти{}, // Туристы взошли на гору
rus_verbs:взъесться{}, // Отец взъелся на непутевого сына
rus_verbs:взъяриться{}, // Отец взъярился на непутевого сына
rus_verbs:вкатить{}, // рабочие вкатили бочку на пандус
rus_verbs:вкатывать{}, // рабочик вкатывают бочку на пандус
rus_verbs:влиять{}, // Это решение влияет на всех игроков рынка
rus_verbs:водворить{}, // водворить нарушителя на место
rus_verbs:водвориться{}, // водвориться на свое место
rus_verbs:водворять{}, // водворять вещь на свое место
rus_verbs:водворяться{}, // водворяться на свое место
rus_verbs:водружать{}, // водружать флаг на флагшток
rus_verbs:водружаться{}, // Флаг водружается на флагшток
rus_verbs:водрузить{}, // водрузить флаг на флагшток
rus_verbs:водрузиться{}, // Флаг водрузился на вершину горы
rus_verbs:воздействовать{}, // Излучение воздействует на кожу
rus_verbs:воззреть{}, // воззреть на поле боя
rus_verbs:воззриться{}, // воззриться на поле боя
rus_verbs:возить{}, // возить туристов на гору
rus_verbs:возлагать{}, // Многочисленные посетители возлагают цветы на могилу
rus_verbs:возлагаться{}, // Ответственность возлагается на начальство
rus_verbs:возлечь{}, // возлечь на лежанку
rus_verbs:возложить{}, // возложить цветы на могилу поэта
rus_verbs:вознести{}, // вознести кого-то на вершину славы
rus_verbs:возноситься{}, // возносится на вершину успеха
rus_verbs:возносить{}, // возносить счастливчика на вершину успеха
rus_verbs:подниматься{}, // Мы поднимаемся на восьмой этаж
rus_verbs:подняться{}, // Мы поднялись на восьмой этаж
rus_verbs:вонять{}, // Кусок сыра воняет на всю округу
rus_verbs:воодушевлять{}, // Идеалы воодушевляют на подвиги
rus_verbs:воодушевляться{}, // Люди воодушевляются на подвиги
rus_verbs:ворчать{}, // Старый пес ворчит на прохожих
rus_verbs:воспринимать{}, // воспринимать сообщение на слух
rus_verbs:восприниматься{}, // сообщение плохо воспринимается на слух
rus_verbs:воспринять{}, // воспринять сообщение на слух
rus_verbs:восприняться{}, // восприняться на слух
rus_verbs:воссесть{}, // Коля воссел на трон
rus_verbs:вправить{}, // вправить мозг на место
rus_verbs:вправлять{}, // вправлять мозги на место
rus_verbs:временить{}, // временить с выходом на пенсию
rus_verbs:врубать{}, // врубать на полную мощность
rus_verbs:врубить{}, // врубить на полную мощность
rus_verbs:врубиться{}, // врубиться на полную мощность
rus_verbs:врываться{}, // врываться на собрание
rus_verbs:вскарабкаться{}, // вскарабкаться на утёс
rus_verbs:вскарабкиваться{}, // вскарабкиваться на утёс
rus_verbs:вскочить{}, // вскочить на ноги
rus_verbs:всплывать{}, // всплывать на поверхность воды
rus_verbs:всплыть{}, // всплыть на поверхность воды
rus_verbs:вспрыгивать{}, // вспрыгивать на платформу
rus_verbs:вспрыгнуть{}, // вспрыгнуть на платформу
rus_verbs:встать{}, // встать на защиту чести и достоинства
rus_verbs:вторгаться{}, // вторгаться на чужую территорию
rus_verbs:вторгнуться{}, // вторгнуться на чужую территорию
rus_verbs:въезжать{}, // въезжать на пандус
rus_verbs:наябедничать{}, // наябедничать на соседа по парте
rus_verbs:выблевать{}, // выблевать завтрак на пол
rus_verbs:выблеваться{}, // выблеваться на пол
rus_verbs:выблевывать{}, // выблевывать завтрак на пол
rus_verbs:выблевываться{}, // выблевываться на пол
rus_verbs:вывезти{}, // вывезти мусор на свалку
rus_verbs:вывесить{}, // вывесить белье на просушку
rus_verbs:вывести{}, // вывести собаку на прогулку
rus_verbs:вывешивать{}, // вывешивать белье на веревку
rus_verbs:вывозить{}, // вывозить детей на природу
rus_verbs:вызывать{}, // Начальник вызывает на ковер
rus_verbs:выйти{}, // выйти на свободу
rus_verbs:выкладывать{}, // выкладывать на всеобщее обозрение
rus_verbs:выкладываться{}, // выкладываться на всеобщее обозрение
rus_verbs:выливать{}, // выливать на землю
rus_verbs:выливаться{}, // выливаться на землю
rus_verbs:вылить{}, // вылить жидкость на землю
rus_verbs:вылиться{}, // Топливо вылилось на землю
rus_verbs:выложить{}, // выложить на берег
rus_verbs:выменивать{}, // выменивать золото на хлеб
rus_verbs:вымениваться{}, // Золото выменивается на хлеб
rus_verbs:выменять{}, // выменять золото на хлеб
rus_verbs:выпадать{}, // снег выпадает на землю
rus_verbs:выплевывать{}, // выплевывать на землю
rus_verbs:выплевываться{}, // выплевываться на землю
rus_verbs:выплескать{}, // выплескать на землю
rus_verbs:выплескаться{}, // выплескаться на землю
rus_verbs:выплескивать{}, // выплескивать на землю
rus_verbs:выплескиваться{}, // выплескиваться на землю
rus_verbs:выплывать{}, // выплывать на поверхность
rus_verbs:выплыть{}, // выплыть на поверхность
rus_verbs:выплюнуть{}, // выплюнуть на пол
rus_verbs:выползать{}, // выползать на свежий воздух
rus_verbs:выпроситься{}, // выпроситься на улицу
rus_verbs:выпрыгивать{}, // выпрыгивать на свободу
rus_verbs:выпрыгнуть{}, // выпрыгнуть на перрон
rus_verbs:выпускать{}, // выпускать на свободу
rus_verbs:выпустить{}, // выпустить на свободу
rus_verbs:выпучивать{}, // выпучивать на кого-то глаза
rus_verbs:выпучиваться{}, // глаза выпучиваются на кого-то
rus_verbs:выпучить{}, // выпучить глаза на кого-то
rus_verbs:выпучиться{}, // выпучиться на кого-то
rus_verbs:выронить{}, // выронить на землю
rus_verbs:высадить{}, // высадить на берег
rus_verbs:высадиться{}, // высадиться на берег
rus_verbs:высаживаться{}, // высаживаться на остров
rus_verbs:выскальзывать{}, // выскальзывать на землю
rus_verbs:выскочить{}, // выскочить на сцену
rus_verbs:высморкаться{}, // высморкаться на землю
rus_verbs:высморкнуться{}, // высморкнуться на землю
rus_verbs:выставить{}, // выставить на всеобщее обозрение
rus_verbs:выставиться{}, // выставиться на всеобщее обозрение
rus_verbs:выставлять{}, // выставлять на всеобщее обозрение
rus_verbs:выставляться{}, // выставляться на всеобщее обозрение
инфинитив:высыпать{вид:соверш}, // высыпать на землю
инфинитив:высыпать{вид:несоверш},
глагол:высыпать{вид:соверш},
глагол:высыпать{вид:несоверш},
деепричастие:высыпав{},
деепричастие:высыпая{},
прилагательное:высыпавший{вид:соверш},
//++прилагательное:высыпавший{вид:несоверш},
прилагательное:высыпающий{вид:несоверш},
rus_verbs:высыпаться{}, // высыпаться на землю
rus_verbs:вытаращивать{}, // вытаращивать глаза на медведя
rus_verbs:вытаращиваться{}, // вытаращиваться на медведя
rus_verbs:вытаращить{}, // вытаращить глаза на медведя
rus_verbs:вытаращиться{}, // вытаращиться на медведя
rus_verbs:вытекать{}, // вытекать на землю
rus_verbs:вытечь{}, // вытечь на землю
rus_verbs:выучиваться{}, // выучиваться на кого-то
rus_verbs:выучиться{}, // выучиться на кого-то
rus_verbs:посмотреть{}, // посмотреть на экран
rus_verbs:нашить{}, // нашить что-то на одежду
rus_verbs:придти{}, // придти на помощь кому-то
инфинитив:прийти{}, // прийти на помощь кому-то
глагол:прийти{},
деепричастие:придя{}, // Придя на вокзал, он поспешно взял билеты.
rus_verbs:поднять{}, // поднять на вершину
rus_verbs:согласиться{}, // согласиться на ничью
rus_verbs:послать{}, // послать на фронт
rus_verbs:слать{}, // слать на фронт
rus_verbs:надеяться{}, // надеяться на лучшее
rus_verbs:крикнуть{}, // крикнуть на шалунов
rus_verbs:пройти{}, // пройти на пляж
rus_verbs:прислать{}, // прислать на экспертизу
rus_verbs:жить{}, // жить на подачки
rus_verbs:становиться{}, // становиться на ноги
rus_verbs:наслать{}, // наслать на кого-то
rus_verbs:принять{}, // принять на заметку
rus_verbs:собираться{}, // собираться на экзамен
rus_verbs:оставить{}, // оставить на всякий случай
rus_verbs:звать{}, // звать на помощь
rus_verbs:направиться{}, // направиться на прогулку
rus_verbs:отвечать{}, // отвечать на звонки
rus_verbs:отправиться{}, // отправиться на прогулку
rus_verbs:поставить{}, // поставить на пол
rus_verbs:обернуться{}, // обернуться на зов
rus_verbs:отозваться{}, // отозваться на просьбу
rus_verbs:закричать{}, // закричать на собаку
rus_verbs:опустить{}, // опустить на землю
rus_verbs:принести{}, // принести на пляж свой жезлонг
rus_verbs:указать{}, // указать на дверь
rus_verbs:ходить{}, // ходить на занятия
rus_verbs:уставиться{}, // уставиться на листок
rus_verbs:приходить{}, // приходить на экзамен
rus_verbs:махнуть{}, // махнуть на пляж
rus_verbs:явиться{}, // явиться на допрос
rus_verbs:оглянуться{}, // оглянуться на дорогу
rus_verbs:уехать{}, // уехать на заработки
rus_verbs:повести{}, // повести на штурм
rus_verbs:опуститься{}, // опуститься на колени
//rus_verbs:передать{}, // передать на проверку
rus_verbs:побежать{}, // побежать на занятия
rus_verbs:прибыть{}, // прибыть на место службы
rus_verbs:кричать{}, // кричать на медведя
rus_verbs:стечь{}, // стечь на землю
rus_verbs:обратить{}, // обратить на себя внимание
rus_verbs:подать{}, // подать на пропитание
rus_verbs:привести{}, // привести на съемки
rus_verbs:испытывать{}, // испытывать на животных
rus_verbs:перевести{}, // перевести на жену
rus_verbs:купить{}, // купить на заемные деньги
rus_verbs:собраться{}, // собраться на встречу
rus_verbs:заглянуть{}, // заглянуть на огонёк
rus_verbs:нажать{}, // нажать на рычаг
rus_verbs:поспешить{}, // поспешить на праздник
rus_verbs:перейти{}, // перейти на русский язык
rus_verbs:поверить{}, // поверить на честное слово
rus_verbs:глянуть{}, // глянуть на обложку
rus_verbs:зайти{}, // зайти на огонёк
rus_verbs:проходить{}, // проходить на сцену
rus_verbs:глядеть{}, // глядеть на актрису
//rus_verbs:решиться{}, // решиться на прыжок
rus_verbs:пригласить{}, // пригласить на танец
rus_verbs:позвать{}, // позвать на экзамен
rus_verbs:усесться{}, // усесться на стул
rus_verbs:поступить{}, // поступить на математический факультет
rus_verbs:лечь{}, // лечь на живот
rus_verbs:потянуться{}, // потянуться на юг
rus_verbs:присесть{}, // присесть на корточки
rus_verbs:наступить{}, // наступить на змею
rus_verbs:заорать{}, // заорать на попрошаек
rus_verbs:надеть{}, // надеть на голову
rus_verbs:поглядеть{}, // поглядеть на девчонок
rus_verbs:принимать{}, // принимать на гарантийное обслуживание
rus_verbs:привезти{}, // привезти на испытания
rus_verbs:рухнуть{}, // рухнуть на асфальт
rus_verbs:пускать{}, // пускать на корм
rus_verbs:отвести{}, // отвести на приём
rus_verbs:отправить{}, // отправить на утилизацию
rus_verbs:двигаться{}, // двигаться на восток
rus_verbs:нести{}, // нести на пляж
rus_verbs:падать{}, // падать на руки
rus_verbs:откинуться{}, // откинуться на спинку кресла
rus_verbs:рявкнуть{}, // рявкнуть на детей
rus_verbs:получать{}, // получать на проживание
rus_verbs:полезть{}, // полезть на рожон
rus_verbs:направить{}, // направить на дообследование
rus_verbs:приводить{}, // приводить на проверку
rus_verbs:потребоваться{}, // потребоваться на замену
rus_verbs:кинуться{}, // кинуться на нападавшего
rus_verbs:учиться{}, // учиться на токаря
rus_verbs:приподнять{}, // приподнять на один метр
rus_verbs:налить{}, // налить на стол
rus_verbs:играть{}, // играть на деньги
rus_verbs:рассчитывать{}, // рассчитывать на подмогу
rus_verbs:шепнуть{}, // шепнуть на ухо
rus_verbs:швырнуть{}, // швырнуть на землю
rus_verbs:прыгнуть{}, // прыгнуть на оленя
rus_verbs:предлагать{}, // предлагать на выбор
rus_verbs:садиться{}, // садиться на стул
rus_verbs:лить{}, // лить на землю
rus_verbs:испытать{}, // испытать на животных
rus_verbs:фыркнуть{}, // фыркнуть на детеныша
rus_verbs:годиться{}, // мясо годится на фарш
rus_verbs:проверить{}, // проверить высказывание на истинность
rus_verbs:откликнуться{}, // откликнуться на призывы
rus_verbs:полагаться{}, // полагаться на интуицию
rus_verbs:покоситься{}, // покоситься на соседа
rus_verbs:повесить{}, // повесить на гвоздь
инфинитив:походить{вид:соверш}, // походить на занятия
глагол:походить{вид:соверш},
деепричастие:походив{},
прилагательное:походивший{},
rus_verbs:помчаться{}, // помчаться на экзамен
rus_verbs:ставить{}, // ставить на контроль
rus_verbs:свалиться{}, // свалиться на землю
rus_verbs:валиться{}, // валиться на землю
rus_verbs:подарить{}, // подарить на день рожденья
rus_verbs:сбежать{}, // сбежать на необитаемый остров
rus_verbs:стрелять{}, // стрелять на поражение
rus_verbs:обращать{}, // обращать на себя внимание
rus_verbs:наступать{}, // наступать на те же грабли
rus_verbs:сбросить{}, // сбросить на землю
rus_verbs:обидеться{}, // обидеться на друга
rus_verbs:устроиться{}, // устроиться на стажировку
rus_verbs:погрузиться{}, // погрузиться на большую глубину
rus_verbs:течь{}, // течь на землю
rus_verbs:отбросить{}, // отбросить на землю
rus_verbs:метать{}, // метать на дно
rus_verbs:пустить{}, // пустить на переплавку
rus_verbs:прожить{}, // прожить на пособие
rus_verbs:полететь{}, // полететь на континент
rus_verbs:пропустить{}, // пропустить на сцену
rus_verbs:указывать{}, // указывать на ошибку
rus_verbs:наткнуться{}, // наткнуться на клад
rus_verbs:рвануть{}, // рвануть на юг
rus_verbs:ступать{}, // ступать на землю
rus_verbs:спрыгнуть{}, // спрыгнуть на берег
rus_verbs:заходить{}, // заходить на огонёк
rus_verbs:нырнуть{}, // нырнуть на глубину
rus_verbs:рвануться{}, // рвануться на свободу
rus_verbs:натянуть{}, // натянуть на голову
rus_verbs:забраться{}, // забраться на стол
rus_verbs:помахать{}, // помахать на прощание
rus_verbs:содержать{}, // содержать на спонсорскую помощь
rus_verbs:приезжать{}, // приезжать на праздники
rus_verbs:проникнуть{}, // проникнуть на территорию
rus_verbs:подъехать{}, // подъехать на митинг
rus_verbs:устремиться{}, // устремиться на волю
rus_verbs:посадить{}, // посадить на стул
rus_verbs:ринуться{}, // ринуться на голкипера
rus_verbs:подвигнуть{}, // подвигнуть на подвиг
rus_verbs:отдавать{}, // отдавать на перевоспитание
rus_verbs:отложить{}, // отложить на черный день
rus_verbs:убежать{}, // убежать на танцы
rus_verbs:поднимать{}, // поднимать на верхний этаж
rus_verbs:переходить{}, // переходить на цифровой сигнал
rus_verbs:отослать{}, // отослать на переаттестацию
rus_verbs:отодвинуть{}, // отодвинуть на другую половину стола
rus_verbs:назначить{}, // назначить на должность
rus_verbs:осесть{}, // осесть на дно
rus_verbs:торопиться{}, // торопиться на экзамен
rus_verbs:менять{}, // менять на еду
rus_verbs:доставить{}, // доставить на шестой этаж
rus_verbs:заслать{}, // заслать на проверку
rus_verbs:дуть{}, // дуть на воду
rus_verbs:сослать{}, // сослать на каторгу
rus_verbs:останавливаться{}, // останавливаться на отдых
rus_verbs:сдаваться{}, // сдаваться на милость победителя
rus_verbs:сослаться{}, // сослаться на презумпцию невиновности
rus_verbs:рассердиться{}, // рассердиться на дочь
rus_verbs:кинуть{}, // кинуть на землю
rus_verbs:расположиться{}, // расположиться на ночлег
rus_verbs:осмелиться{}, // осмелиться на подлог
rus_verbs:шептать{}, // шептать на ушко
rus_verbs:уронить{}, // уронить на землю
rus_verbs:откинуть{}, // откинуть на спинку кресла
rus_verbs:перенести{}, // перенести на рабочий стол
rus_verbs:сдаться{}, // сдаться на милость победителя
rus_verbs:светить{}, // светить на дорогу
rus_verbs:мчаться{}, // мчаться на бал
rus_verbs:нестись{}, // нестись на свидание
rus_verbs:поглядывать{}, // поглядывать на экран
rus_verbs:орать{}, // орать на детей
rus_verbs:уложить{}, // уложить на лопатки
rus_verbs:решаться{}, // решаться на поступок
rus_verbs:попадать{}, // попадать на карандаш
rus_verbs:сплюнуть{}, // сплюнуть на землю
rus_verbs:снимать{}, // снимать на телефон
rus_verbs:опоздать{}, // опоздать на работу
rus_verbs:посылать{}, // посылать на проверку
rus_verbs:погнать{}, // погнать на пастбище
rus_verbs:поступать{}, // поступать на кибернетический факультет
rus_verbs:спускаться{}, // спускаться на уровень моря
rus_verbs:усадить{}, // усадить на диван
rus_verbs:проиграть{}, // проиграть на спор
rus_verbs:прилететь{}, // прилететь на фестиваль
rus_verbs:повалиться{}, // повалиться на спину
rus_verbs:огрызнуться{}, // Собака огрызнулась на хозяина
rus_verbs:задавать{}, // задавать на выходные
rus_verbs:запасть{}, // запасть на девочку
rus_verbs:лезть{}, // лезть на забор
rus_verbs:потащить{}, // потащить на выборы
rus_verbs:направляться{}, // направляться на экзамен
rus_verbs:определять{}, // определять на вкус
rus_verbs:поползти{}, // поползти на стену
rus_verbs:поплыть{}, // поплыть на берег
rus_verbs:залезть{}, // залезть на яблоню
rus_verbs:сдать{}, // сдать на мясокомбинат
rus_verbs:приземлиться{}, // приземлиться на дорогу
rus_verbs:лаять{}, // лаять на прохожих
rus_verbs:перевернуть{}, // перевернуть на бок
rus_verbs:ловить{}, // ловить на живца
rus_verbs:отнести{}, // отнести животное на хирургический стол
rus_verbs:плюнуть{}, // плюнуть на условности
rus_verbs:передавать{}, // передавать на проверку
rus_verbs:нанять{}, // Босс нанял на работу еще несколько человек
rus_verbs:разозлиться{}, // Папа разозлился на сына из-за плохих оценок по математике
инфинитив:рассыпаться{вид:несоверш}, // рассыпаться на мелкие детали
инфинитив:рассыпаться{вид:соверш},
глагол:рассыпаться{вид:несоверш},
глагол:рассыпаться{вид:соверш},
деепричастие:рассыпавшись{},
деепричастие:рассыпаясь{},
прилагательное:рассыпавшийся{вид:несоверш},
прилагательное:рассыпавшийся{вид:соверш},
прилагательное:рассыпающийся{},
rus_verbs:зарычать{}, // Медведица зарычала на медвежонка
rus_verbs:призвать{}, // призвать на сборы
rus_verbs:увезти{}, // увезти на дачу
rus_verbs:содержаться{}, // содержаться на пожертвования
rus_verbs:навести{}, // навести на скопление телескоп
rus_verbs:отправляться{}, // отправляться на утилизацию
rus_verbs:улечься{}, // улечься на животик
rus_verbs:налететь{}, // налететь на препятствие
rus_verbs:перевернуться{}, // перевернуться на спину
rus_verbs:улететь{}, // улететь на родину
rus_verbs:ложиться{}, // ложиться на бок
rus_verbs:класть{}, // класть на место
rus_verbs:отреагировать{}, // отреагировать на выступление
rus_verbs:доставлять{}, // доставлять на дом
rus_verbs:отнять{}, // отнять на благо правящей верхушки
rus_verbs:ступить{}, // ступить на землю
rus_verbs:сводить{}, // сводить на концерт знаменитой рок-группы
rus_verbs:унести{}, // унести на работу
rus_verbs:сходить{}, // сходить на концерт
rus_verbs:потратить{}, // потратить на корм и наполнитель для туалета все деньги
rus_verbs:соскочить{}, // соскочить на землю
rus_verbs:пожаловаться{}, // пожаловаться на соседей
rus_verbs:тащить{}, // тащить на замену
rus_verbs:замахать{}, // замахать руками на паренька
rus_verbs:заглядывать{}, // заглядывать на обед
rus_verbs:соглашаться{}, // соглашаться на равный обмен
rus_verbs:плюхнуться{}, // плюхнуться на мягкий пуфик
rus_verbs:увести{}, // увести на осмотр
rus_verbs:успевать{}, // успевать на контрольную работу
rus_verbs:опрокинуть{}, // опрокинуть на себя
rus_verbs:подавать{}, // подавать на апелляцию
rus_verbs:прибежать{}, // прибежать на вокзал
rus_verbs:отшвырнуть{}, // отшвырнуть на замлю
rus_verbs:привлекать{}, // привлекать на свою сторону
rus_verbs:опереться{}, // опереться на палку
rus_verbs:перебраться{}, // перебраться на маленький островок
rus_verbs:уговорить{}, // уговорить на новые траты
rus_verbs:гулять{}, // гулять на спонсорские деньги
rus_verbs:переводить{}, // переводить на другой путь
rus_verbs:заколебаться{}, // заколебаться на один миг
rus_verbs:зашептать{}, // зашептать на ушко
rus_verbs:привстать{}, // привстать на цыпочки
rus_verbs:хлынуть{}, // хлынуть на берег
rus_verbs:наброситься{}, // наброситься на еду
rus_verbs:напасть{}, // повстанцы, напавшие на конвой
rus_verbs:убрать{}, // книга, убранная на полку
rus_verbs:попасть{}, // путешественники, попавшие на ничейную территорию
rus_verbs:засматриваться{}, // засматриваться на девчонок
rus_verbs:застегнуться{}, // застегнуться на все пуговицы
rus_verbs:провериться{}, // провериться на заболевания
rus_verbs:проверяться{}, // проверяться на заболевания
rus_verbs:тестировать{}, // тестировать на профпригодность
rus_verbs:протестировать{}, // протестировать на профпригодность
rus_verbs:уходить{}, // отец, уходящий на работу
rus_verbs:налипнуть{}, // снег, налипший на провода
rus_verbs:налипать{}, // снег, налипающий на провода
rus_verbs:улетать{}, // Многие птицы улетают осенью на юг.
rus_verbs:поехать{}, // она поехала на встречу с заказчиком
rus_verbs:переключать{}, // переключать на резервную линию
rus_verbs:переключаться{}, // переключаться на резервную линию
rus_verbs:подписаться{}, // подписаться на обновление
rus_verbs:нанести{}, // нанести на кожу
rus_verbs:нарываться{}, // нарываться на неприятности
rus_verbs:выводить{}, // выводить на орбиту
rus_verbs:вернуться{}, // вернуться на родину
rus_verbs:возвращаться{}, // возвращаться на родину
прилагательное:падкий{}, // Он падок на деньги.
прилагательное:обиженный{}, // Он обижен на отца.
rus_verbs:косить{}, // Он косит на оба глаза.
rus_verbs:закрыть{}, // Он забыл закрыть дверь на замок.
прилагательное:готовый{}, // Он готов на всякие жертвы.
rus_verbs:говорить{}, // Он говорит на скользкую тему.
прилагательное:глухой{}, // Он глух на одно ухо.
rus_verbs:взять{}, // Он взял ребёнка себе на колени.
rus_verbs:оказывать{}, // Лекарство не оказывало на него никакого действия.
rus_verbs:вести{}, // Лестница ведёт на третий этаж.
rus_verbs:уполномочивать{}, // уполномочивать на что-либо
глагол:спешить{ вид:несоверш }, // Я спешу на поезд.
rus_verbs:брать{}, // Я беру всю ответственность на себя.
rus_verbs:произвести{}, // Это произвело на меня глубокое впечатление.
rus_verbs:употребить{}, // Эти деньги можно употребить на ремонт фабрики.
rus_verbs:наводить{}, // Эта песня наводит на меня сон и скуку.
rus_verbs:разбираться{}, // Эта машина разбирается на части.
rus_verbs:оказать{}, // Эта книга оказала на меня большое влияние.
rus_verbs:разбить{}, // Учитель разбил учеников на несколько групп.
rus_verbs:отразиться{}, // Усиленная работа отразилась на его здоровье.
rus_verbs:перегрузить{}, // Уголь надо перегрузить на другое судно.
rus_verbs:делиться{}, // Тридцать делится на пять без остатка.
rus_verbs:удаляться{}, // Суд удаляется на совещание.
rus_verbs:показывать{}, // Стрелка компаса всегда показывает на север.
rus_verbs:сохранить{}, // Сохраните это на память обо мне.
rus_verbs:уезжать{}, // Сейчас все студенты уезжают на экскурсию.
rus_verbs:лететь{}, // Самолёт летит на север.
rus_verbs:бить{}, // Ружьё бьёт на пятьсот метров.
// rus_verbs:прийтись{}, // Пятое число пришлось на субботу.
rus_verbs:вынести{}, // Они вынесли из лодки на берег все вещи.
rus_verbs:смотреть{}, // Она смотрит на нас из окна.
rus_verbs:отдать{}, // Она отдала мне деньги на сохранение.
rus_verbs:налюбоваться{}, // Не могу налюбоваться на картину.
rus_verbs:любоваться{}, // гости любовались на картину
rus_verbs:попробовать{}, // Дайте мне попробовать на ощупь.
прилагательное:действительный{}, // Прививка оспы действительна только на три года.
rus_verbs:спуститься{}, // На город спустился смог
прилагательное:нечистый{}, // Он нечист на руку.
прилагательное:неспособный{}, // Он неспособен на такую низость.
прилагательное:злой{}, // кот очень зол на хозяина
rus_verbs:пойти{}, // Девочка не пошла на урок физультуры
rus_verbs:прибывать{}, // мой поезд прибывает на первый путь
rus_verbs:застегиваться{}, // пальто застегивается на двадцать одну пуговицу
rus_verbs:идти{}, // Дело идёт на лад.
rus_verbs:лазить{}, // Он лазил на чердак.
rus_verbs:поддаваться{}, // Он легко поддаётся на уговоры.
// rus_verbs:действовать{}, // действующий на нервы
rus_verbs:выходить{}, // Балкон выходит на площадь.
rus_verbs:работать{}, // Время работает на нас.
глагол:написать{aux stress="напис^ать"}, // Он написал музыку на слова Пушкина.
rus_verbs:бросить{}, // Они бросили все силы на строительство.
// глагол:разрезать{aux stress="разр^езать"}, глагол:разрезать{aux stress="разрез^ать"}, // Она разрезала пирог на шесть кусков.
rus_verbs:броситься{}, // Она радостно бросилась мне на шею.
rus_verbs:оправдать{}, // Она оправдала неявку на занятия болезнью.
rus_verbs:ответить{}, // Она не ответила на мой поклон.
rus_verbs:нашивать{}, // Она нашивала заплату на локоть.
rus_verbs:молиться{}, // Она молится на свою мать.
rus_verbs:запереть{}, // Она заперла дверь на замок.
rus_verbs:заявить{}, // Она заявила свои права на наследство.
rus_verbs:уйти{}, // Все деньги ушли на путешествие.
rus_verbs:вступить{}, // Водолаз вступил на берег.
rus_verbs:сойти{}, // Ночь сошла на землю.
rus_verbs:приехать{}, // Мы приехали на вокзал слишком рано.
rus_verbs:рыдать{}, // Не рыдай так безумно над ним.
rus_verbs:подписать{}, // Не забудьте подписать меня на газету.
rus_verbs:держать{}, // Наш пароход держал курс прямо на север.
rus_verbs:свезти{}, // На выставку свезли экспонаты со всего мира.
rus_verbs:ехать{}, // Мы сейчас едем на завод.
rus_verbs:выбросить{}, // Волнами лодку выбросило на берег.
ГЛ_ИНФ(сесть), // сесть на снег
ГЛ_ИНФ(записаться),
ГЛ_ИНФ(положить) // положи книгу на стол
}
#endregion VerbList
// Чтобы разрешить связывание в паттернах типа: залить на youtube
fact гл_предл
{
if context { Гл_НА_Вин предлог:на{} @regex("[a-z]+[0-9]*") }
then return true
}
fact гл_предл
{
if context { глагол:купить{} предлог:на{} 'деньги'{падеж:вин} }
then return true
}
fact гл_предл
{
if context { Гл_НА_Вин предлог:на{} *:*{ падеж:вин } }
then return true
}
// смещаться на несколько миллиметров
fact гл_предл
{
if context { Гл_НА_Вин предлог:на{} наречие:*{} }
then return true
}
// партия взяла на себя нереалистичные обязательства
fact гл_предл
{
if context { глагол:взять{} предлог:на{} 'себя'{падеж:вин} }
then return true
}
#endregion ВИНИТЕЛЬНЫЙ
// Все остальные варианты с предлогом 'НА' по умолчанию запрещаем.
fact гл_предл
{
if context { * предлог:на{} *:*{ падеж:предл } }
then return false,-3
}
fact гл_предл
{
if context { * предлог:на{} *:*{ падеж:мест } }
then return false,-3
}
fact гл_предл
{
if context { * предлог:на{} *:*{ падеж:вин } }
then return false,-4
}
// Этот вариант нужен для обработки конструкций с числительными:
// Президентские выборы разделили Венесуэлу на два непримиримых лагеря
fact гл_предл
{
if context { * предлог:на{} *:*{ падеж:род } }
then return false,-4
}
// Продавать на eBay
fact гл_предл
{
if context { * предлог:на{} * }
then return false,-6
}
#endregion Предлог_НА
#region Предлог_С
// ------------- ПРЕДЛОГ 'С' -----------------
// У этого предлога предпочтительная семантика привязывает его обычно к существительному.
// Поэтому запрещаем по умолчанию его привязку к глаголам, а разрешенные глаголы перечислим.
#region ТВОРИТЕЛЬНЫЙ
wordentry_set Гл_С_Твор={
rus_verbs:помогать{}, // будет готов помогать врачам в онкологическом центре с постановкой верных диагнозов
rus_verbs:перепихнуться{}, // неужели ты не хочешь со мной перепихнуться
rus_verbs:забраться{},
rus_verbs:ДРАТЬСЯ{}, // Мои же собственные ратники забросали бы меня гнилой капустой, и мне пришлось бы драться с каждым рыцарем в стране, чтобы доказать свою смелость. (ДРАТЬСЯ/БИТЬСЯ/ПОДРАТЬСЯ)
rus_verbs:БИТЬСЯ{}, //
rus_verbs:ПОДРАТЬСЯ{}, //
прилагательное:СХОЖИЙ{}, // Не был ли он схожим с одним из живых языков Земли (СХОЖИЙ)
rus_verbs:ВСТУПИТЬ{}, // Он намеревался вступить с Вольфом в ближний бой. (ВСТУПИТЬ)
rus_verbs:КОРРЕЛИРОВАТЬ{}, // Это коррелирует с традиционно сильными направлениями московской математической школы. (КОРРЕЛИРОВАТЬ)
rus_verbs:УВИДЕТЬСЯ{}, // Он проигнорирует истерические протесты жены и увидится сначала с доктором, а затем с психотерапевтом (УВИДЕТЬСЯ)
rus_verbs:ОЧНУТЬСЯ{}, // Когда он очнулся с болью в левой стороне черепа, у него возникло пугающее ощущение. (ОЧНУТЬСЯ)
прилагательное:сходный{}, // Мозг этих существ сходен по размерам с мозгом динозавра
rus_verbs:накрыться{}, // Было холодно, и он накрылся с головой одеялом.
rus_verbs:РАСПРЕДЕЛИТЬ{}, // Бюджет распределят с участием горожан (РАСПРЕДЕЛИТЬ)
rus_verbs:НАБРОСИТЬСЯ{}, // Пьяный водитель набросился с ножом на сотрудников ГИБДД (НАБРОСИТЬСЯ)
rus_verbs:БРОСИТЬСЯ{}, // она со смехом бросилась прочь (БРОСИТЬСЯ)
rus_verbs:КОНТАКТИРОВАТЬ{}, // Электронным магазинам стоит контактировать с клиентами (КОНТАКТИРОВАТЬ)
rus_verbs:ВИДЕТЬСЯ{}, // Тогда мы редко виделись друг с другом
rus_verbs:сесть{}, // сел в него с дорожной сумкой , наполненной наркотиками
rus_verbs:купить{}, // Мы купили с ним одну и ту же книгу
rus_verbs:ПРИМЕНЯТЬ{}, // Меры по стимулированию спроса в РФ следует применять с осторожностью (ПРИМЕНЯТЬ)
rus_verbs:УЙТИ{}, // ты мог бы уйти со мной (УЙТИ)
rus_verbs:ЖДАТЬ{}, // С нарастающим любопытством ждем результатов аудита золотых хранилищ европейских и американских центробанков (ЖДАТЬ)
rus_verbs:ГОСПИТАЛИЗИРОВАТЬ{}, // Мэра Твери, участвовавшего в спартакиаде, госпитализировали с инфарктом (ГОСПИТАЛИЗИРОВАТЬ)
rus_verbs:ЗАХЛОПНУТЬСЯ{}, // она захлопнулась со звоном (ЗАХЛОПНУТЬСЯ)
rus_verbs:ОТВЕРНУТЬСЯ{}, // она со вздохом отвернулась (ОТВЕРНУТЬСЯ)
rus_verbs:отправить{}, // вы можете отправить со мной человека
rus_verbs:выступать{}, // Градоначальник , выступая с обзором основных городских событий , поведал об этом депутатам
rus_verbs:ВЫЕЗЖАТЬ{}, // заключенные сами шьют куклы и иногда выезжают с представлениями в детский дом неподалеку (ВЫЕЗЖАТЬ С твор)
rus_verbs:ПОКОНЧИТЬ{}, // со всем этим покончено (ПОКОНЧИТЬ С)
rus_verbs:ПОБЕЖАТЬ{}, // Дмитрий побежал со всеми (ПОБЕЖАТЬ С)
прилагательное:несовместимый{}, // характер ранений был несовместим с жизнью (НЕСОВМЕСТИМЫЙ С)
rus_verbs:ПОСЕТИТЬ{}, // Его кабинет местные тележурналисты посетили со скрытой камерой (ПОСЕТИТЬ С)
rus_verbs:СЛОЖИТЬСЯ{}, // сами банки принимают меры по урегулированию сложившейся с вкладчиками ситуации (СЛОЖИТЬСЯ С)
rus_verbs:ЗАСТАТЬ{}, // Молодой человек убил пенсионера , застав его в постели с женой (ЗАСТАТЬ С)
rus_verbs:ОЗНАКАМЛИВАТЬСЯ{}, // при заполнении заявления владельцы судов ознакамливаются с режимом (ОЗНАКАМЛИВАТЬСЯ С)
rus_verbs:СООБРАЗОВЫВАТЬ{}, // И все свои задачи мы сообразовываем с этим пониманием (СООБРАЗОВЫВАТЬ С)
rus_verbs:СВЫКАТЬСЯ{},
rus_verbs:стаскиваться{},
rus_verbs:спиливаться{},
rus_verbs:КОНКУРИРОВАТЬ{}, // Бедные и менее развитые страны не могут конкурировать с этими субсидиями (КОНКУРИРОВАТЬ С)
rus_verbs:ВЫРВАТЬСЯ{}, // тот с трудом вырвался (ВЫРВАТЬСЯ С твор)
rus_verbs:СОБРАТЬСЯ{}, // нужно собраться с силами (СОБРАТЬСЯ С)
rus_verbs:УДАВАТЬСЯ{}, // удавалось это с трудом (УДАВАТЬСЯ С)
rus_verbs:РАСПАХНУТЬСЯ{}, // дверь с треском распахнулась (РАСПАХНУТЬСЯ С)
rus_verbs:НАБЛЮДАТЬ{}, // Олег наблюдал с любопытством (НАБЛЮДАТЬ С)
rus_verbs:ПОТЯНУТЬ{}, // затем с силой потянул (ПОТЯНУТЬ С)
rus_verbs:КИВНУТЬ{}, // Питер с трудом кивнул (КИВНУТЬ С)
rus_verbs:СГЛОТНУТЬ{}, // Борис с трудом сглотнул (СГЛОТНУТЬ С)
rus_verbs:ЗАБРАТЬ{}, // забрать его с собой (ЗАБРАТЬ С)
rus_verbs:ОТКРЫТЬСЯ{}, // дверь с шипением открылась (ОТКРЫТЬСЯ С)
rus_verbs:ОТОРВАТЬ{}, // с усилием оторвал взгляд (ОТОРВАТЬ С твор)
rus_verbs:ОГЛЯДЕТЬСЯ{}, // Рома с любопытством огляделся (ОГЛЯДЕТЬСЯ С)
rus_verbs:ФЫРКНУТЬ{}, // турок фыркнул с отвращением (ФЫРКНУТЬ С)
rus_verbs:согласиться{}, // с этим согласились все (согласиться с)
rus_verbs:ПОСЫПАТЬСЯ{}, // с грохотом посыпались камни (ПОСЫПАТЬСЯ С твор)
rus_verbs:ВЗДОХНУТЬ{}, // Алиса вздохнула с облегчением (ВЗДОХНУТЬ С)
rus_verbs:ОБЕРНУТЬСЯ{}, // та с удивлением обернулась (ОБЕРНУТЬСЯ С)
rus_verbs:ХМЫКНУТЬ{}, // Алексей хмыкнул с сомнением (ХМЫКНУТЬ С твор)
rus_verbs:ВЫЕХАТЬ{}, // они выехали с рассветом (ВЫЕХАТЬ С твор)
rus_verbs:ВЫДОХНУТЬ{}, // Владимир выдохнул с облегчением (ВЫДОХНУТЬ С)
rus_verbs:УХМЫЛЬНУТЬСЯ{}, // Кеша ухмыльнулся с сомнением (УХМЫЛЬНУТЬСЯ С)
rus_verbs:НЕСТИСЬ{}, // тот несся с криком (НЕСТИСЬ С твор)
rus_verbs:ПАДАТЬ{}, // падают с глухим стуком (ПАДАТЬ С твор)
rus_verbs:ТВОРИТЬСЯ{}, // странное творилось с глазами (ТВОРИТЬСЯ С твор)
rus_verbs:УХОДИТЬ{}, // с ними уходили эльфы (УХОДИТЬ С твор)
rus_verbs:СКАКАТЬ{}, // скакали тут с топорами (СКАКАТЬ С твор)
rus_verbs:ЕСТЬ{}, // здесь едят с зеленью (ЕСТЬ С твор)
rus_verbs:ПОЯВИТЬСЯ{}, // с рассветом появились птицы (ПОЯВИТЬСЯ С твор)
rus_verbs:ВСКОЧИТЬ{}, // Олег вскочил с готовностью (ВСКОЧИТЬ С твор)
rus_verbs:БЫТЬ{}, // хочу быть с тобой (БЫТЬ С твор)
rus_verbs:ПОКАЧАТЬ{}, // с сомнением покачал головой. (ПОКАЧАТЬ С СОМНЕНИЕМ)
rus_verbs:ВЫРУГАТЬСЯ{}, // капитан с чувством выругался (ВЫРУГАТЬСЯ С ЧУВСТВОМ)
rus_verbs:ОТКРЫТЬ{}, // с трудом открыл глаза (ОТКРЫТЬ С ТРУДОМ, таких много)
rus_verbs:ПОЛУЧИТЬСЯ{}, // забавно получилось с ним (ПОЛУЧИТЬСЯ С)
rus_verbs:ВЫБЕЖАТЬ{}, // старый выбежал с копьем (ВЫБЕЖАТЬ С)
rus_verbs:ГОТОВИТЬСЯ{}, // Большинство компотов готовится с использованием сахара (ГОТОВИТЬСЯ С)
rus_verbs:ПОДИСКУТИРОВАТЬ{}, // я бы подискутировал с Андрюхой (ПОДИСКУТИРОВАТЬ С)
rus_verbs:ТУСИТЬ{}, // кто тусил со Светкой (ТУСИТЬ С)
rus_verbs:БЕЖАТЬ{}, // куда она бежит со всеми? (БЕЖАТЬ С твор)
rus_verbs:ГОРЕТЬ{}, // ты горел со своим кораблем? (ГОРЕТЬ С)
rus_verbs:ВЫПИТЬ{}, // хотите выпить со мной чаю? (ВЫПИТЬ С)
rus_verbs:МЕНЯТЬСЯ{}, // Я меняюсь с товарищем книгами. (МЕНЯТЬСЯ С)
rus_verbs:ВАЛЯТЬСЯ{}, // Он уже неделю валяется с гриппом. (ВАЛЯТЬСЯ С)
rus_verbs:ПИТЬ{}, // вы даже будете пить со мной пиво. (ПИТЬ С)
инфинитив:кристаллизоваться{ вид:соверш }, // После этого пересыщенный раствор кристаллизуется с образованием кристаллов сахара.
инфинитив:кристаллизоваться{ вид:несоверш },
глагол:кристаллизоваться{ вид:соверш },
глагол:кристаллизоваться{ вид:несоверш },
rus_verbs:ПООБЩАТЬСЯ{}, // пообщайся с Борисом (ПООБЩАТЬСЯ С)
rus_verbs:ОБМЕНЯТЬСЯ{}, // Миша обменялся с Петей марками (ОБМЕНЯТЬСЯ С)
rus_verbs:ПРОХОДИТЬ{}, // мы с тобой сегодня весь день проходили с вещами. (ПРОХОДИТЬ С)
rus_verbs:ВСТАТЬ{}, // Он занимался всю ночь и встал с головной болью. (ВСТАТЬ С)
rus_verbs:ПОВРЕМЕНИТЬ{}, // МВФ рекомендует Ирландии повременить с мерами экономии (ПОВРЕМЕНИТЬ С)
rus_verbs:ГЛЯДЕТЬ{}, // Её глаза глядели с мягкой грустью. (ГЛЯДЕТЬ С + твор)
rus_verbs:ВЫСКОЧИТЬ{}, // Зачем ты выскочил со своим замечанием? (ВЫСКОЧИТЬ С)
rus_verbs:НЕСТИ{}, // плот несло со страшной силой. (НЕСТИ С)
rus_verbs:приближаться{}, // стена приближалась со страшной быстротой. (приближаться с)
rus_verbs:заниматься{}, // После уроков я занимался с отстающими учениками. (заниматься с)
rus_verbs:разработать{}, // Этот лекарственный препарат разработан с использованием рецептов традиционной китайской медицины. (разработать с)
rus_verbs:вестись{}, // Разработка месторождения ведется с использованием большого количества техники. (вестись с)
rus_verbs:конфликтовать{}, // Маша конфликтует с Петей (конфликтовать с)
rus_verbs:мешать{}, // мешать воду с мукой (мешать с)
rus_verbs:иметь{}, // мне уже приходилось несколько раз иметь с ним дело.
rus_verbs:синхронизировать{}, // синхронизировать с эталонным генератором
rus_verbs:засинхронизировать{}, // засинхронизировать с эталонным генератором
rus_verbs:синхронизироваться{}, // синхронизироваться с эталонным генератором
rus_verbs:засинхронизироваться{}, // засинхронизироваться с эталонным генератором
rus_verbs:стирать{}, // стирать с мылом рубашку в тазу
rus_verbs:прыгать{}, // парашютист прыгает с парашютом
rus_verbs:выступить{}, // Он выступил с приветствием съезду.
rus_verbs:ходить{}, // В чужой монастырь со своим уставом не ходят.
rus_verbs:отозваться{}, // Он отозвался об этой книге с большой похвалой.
rus_verbs:отзываться{}, // Он отзывается об этой книге с большой похвалой.
rus_verbs:вставать{}, // он встаёт с зарёй
rus_verbs:мирить{}, // Его ум мирил всех с его дурным характером.
rus_verbs:продолжаться{}, // стрельба тем временем продолжалась с прежней точностью.
rus_verbs:договориться{}, // мы договоримся с вами
rus_verbs:побыть{}, // он хотел побыть с тобой
rus_verbs:расти{}, // Мировые производственные мощности растут с беспрецедентной скоростью
rus_verbs:вязаться{}, // вязаться с фактами
rus_verbs:отнестись{}, // отнестись к животным с сочуствием
rus_verbs:относиться{}, // относиться с пониманием
rus_verbs:пойти{}, // Спектакль пойдёт с участием известных артистов.
rus_verbs:бракосочетаться{}, // Потомственный кузнец бракосочетался с разорившейся графиней
rus_verbs:гулять{}, // бабушка гуляет с внуком
rus_verbs:разбираться{}, // разбираться с задачей
rus_verbs:сверить{}, // Данные были сверены с эталонными значениями
rus_verbs:делать{}, // Что делать со старым телефоном
rus_verbs:осматривать{}, // осматривать с удивлением
rus_verbs:обсудить{}, // обсудить с приятелем прохождение уровня в новой игре
rus_verbs:попрощаться{}, // попрощаться с талантливым актером
rus_verbs:задремать{}, // задремать с кружкой чая в руке
rus_verbs:связать{}, // связать катастрофу с действиями конкурентов
rus_verbs:носиться{}, // носиться с безумной идеей
rus_verbs:кончать{}, // кончать с собой
rus_verbs:обмениваться{}, // обмениваться с собеседниками
rus_verbs:переговариваться{}, // переговариваться с маяком
rus_verbs:общаться{}, // общаться с полицией
rus_verbs:завершить{}, // завершить с ошибкой
rus_verbs:обняться{}, // обняться с подругой
rus_verbs:сливаться{}, // сливаться с фоном
rus_verbs:смешаться{}, // смешаться с толпой
rus_verbs:договариваться{}, // договариваться с потерпевшим
rus_verbs:обедать{}, // обедать с гостями
rus_verbs:сообщаться{}, // сообщаться с подземной рекой
rus_verbs:сталкиваться{}, // сталкиваться со стаей птиц
rus_verbs:читаться{}, // читаться с трудом
rus_verbs:смириться{}, // смириться с утратой
rus_verbs:разделить{}, // разделить с другими ответственность
rus_verbs:роднить{}, // роднить с медведем
rus_verbs:медлить{}, // медлить с ответом
rus_verbs:скрестить{}, // скрестить с ужом
rus_verbs:покоиться{}, // покоиться с миром
rus_verbs:делиться{}, // делиться с друзьями
rus_verbs:познакомить{}, // познакомить с Олей
rus_verbs:порвать{}, // порвать с Олей
rus_verbs:завязать{}, // завязать с Олей знакомство
rus_verbs:суетиться{}, // суетиться с изданием романа
rus_verbs:соединиться{}, // соединиться с сервером
rus_verbs:справляться{}, // справляться с нуждой
rus_verbs:замешкаться{}, // замешкаться с ответом
rus_verbs:поссориться{}, // поссориться с подругой
rus_verbs:ссориться{}, // ссориться с друзьями
rus_verbs:торопить{}, // торопить с решением
rus_verbs:поздравить{}, // поздравить с победой
rus_verbs:проститься{}, // проститься с человеком
rus_verbs:поработать{}, // поработать с деревом
rus_verbs:приключиться{}, // приключиться с Колей
rus_verbs:сговориться{}, // сговориться с Ваней
rus_verbs:отъехать{}, // отъехать с ревом
rus_verbs:объединять{}, // объединять с другой кампанией
rus_verbs:употребить{}, // употребить с молоком
rus_verbs:перепутать{}, // перепутать с другой книгой
rus_verbs:запоздать{}, // запоздать с ответом
rus_verbs:подружиться{}, // подружиться с другими детьми
rus_verbs:дружить{}, // дружить с Сережей
rus_verbs:поравняться{}, // поравняться с финишной чертой
rus_verbs:ужинать{}, // ужинать с гостями
rus_verbs:расставаться{}, // расставаться с приятелями
rus_verbs:завтракать{}, // завтракать с семьей
rus_verbs:объединиться{}, // объединиться с соседями
rus_verbs:сменяться{}, // сменяться с напарником
rus_verbs:соединить{}, // соединить с сетью
rus_verbs:разговориться{}, // разговориться с охранником
rus_verbs:преподнести{}, // преподнести с помпой
rus_verbs:напечатать{}, // напечатать с картинками
rus_verbs:соединять{}, // соединять с сетью
rus_verbs:расправиться{}, // расправиться с беззащитным человеком
rus_verbs:распрощаться{}, // распрощаться с деньгами
rus_verbs:сравнить{}, // сравнить с конкурентами
rus_verbs:ознакомиться{}, // ознакомиться с выступлением
инфинитив:сочетаться{ вид:несоверш }, глагол:сочетаться{ вид:несоверш }, // сочетаться с сумочкой
деепричастие:сочетаясь{}, прилагательное:сочетающийся{}, прилагательное:сочетавшийся{},
rus_verbs:изнасиловать{}, // изнасиловать с применением чрезвычайного насилия
rus_verbs:прощаться{}, // прощаться с боевым товарищем
rus_verbs:сравнивать{}, // сравнивать с конкурентами
rus_verbs:складывать{}, // складывать с весом упаковки
rus_verbs:повестись{}, // повестись с ворами
rus_verbs:столкнуть{}, // столкнуть с отбойником
rus_verbs:переглядываться{}, // переглядываться с соседом
rus_verbs:поторопить{}, // поторопить с откликом
rus_verbs:развлекаться{}, // развлекаться с подружками
rus_verbs:заговаривать{}, // заговаривать с незнакомцами
rus_verbs:поцеловаться{}, // поцеловаться с первой девушкой
инфинитив:согласоваться{ вид:несоверш }, глагол:согласоваться{ вид:несоверш }, // согласоваться с подлежащим
деепричастие:согласуясь{}, прилагательное:согласующийся{},
rus_verbs:совпасть{}, // совпасть с оригиналом
rus_verbs:соединяться{}, // соединяться с куратором
rus_verbs:повстречаться{}, // повстречаться с героями
rus_verbs:поужинать{}, // поужинать с родителями
rus_verbs:развестись{}, // развестись с первым мужем
rus_verbs:переговорить{}, // переговорить с коллегами
rus_verbs:сцепиться{}, // сцепиться с бродячей собакой
rus_verbs:сожрать{}, // сожрать с потрохами
rus_verbs:побеседовать{}, // побеседовать со шпаной
rus_verbs:поиграть{}, // поиграть с котятами
rus_verbs:сцепить{}, // сцепить с тягачом
rus_verbs:помириться{}, // помириться с подружкой
rus_verbs:связываться{}, // связываться с бандитами
rus_verbs:совещаться{}, // совещаться с мастерами
rus_verbs:обрушиваться{}, // обрушиваться с беспощадной критикой
rus_verbs:переплестись{}, // переплестись с кустами
rus_verbs:мутить{}, // мутить с одногрупницами
rus_verbs:приглядываться{}, // приглядываться с интересом
rus_verbs:сблизиться{}, // сблизиться с врагами
rus_verbs:перешептываться{}, // перешептываться с симпатичной соседкой
rus_verbs:растереть{}, // растереть с солью
rus_verbs:смешиваться{}, // смешиваться с известью
rus_verbs:соприкоснуться{}, // соприкоснуться с тайной
rus_verbs:ладить{}, // ладить с родственниками
rus_verbs:сотрудничать{}, // сотрудничать с органами дознания
rus_verbs:съехаться{}, // съехаться с родственниками
rus_verbs:перекинуться{}, // перекинуться с коллегами парой слов
rus_verbs:советоваться{}, // советоваться с отчимом
rus_verbs:сравниться{}, // сравниться с лучшими
rus_verbs:знакомиться{}, // знакомиться с абитуриентами
rus_verbs:нырять{}, // нырять с аквалангом
rus_verbs:забавляться{}, // забавляться с куклой
rus_verbs:перекликаться{}, // перекликаться с другой статьей
rus_verbs:тренироваться{}, // тренироваться с партнершей
rus_verbs:поспорить{}, // поспорить с казночеем
инфинитив:сладить{ вид:соверш }, глагол:сладить{ вид:соверш }, // сладить с бычком
деепричастие:сладив{}, прилагательное:сладивший{ вид:соверш },
rus_verbs:примириться{}, // примириться с утратой
rus_verbs:раскланяться{}, // раскланяться с фрейлинами
rus_verbs:слечь{}, // слечь с ангиной
rus_verbs:соприкасаться{}, // соприкасаться со стеной
rus_verbs:смешать{}, // смешать с грязью
rus_verbs:пересекаться{}, // пересекаться с трассой
rus_verbs:путать{}, // путать с государственной шерстью
rus_verbs:поболтать{}, // поболтать с ученицами
rus_verbs:здороваться{}, // здороваться с профессором
rus_verbs:просчитаться{}, // просчитаться с покупкой
rus_verbs:сторожить{}, // сторожить с собакой
rus_verbs:обыскивать{}, // обыскивать с собаками
rus_verbs:переплетаться{}, // переплетаться с другой веткой
rus_verbs:обниматься{}, // обниматься с Ксюшей
rus_verbs:объединяться{}, // объединяться с конкурентами
rus_verbs:погорячиться{}, // погорячиться с покупкой
rus_verbs:мыться{}, // мыться с мылом
rus_verbs:свериться{}, // свериться с эталоном
rus_verbs:разделаться{}, // разделаться с кем-то
rus_verbs:чередоваться{}, // чередоваться с партнером
rus_verbs:налететь{}, // налететь с соратниками
rus_verbs:поспать{}, // поспать с включенным светом
rus_verbs:управиться{}, // управиться с собакой
rus_verbs:согрешить{}, // согрешить с замужней
rus_verbs:определиться{}, // определиться с победителем
rus_verbs:перемешаться{}, // перемешаться с гранулами
rus_verbs:затрудняться{}, // затрудняться с ответом
rus_verbs:обождать{}, // обождать со стартом
rus_verbs:фыркать{}, // фыркать с презрением
rus_verbs:засидеться{}, // засидеться с приятелем
rus_verbs:крепнуть{}, // крепнуть с годами
rus_verbs:пировать{}, // пировать с дружиной
rus_verbs:щебетать{}, // щебетать с сестричками
rus_verbs:маяться{}, // маяться с кашлем
rus_verbs:сближать{}, // сближать с центральным светилом
rus_verbs:меркнуть{}, // меркнуть с возрастом
rus_verbs:заспорить{}, // заспорить с оппонентами
rus_verbs:граничить{}, // граничить с Ливаном
rus_verbs:перестараться{}, // перестараться со стимуляторами
rus_verbs:объединить{}, // объединить с филиалом
rus_verbs:свыкнуться{}, // свыкнуться с утратой
rus_verbs:посоветоваться{}, // посоветоваться с адвокатами
rus_verbs:напутать{}, // напутать с ведомостями
rus_verbs:нагрянуть{}, // нагрянуть с обыском
rus_verbs:посовещаться{}, // посовещаться с судьей
rus_verbs:провернуть{}, // провернуть с друганом
rus_verbs:разделяться{}, // разделяться с сотрапезниками
rus_verbs:пересечься{}, // пересечься с второй колонной
rus_verbs:опережать{}, // опережать с большим запасом
rus_verbs:перепутаться{}, // перепутаться с другой линией
rus_verbs:соотноситься{}, // соотноситься с затратами
rus_verbs:смешивать{}, // смешивать с золой
rus_verbs:свидеться{}, // свидеться с тобой
rus_verbs:переспать{}, // переспать с графиней
rus_verbs:поладить{}, // поладить с соседями
rus_verbs:протащить{}, // протащить с собой
rus_verbs:разминуться{}, // разминуться с встречным потоком
rus_verbs:перемежаться{}, // перемежаться с успехами
rus_verbs:рассчитаться{}, // рассчитаться с кредиторами
rus_verbs:срастись{}, // срастись с телом
rus_verbs:знакомить{}, // знакомить с родителями
rus_verbs:поругаться{}, // поругаться с родителями
rus_verbs:совладать{}, // совладать с чувствами
rus_verbs:обручить{}, // обручить с богатой невестой
rus_verbs:сближаться{}, // сближаться с вражеским эсминцем
rus_verbs:замутить{}, // замутить с Ксюшей
rus_verbs:повозиться{}, // повозиться с настройкой
rus_verbs:торговаться{}, // торговаться с продавцами
rus_verbs:уединиться{}, // уединиться с девчонкой
rus_verbs:переборщить{}, // переборщить с добавкой
rus_verbs:ознакомить{}, // ознакомить с пожеланиями
rus_verbs:прочесывать{}, // прочесывать с собаками
rus_verbs:переписываться{}, // переписываться с корреспондентами
rus_verbs:повздорить{}, // повздорить с сержантом
rus_verbs:разлучить{}, // разлучить с семьей
rus_verbs:соседствовать{}, // соседствовать с цыганами
rus_verbs:застукать{}, // застукать с проститутками
rus_verbs:напуститься{}, // напуститься с кулаками
rus_verbs:сдружиться{}, // сдружиться с ребятами
rus_verbs:соперничать{}, // соперничать с параллельным классом
rus_verbs:прочесать{}, // прочесать с собаками
rus_verbs:кокетничать{}, // кокетничать с гимназистками
rus_verbs:мириться{}, // мириться с убытками
rus_verbs:оплошать{}, // оплошать с билетами
rus_verbs:отождествлять{}, // отождествлять с литературным героем
rus_verbs:хитрить{}, // хитрить с зарплатой
rus_verbs:провозиться{}, // провозиться с задачкой
rus_verbs:коротать{}, // коротать с друзьями
rus_verbs:соревноваться{}, // соревноваться с машиной
rus_verbs:уживаться{}, // уживаться с местными жителями
rus_verbs:отождествляться{}, // отождествляться с литературным героем
rus_verbs:сопоставить{}, // сопоставить с эталоном
rus_verbs:пьянствовать{}, // пьянствовать с друзьями
rus_verbs:залетать{}, // залетать с паленой водкой
rus_verbs:гастролировать{}, // гастролировать с новой цирковой программой
rus_verbs:запаздывать{}, // запаздывать с кормлением
rus_verbs:таскаться{}, // таскаться с сумками
rus_verbs:контрастировать{}, // контрастировать с туфлями
rus_verbs:сшибиться{}, // сшибиться с форвардом
rus_verbs:состязаться{}, // состязаться с лучшей командой
rus_verbs:затрудниться{}, // затрудниться с объяснением
rus_verbs:объясниться{}, // объясниться с пострадавшими
rus_verbs:разводиться{}, // разводиться со сварливой женой
rus_verbs:препираться{}, // препираться с адвокатами
rus_verbs:сосуществовать{}, // сосуществовать с крупными хищниками
rus_verbs:свестись{}, // свестись с нулевым счетом
rus_verbs:обговорить{}, // обговорить с директором
rus_verbs:обвенчаться{}, // обвенчаться с ведьмой
rus_verbs:экспериментировать{}, // экспериментировать с генами
rus_verbs:сверять{}, // сверять с таблицей
rus_verbs:сверяться{}, // свериться с таблицей
rus_verbs:сблизить{}, // сблизить с точкой
rus_verbs:гармонировать{}, // гармонировать с обоями
rus_verbs:перемешивать{}, // перемешивать с молоком
rus_verbs:трепаться{}, // трепаться с сослуживцами
rus_verbs:перемигиваться{}, // перемигиваться с соседкой
rus_verbs:разоткровенничаться{}, // разоткровенничаться с незнакомцем
rus_verbs:распить{}, // распить с собутыльниками
rus_verbs:скрестись{}, // скрестись с дикой лошадью
rus_verbs:передраться{}, // передраться с дворовыми собаками
rus_verbs:умыть{}, // умыть с мылом
rus_verbs:грызться{}, // грызться с соседями
rus_verbs:переругиваться{}, // переругиваться с соседями
rus_verbs:доиграться{}, // доиграться со спичками
rus_verbs:заладиться{}, // заладиться с подругой
rus_verbs:скрещиваться{}, // скрещиваться с дикими видами
rus_verbs:повидаться{}, // повидаться с дедушкой
rus_verbs:повоевать{}, // повоевать с орками
rus_verbs:сразиться{}, // сразиться с лучшим рыцарем
rus_verbs:кипятить{}, // кипятить с отбеливателем
rus_verbs:усердствовать{}, // усердствовать с наказанием
rus_verbs:схлестнуться{}, // схлестнуться с лучшим боксером
rus_verbs:пошептаться{}, // пошептаться с судьями
rus_verbs:сравняться{}, // сравняться с лучшими экземплярами
rus_verbs:церемониться{}, // церемониться с пьяницами
rus_verbs:консультироваться{}, // консультироваться со специалистами
rus_verbs:переусердствовать{}, // переусердствовать с наказанием
rus_verbs:проноситься{}, // проноситься с собой
rus_verbs:перемешать{}, // перемешать с гипсом
rus_verbs:темнить{}, // темнить с долгами
rus_verbs:сталкивать{}, // сталкивать с черной дырой
rus_verbs:увольнять{}, // увольнять с волчьим билетом
rus_verbs:заигрывать{}, // заигрывать с совершенно диким животным
rus_verbs:сопоставлять{}, // сопоставлять с эталонными образцами
rus_verbs:расторгнуть{}, // расторгнуть с нерасторопными поставщиками долгосрочный контракт
rus_verbs:созвониться{}, // созвониться с мамой
rus_verbs:спеться{}, // спеться с отъявленными хулиганами
rus_verbs:интриговать{}, // интриговать с придворными
rus_verbs:приобрести{}, // приобрести со скидкой
rus_verbs:задержаться{}, // задержаться со сдачей работы
rus_verbs:плавать{}, // плавать со спасательным кругом
rus_verbs:якшаться{}, // Не якшайся с врагами
инфинитив:ассоциировать{вид:соверш}, // читатели ассоциируют с собой героя книги
инфинитив:ассоциировать{вид:несоверш},
глагол:ассоциировать{вид:соверш}, // читатели ассоциируют с собой героя книги
глагол:ассоциировать{вид:несоверш},
//+прилагательное:ассоциировавший{вид:несоверш},
прилагательное:ассоциировавший{вид:соверш},
прилагательное:ассоциирующий{},
деепричастие:ассоциируя{},
деепричастие:ассоциировав{},
rus_verbs:ассоциироваться{}, // герой книги ассоциируется с реальным персонажем
rus_verbs:аттестовывать{}, // Они аттестовывают сотрудников с помощью наборра тестов
rus_verbs:аттестовываться{}, // Сотрудники аттестовываются с помощью набора тестов
//+инфинитив:аффилировать{вид:соверш}, // эти предприятия были аффилированы с олигархом
//+глагол:аффилировать{вид:соверш},
прилагательное:аффилированный{},
rus_verbs:баловаться{}, // мальчик баловался с молотком
rus_verbs:балясничать{}, // женщина балясничала с товарками
rus_verbs:богатеть{}, // Провинция богатеет от торговли с соседями
rus_verbs:бодаться{}, // теленок бодается с деревом
rus_verbs:боксировать{}, // Майкл дважды боксировал с ним
rus_verbs:брататься{}, // Солдаты братались с бойцами союзников
rus_verbs:вальсировать{}, // Мальчик вальсирует с девочкой
rus_verbs:вверстывать{}, // Дизайнер с трудом вверстывает блоки в страницу
rus_verbs:происходить{}, // Что происходит с мировой экономикой?
rus_verbs:произойти{}, // Что произошло с экономикой?
rus_verbs:взаимодействовать{}, // Электроны взаимодействуют с фотонами
rus_verbs:вздорить{}, // Эта женщина часто вздорила с соседями
rus_verbs:сойтись{}, // Мальчик сошелся с бандой хулиганов
rus_verbs:вобрать{}, // вобрать в себя лучшие методы борьбы с вредителями
rus_verbs:водиться{}, // Няня водится с детьми
rus_verbs:воевать{}, // Фермеры воевали с волками
rus_verbs:возиться{}, // Няня возится с детьми
rus_verbs:ворковать{}, // Голубь воркует с голубкой
rus_verbs:воссоединиться{}, // Дети воссоединились с семьей
rus_verbs:воссоединяться{}, // Дети воссоединяются с семьей
rus_verbs:вошкаться{}, // Не вошкайся с этой ерундой
rus_verbs:враждовать{}, // враждовать с соседями
rus_verbs:временить{}, // временить с выходом на пенсию
rus_verbs:расстаться{}, // я не могу расстаться с тобой
rus_verbs:выдирать{}, // выдирать с мясом
rus_verbs:выдираться{}, // выдираться с мясом
rus_verbs:вытворить{}, // вытворить что-либо с чем-либо
rus_verbs:вытворять{}, // вытворять что-либо с чем-либо
rus_verbs:сделать{}, // сделать с чем-то
rus_verbs:домыть{}, // домыть с мылом
rus_verbs:случиться{}, // случиться с кем-то
rus_verbs:остаться{}, // остаться с кем-то
rus_verbs:случать{}, // случать с породистым кобельком
rus_verbs:послать{}, // послать с весточкой
rus_verbs:работать{}, // работать с роботами
rus_verbs:провести{}, // провести с девчонками время
rus_verbs:заговорить{}, // заговорить с незнакомкой
rus_verbs:прошептать{}, // прошептать с придыханием
rus_verbs:читать{}, // читать с выражением
rus_verbs:слушать{}, // слушать с повышенным вниманием
rus_verbs:принести{}, // принести с собой
rus_verbs:спать{}, // спать с женщинами
rus_verbs:закончить{}, // закончить с приготовлениями
rus_verbs:помочь{}, // помочь с перестановкой
rus_verbs:уехать{}, // уехать с семьей
rus_verbs:случаться{}, // случаться с кем-то
rus_verbs:кутить{}, // кутить с проститутками
rus_verbs:разговаривать{}, // разговаривать с ребенком
rus_verbs:погодить{}, // погодить с ликвидацией
rus_verbs:считаться{}, // считаться с чужим мнением
rus_verbs:носить{}, // носить с собой
rus_verbs:хорошеть{}, // хорошеть с каждым днем
rus_verbs:приводить{}, // приводить с собой
rus_verbs:прыгнуть{}, // прыгнуть с парашютом
rus_verbs:петь{}, // петь с чувством
rus_verbs:сложить{}, // сложить с результатом
rus_verbs:познакомиться{}, // познакомиться с другими студентами
rus_verbs:обращаться{}, // обращаться с животными
rus_verbs:съесть{}, // съесть с хлебом
rus_verbs:ошибаться{}, // ошибаться с дозировкой
rus_verbs:столкнуться{}, // столкнуться с медведем
rus_verbs:справиться{}, // справиться с нуждой
rus_verbs:торопиться{}, // торопиться с ответом
rus_verbs:поздравлять{}, // поздравлять с победой
rus_verbs:объясняться{}, // объясняться с начальством
rus_verbs:пошутить{}, // пошутить с подругой
rus_verbs:поздороваться{}, // поздороваться с коллегами
rus_verbs:поступать{}, // Как поступать с таким поведением?
rus_verbs:определяться{}, // определяться с кандидатами
rus_verbs:связаться{}, // связаться с поставщиком
rus_verbs:спорить{}, // спорить с собеседником
rus_verbs:разобраться{}, // разобраться с делами
rus_verbs:ловить{}, // ловить с удочкой
rus_verbs:помедлить{}, // Кандидат помедлил с ответом на заданный вопрос
rus_verbs:шутить{}, // шутить с диким зверем
rus_verbs:разорвать{}, // разорвать с поставщиком контракт
rus_verbs:увезти{}, // увезти с собой
rus_verbs:унести{}, // унести с собой
rus_verbs:сотворить{}, // сотворить с собой что-то нехорошее
rus_verbs:складываться{}, // складываться с первым импульсом
rus_verbs:соглашаться{}, // соглашаться с предложенным договором
//rus_verbs:покончить{}, // покончить с развратом
rus_verbs:прихватить{}, // прихватить с собой
rus_verbs:похоронить{}, // похоронить с почестями
rus_verbs:связывать{}, // связывать с компанией свою судьбу
rus_verbs:совпадать{}, // совпадать с предсказанием
rus_verbs:танцевать{}, // танцевать с девушками
rus_verbs:поделиться{}, // поделиться с выжившими
rus_verbs:оставаться{}, // я не хотел оставаться с ним в одной комнате.
rus_verbs:беседовать{}, // преподаватель, беседующий со студентами
rus_verbs:бороться{}, // человек, борющийся со смертельной болезнью
rus_verbs:шептаться{}, // девочка, шепчущаяся с подругой
rus_verbs:сплетничать{}, // женщина, сплетничавшая с товарками
rus_verbs:поговорить{}, // поговорить с виновниками
rus_verbs:сказать{}, // сказать с трудом
rus_verbs:произнести{}, // произнести с трудом
rus_verbs:говорить{}, // говорить с акцентом
rus_verbs:произносить{}, // произносить с трудом
rus_verbs:встречаться{}, // кто с Антонио встречался?
rus_verbs:посидеть{}, // посидеть с друзьями
rus_verbs:расквитаться{}, // расквитаться с обидчиком
rus_verbs:поквитаться{}, // поквитаться с обидчиком
rus_verbs:ругаться{}, // ругаться с женой
rus_verbs:поскандалить{}, // поскандалить с женой
rus_verbs:потанцевать{}, // потанцевать с подругой
rus_verbs:скандалить{}, // скандалить с соседями
rus_verbs:разругаться{}, // разругаться с другом
rus_verbs:болтать{}, // болтать с подругами
rus_verbs:потрепаться{}, // потрепаться с соседкой
rus_verbs:войти{}, // войти с регистрацией
rus_verbs:входить{}, // входить с регистрацией
rus_verbs:возвращаться{}, // возвращаться с триумфом
rus_verbs:опоздать{}, // Он опоздал с подачей сочинения.
rus_verbs:молчать{}, // Он молчал с ледяным спокойствием.
rus_verbs:сражаться{}, // Он героически сражался с врагами.
rus_verbs:выходить{}, // Он всегда выходит с зонтиком.
rus_verbs:сличать{}, // сличать перевод с оригиналом
rus_verbs:начать{}, // я начал с товарищем спор о религии
rus_verbs:согласовать{}, // Маша согласовала с Петей дальнейшие поездки
rus_verbs:приходить{}, // Приходите с нею.
rus_verbs:жить{}, // кто с тобой жил?
rus_verbs:расходиться{}, // Маша расходится с Петей
rus_verbs:сцеплять{}, // сцеплять карабин с обвязкой
rus_verbs:торговать{}, // мы торгуем с ними нефтью
rus_verbs:уединяться{}, // уединяться с подругой в доме
rus_verbs:уладить{}, // уладить конфликт с соседями
rus_verbs:идти{}, // Я шел туда с тяжёлым сердцем.
rus_verbs:разделять{}, // Я разделяю с вами горе и радость.
rus_verbs:обратиться{}, // Я обратился к нему с просьбой о помощи.
rus_verbs:захватить{}, // Я не захватил с собой денег.
прилагательное:знакомый{}, // Я знаком с ними обоими.
rus_verbs:вести{}, // Я веду с ней переписку.
прилагательное:сопряженный{}, // Это сопряжено с большими трудностями.
прилагательное:связанный{причастие}, // Это дело связано с риском.
rus_verbs:поехать{}, // Хотите поехать со мной в театр?
rus_verbs:проснуться{}, // Утром я проснулся с ясной головой.
rus_verbs:лететь{}, // Самолёт летел со скоростью звука.
rus_verbs:играть{}, // С огнём играть опасно!
rus_verbs:поделать{}, // С ним ничего не поделаешь.
rus_verbs:стрястись{}, // С ней стряслось несчастье.
rus_verbs:смотреться{}, // Пьеса смотрится с удовольствием.
rus_verbs:смотреть{}, // Она смотрела на меня с явным неудовольствием.
rus_verbs:разойтись{}, // Она разошлась с мужем.
rus_verbs:пристать{}, // Она пристала ко мне с расспросами.
rus_verbs:посмотреть{}, // Она посмотрела на меня с удивлением.
rus_verbs:поступить{}, // Она плохо поступила с ним.
rus_verbs:выйти{}, // Она вышла с усталым и недовольным видом.
rus_verbs:взять{}, // Возьмите с собой только самое необходимое.
rus_verbs:наплакаться{}, // Наплачется она с ним.
rus_verbs:лежать{}, // Он лежит с воспалением лёгких.
rus_verbs:дышать{}, // дышащий с трудом
rus_verbs:брать{}, // брать с собой
rus_verbs:мчаться{}, // Автомобиль мчится с необычайной быстротой.
rus_verbs:упасть{}, // Ваза упала со звоном.
rus_verbs:вернуться{}, // мы вернулись вчера домой с полным лукошком
rus_verbs:сидеть{}, // Она сидит дома с ребенком
rus_verbs:встретиться{}, // встречаться с кем-либо
ГЛ_ИНФ(придти), прилагательное:пришедший{}, // пришедший с другом
ГЛ_ИНФ(постирать), прилагательное:постиранный{}, деепричастие:постирав{},
rus_verbs:мыть{}
}
fact гл_предл
{
if context { Гл_С_Твор предлог:с{} @regex("[a-z]+[0-9]*") }
then return true
}
fact гл_предл
{
if context { Гл_С_Твор предлог:с{} *:*{падеж:твор} }
then return true
}
#endregion ТВОРИТЕЛЬНЫЙ
#region РОДИТЕЛЬНЫЙ
wordentry_set Гл_С_Род=
{
rus_verbs:УХОДИТЬ{}, // Но с базы не уходить.
rus_verbs:РВАНУТЬ{}, // Водитель прорычал проклятие и рванул машину с места. (РВАНУТЬ)
rus_verbs:ОХВАТИТЬ{}, // огонь охватил его со всех сторон (ОХВАТИТЬ)
rus_verbs:ЗАМЕТИТЬ{}, // Он понимал, что свет из тайника невозможно заметить с палубы (ЗАМЕТИТЬ/РАЗГЛЯДЕТЬ)
rus_verbs:РАЗГЛЯДЕТЬ{}, //
rus_verbs:СПЛАНИРОВАТЬ{}, // Птицы размером с орлицу, вероятно, не могли бы подняться в воздух, не спланировав с высокого утеса. (СПЛАНИРОВАТЬ)
rus_verbs:УМЕРЕТЬ{}, // Он умрет с голоду. (УМЕРЕТЬ)
rus_verbs:ВСПУГНУТЬ{}, // Оба упали с лязгом, вспугнувшим птиц с ближайших деревьев (ВСПУГНУТЬ)
rus_verbs:РЕВЕТЬ{}, // Время от времени какой-то ящер ревел с берега или самой реки. (РЕВЕТЬ/ЗАРЕВЕТЬ/ПРОРЕВЕТЬ/ЗАОРАТЬ/ПРООРАТЬ/ОРАТЬ/ПРОКРИЧАТЬ/ЗАКРИЧАТЬ/ВОПИТЬ/ЗАВОПИТЬ)
rus_verbs:ЗАРЕВЕТЬ{}, //
rus_verbs:ПРОРЕВЕТЬ{}, //
rus_verbs:ЗАОРАТЬ{}, //
rus_verbs:ПРООРАТЬ{}, //
rus_verbs:ОРАТЬ{}, //
rus_verbs:ЗАКРИЧАТЬ{},
rus_verbs:ВОПИТЬ{}, //
rus_verbs:ЗАВОПИТЬ{}, //
rus_verbs:СТАЩИТЬ{}, // Я видела как они стащили его с валуна и увели с собой. (СТАЩИТЬ/СТАСКИВАТЬ)
rus_verbs:СТАСКИВАТЬ{}, //
rus_verbs:ПРОВЫТЬ{}, // Призрак трубного зова провыл с другой стороны дверей. (ПРОВЫТЬ, ЗАВЫТЬ, ВЫТЬ)
rus_verbs:ЗАВЫТЬ{}, //
rus_verbs:ВЫТЬ{}, //
rus_verbs:СВЕТИТЬ{}, // Полуденное майское солнце ярко светило с голубых небес Аризоны. (СВЕТИТЬ)
rus_verbs:ОТСВЕЧИВАТЬ{}, // Солнце отсвечивало с белых лошадей, белых щитов и белых перьев и искрилось на наконечниках пик. (ОТСВЕЧИВАТЬ С, ИСКРИТЬСЯ НА)
rus_verbs:перегнать{}, // Скот нужно перегнать с этого пастбища на другое
rus_verbs:собирать{}, // мальчики начали собирать со столов посуду
rus_verbs:разглядывать{}, // ты ее со всех сторон разглядывал
rus_verbs:СЖИМАТЬ{}, // меня плотно сжимали со всех сторон (СЖИМАТЬ)
rus_verbs:СОБРАТЬСЯ{}, // со всего света собрались! (СОБРАТЬСЯ)
rus_verbs:ИЗГОНЯТЬ{}, // Вино в пакетах изгоняют с рынка (ИЗГОНЯТЬ)
rus_verbs:ВЛЮБИТЬСЯ{}, // влюбился в нее с первого взгляда (ВЛЮБИТЬСЯ)
rus_verbs:РАЗДАВАТЬСЯ{}, // теперь крик раздавался со всех сторон (РАЗДАВАТЬСЯ)
rus_verbs:ПОСМОТРЕТЬ{}, // Посмотрите на это с моей точки зрения (ПОСМОТРЕТЬ С род)
rus_verbs:СХОДИТЬ{}, // принимать участие во всех этих событиях - значит продолжать сходить с ума (СХОДИТЬ С род)
rus_verbs:РУХНУТЬ{}, // В Башкирии микроавтобус рухнул с моста (РУХНУТЬ С)
rus_verbs:УВОЛИТЬ{}, // рекомендовать уволить их с работы (УВОЛИТЬ С)
rus_verbs:КУПИТЬ{}, // еда , купленная с рук (КУПИТЬ С род)
rus_verbs:УБРАТЬ{}, // помочь убрать со стола? (УБРАТЬ С)
rus_verbs:ТЯНУТЬ{}, // с моря тянуло ветром (ТЯНУТЬ С)
rus_verbs:ПРИХОДИТЬ{}, // приходит с работы муж (ПРИХОДИТЬ С)
rus_verbs:ПРОПАСТЬ{}, // изображение пропало с экрана (ПРОПАСТЬ С)
rus_verbs:ПОТЯНУТЬ{}, // с балкона потянуло холодом (ПОТЯНУТЬ С род)
rus_verbs:РАЗДАТЬСЯ{}, // с палубы раздался свист (РАЗДАТЬСЯ С род)
rus_verbs:ЗАЙТИ{}, // зашел с другой стороны (ЗАЙТИ С род)
rus_verbs:НАЧАТЬ{}, // давай начнем с этого (НАЧАТЬ С род)
rus_verbs:УВЕСТИ{}, // дала увести с развалин (УВЕСТИ С род)
rus_verbs:ОПУСКАТЬСЯ{}, // с гор опускалась ночь (ОПУСКАТЬСЯ С)
rus_verbs:ВСКОЧИТЬ{}, // Тристан вскочил с места (ВСКОЧИТЬ С род)
rus_verbs:БРАТЬ{}, // беру с него пример (БРАТЬ С род)
rus_verbs:ПРИПОДНЯТЬСЯ{}, // голова приподнялась с плеча (ПРИПОДНЯТЬСЯ С род)
rus_verbs:ПОЯВИТЬСЯ{}, // всадники появились с востока (ПОЯВИТЬСЯ С род)
rus_verbs:НАЛЕТЕТЬ{}, // с моря налетел ветер (НАЛЕТЕТЬ С род)
rus_verbs:ВЗВИТЬСЯ{}, // Натан взвился с места (ВЗВИТЬСЯ С род)
rus_verbs:ПОДОБРАТЬ{}, // подобрал с земли копье (ПОДОБРАТЬ С)
rus_verbs:ДЕРНУТЬСЯ{}, // Кирилл дернулся с места (ДЕРНУТЬСЯ С род)
rus_verbs:ВОЗВРАЩАТЬСЯ{}, // они возвращались с реки (ВОЗВРАЩАТЬСЯ С род)
rus_verbs:ПЛЫТЬ{}, // плыли они с запада (ПЛЫТЬ С род)
rus_verbs:ЗНАТЬ{}, // одно знали с древности (ЗНАТЬ С)
rus_verbs:НАКЛОНИТЬСЯ{}, // всадник наклонился с лошади (НАКЛОНИТЬСЯ С)
rus_verbs:НАЧАТЬСЯ{}, // началось все со скуки (НАЧАТЬСЯ С)
прилагательное:ИЗВЕСТНЫЙ{}, // Культура его известна со времен глубокой древности (ИЗВЕСТНЫЙ С)
rus_verbs:СБИТЬ{}, // Порыв ветра сбил Ваньку с ног (ts СБИТЬ С)
rus_verbs:СОБИРАТЬСЯ{}, // они собираются сюда со всей равнины. (СОБИРАТЬСЯ С род)
rus_verbs:смыть{}, // Дождь должен смыть с листьев всю пыль. (СМЫТЬ С)
rus_verbs:привстать{}, // Мартин привстал со своего стула. (привстать с)
rus_verbs:спасть{}, // тяжесть спала с души. (спасть с)
rus_verbs:выглядеть{}, // так оно со стороны выглядело. (ВЫГЛЯДЕТЬ С)
rus_verbs:повернуть{}, // к вечеру они повернули с нее направо. (ПОВЕРНУТЬ С)
rus_verbs:ТЯНУТЬСЯ{}, // со стороны реки ко мне тянулись языки тумана. (ТЯНУТЬСЯ С)
rus_verbs:ВОЕВАТЬ{}, // Генерал воевал с юных лет. (ВОЕВАТЬ С чего-то)
rus_verbs:БОЛЕТЬ{}, // Голова болит с похмелья. (БОЛЕТЬ С)
rus_verbs:приближаться{}, // со стороны острова приближалась лодка.
rus_verbs:ПОТЯНУТЬСЯ{}, // со всех сторон к нему потянулись руки. (ПОТЯНУТЬСЯ С)
rus_verbs:пойти{}, // низкий гул пошел со стороны долины. (пошел с)
rus_verbs:зашевелиться{}, // со всех сторон зашевелились кусты. (зашевелиться с)
rus_verbs:МЧАТЬСЯ{}, // со стороны леса мчались всадники. (МЧАТЬСЯ С)
rus_verbs:БЕЖАТЬ{}, // люди бежали со всех ног. (БЕЖАТЬ С)
rus_verbs:СЛЫШАТЬСЯ{}, // шум слышался со стороны моря. (СЛЫШАТЬСЯ С)
rus_verbs:ЛЕТЕТЬ{}, // со стороны деревни летела птица. (ЛЕТЕТЬ С)
rus_verbs:ПЕРЕТЬ{}, // враги прут со всех сторон. (ПЕРЕТЬ С)
rus_verbs:ПОСЫПАТЬСЯ{}, // вопросы посыпались со всех сторон. (ПОСЫПАТЬСЯ С)
rus_verbs:ИДТИ{}, // угроза шла со стороны моря. (ИДТИ С + род.п.)
rus_verbs:ПОСЛЫШАТЬСЯ{}, // со стен послышались крики ужаса. (ПОСЛЫШАТЬСЯ С)
rus_verbs:ОБРУШИТЬСЯ{}, // звуки обрушились со всех сторон. (ОБРУШИТЬСЯ С)
rus_verbs:УДАРИТЬ{}, // голоса ударили со всех сторон. (УДАРИТЬ С)
rus_verbs:ПОКАЗАТЬСЯ{}, // со стороны деревни показались земляне. (ПОКАЗАТЬСЯ С)
rus_verbs:прыгать{}, // придется прыгать со второго этажа. (прыгать с)
rus_verbs:СТОЯТЬ{}, // со всех сторон стоял лес. (СТОЯТЬ С)
rus_verbs:доноситься{}, // шум со двора доносился чудовищный. (доноситься с)
rus_verbs:мешать{}, // мешать воду с мукой (мешать с)
rus_verbs:вестись{}, // Переговоры ведутся с позиции силы. (вестись с)
rus_verbs:вставать{}, // Он не встает с кровати. (вставать с)
rus_verbs:окружать{}, // зеленые щупальца окружали ее со всех сторон. (окружать с)
rus_verbs:причитаться{}, // С вас причитается 50 рублей.
rus_verbs:соскользнуть{}, // его острый клюв соскользнул с ее руки.
rus_verbs:сократить{}, // Его сократили со службы.
rus_verbs:поднять{}, // рука подняла с пола
rus_verbs:поднимать{},
rus_verbs:тащить{}, // тем временем другие пришельцы тащили со всех сторон камни.
rus_verbs:полететь{}, // Мальчик полетел с лестницы.
rus_verbs:литься{}, // вода льется с неба
rus_verbs:натечь{}, // натечь с сапог
rus_verbs:спрыгивать{}, // спрыгивать с движущегося трамвая
rus_verbs:съезжать{}, // съезжать с заявленной темы
rus_verbs:покатываться{}, // покатываться со смеху
rus_verbs:перескакивать{}, // перескакивать с одного примера на другой
rus_verbs:сдирать{}, // сдирать с тела кожу
rus_verbs:соскальзывать{}, // соскальзывать с крючка
rus_verbs:сметать{}, // сметать с прилавков
rus_verbs:кувыркнуться{}, // кувыркнуться со ступеньки
rus_verbs:прокаркать{}, // прокаркать с ветки
rus_verbs:стряхивать{}, // стряхивать с одежды
rus_verbs:сваливаться{}, // сваливаться с лестницы
rus_verbs:слизнуть{}, // слизнуть с лица
rus_verbs:доставляться{}, // доставляться с фермы
rus_verbs:обступать{}, // обступать с двух сторон
rus_verbs:повскакивать{}, // повскакивать с мест
rus_verbs:обозревать{}, // обозревать с вершины
rus_verbs:слинять{}, // слинять с урока
rus_verbs:смывать{}, // смывать с лица
rus_verbs:спихнуть{}, // спихнуть со стола
rus_verbs:обозреть{}, // обозреть с вершины
rus_verbs:накупить{}, // накупить с рук
rus_verbs:схлынуть{}, // схлынуть с берега
rus_verbs:спикировать{}, // спикировать с километровой высоты
rus_verbs:уползти{}, // уползти с поля боя
rus_verbs:сбиваться{}, // сбиваться с пути
rus_verbs:отлучиться{}, // отлучиться с поста
rus_verbs:сигануть{}, // сигануть с крыши
rus_verbs:сместить{}, // сместить с поста
rus_verbs:списать{}, // списать с оригинального устройства
инфинитив:слетать{ вид:несоверш }, глагол:слетать{ вид:несоверш }, // слетать с трассы
деепричастие:слетая{},
rus_verbs:напиваться{}, // напиваться с горя
rus_verbs:свесить{}, // свесить с крыши
rus_verbs:заполучить{}, // заполучить со склада
rus_verbs:спадать{}, // спадать с глаз
rus_verbs:стартовать{}, // стартовать с мыса
rus_verbs:спереть{}, // спереть со склада
rus_verbs:согнать{}, // согнать с живота
rus_verbs:скатываться{}, // скатываться со стога
rus_verbs:сняться{}, // сняться с выборов
rus_verbs:слезать{}, // слезать со стола
rus_verbs:деваться{}, // деваться с подводной лодки
rus_verbs:огласить{}, // огласить с трибуны
rus_verbs:красть{}, // красть со склада
rus_verbs:расширить{}, // расширить с торца
rus_verbs:угадывать{}, // угадывать с полуслова
rus_verbs:оскорбить{}, // оскорбить со сцены
rus_verbs:срывать{}, // срывать с головы
rus_verbs:сшибить{}, // сшибить с коня
rus_verbs:сбивать{}, // сбивать с одежды
rus_verbs:содрать{}, // содрать с посетителей
rus_verbs:столкнуть{}, // столкнуть с горы
rus_verbs:отряхнуть{}, // отряхнуть с одежды
rus_verbs:сбрасывать{}, // сбрасывать с борта
rus_verbs:расстреливать{}, // расстреливать с борта вертолета
rus_verbs:придти{}, // мать скоро придет с работы
rus_verbs:съехать{}, // Миша съехал с горки
rus_verbs:свисать{}, // свисать с веток
rus_verbs:стянуть{}, // стянуть с кровати
rus_verbs:скинуть{}, // скинуть снег с плеча
rus_verbs:загреметь{}, // загреметь со стула
rus_verbs:сыпаться{}, // сыпаться с неба
rus_verbs:стряхнуть{}, // стряхнуть с головы
rus_verbs:сползти{}, // сползти со стула
rus_verbs:стереть{}, // стереть с экрана
rus_verbs:прогнать{}, // прогнать с фермы
rus_verbs:смахнуть{}, // смахнуть со стола
rus_verbs:спускать{}, // спускать с поводка
rus_verbs:деться{}, // деться с подводной лодки
rus_verbs:сдернуть{}, // сдернуть с себя
rus_verbs:сдвинуться{}, // сдвинуться с места
rus_verbs:слететь{}, // слететь с катушек
rus_verbs:обступить{}, // обступить со всех сторон
rus_verbs:снести{}, // снести с плеч
инфинитив:сбегать{ вид:несоверш }, глагол:сбегать{ вид:несоверш }, // сбегать с уроков
деепричастие:сбегая{}, прилагательное:сбегающий{},
// прилагательное:сбегавший{ вид:несоверш },
rus_verbs:запить{}, // запить с горя
rus_verbs:рубануть{}, // рубануть с плеча
rus_verbs:чертыхнуться{}, // чертыхнуться с досады
rus_verbs:срываться{}, // срываться с цепи
rus_verbs:смыться{}, // смыться с уроков
rus_verbs:похитить{}, // похитить со склада
rus_verbs:смести{}, // смести со своего пути
rus_verbs:отгружать{}, // отгружать со склада
rus_verbs:отгрузить{}, // отгрузить со склада
rus_verbs:бросаться{}, // Дети бросались в воду с моста
rus_verbs:броситься{}, // самоубийца бросился с моста в воду
rus_verbs:взимать{}, // Билетер взимает плату с каждого посетителя
rus_verbs:взиматься{}, // Плата взимается с любого посетителя
rus_verbs:взыскать{}, // Приставы взыскали долг с бедолаги
rus_verbs:взыскивать{}, // Приставы взыскивают с бедолаги все долги
rus_verbs:взыскиваться{}, // Долги взыскиваются с алиментщиков
rus_verbs:вспархивать{}, // вспархивать с цветка
rus_verbs:вспорхнуть{}, // вспорхнуть с ветки
rus_verbs:выбросить{}, // выбросить что-то с балкона
rus_verbs:выводить{}, // выводить с одежды пятна
rus_verbs:снять{}, // снять с головы
rus_verbs:начинать{}, // начинать с эскиза
rus_verbs:двинуться{}, // двинуться с места
rus_verbs:начинаться{}, // начинаться с гардероба
rus_verbs:стечь{}, // стечь с крыши
rus_verbs:слезть{}, // слезть с кучи
rus_verbs:спуститься{}, // спуститься с крыши
rus_verbs:сойти{}, // сойти с пьедестала
rus_verbs:свернуть{}, // свернуть с пути
rus_verbs:сорвать{}, // сорвать с цепи
rus_verbs:сорваться{}, // сорваться с поводка
rus_verbs:тронуться{}, // тронуться с места
rus_verbs:угадать{}, // угадать с первой попытки
rus_verbs:спустить{}, // спустить с лестницы
rus_verbs:соскочить{}, // соскочить с крючка
rus_verbs:сдвинуть{}, // сдвинуть с места
rus_verbs:подниматься{}, // туман, поднимающийся с болота
rus_verbs:подняться{}, // туман, поднявшийся с болота
rus_verbs:валить{}, // Резкий порывистый ветер валит прохожих с ног.
rus_verbs:свалить{}, // Резкий порывистый ветер свалит тебя с ног.
rus_verbs:донестись{}, // С улицы донесся шум дождя.
rus_verbs:опасть{}, // Опавшие с дерева листья.
rus_verbs:махнуть{}, // Он махнул с берега в воду.
rus_verbs:исчезнуть{}, // исчезнуть с экрана
rus_verbs:свалиться{}, // свалиться со сцены
rus_verbs:упасть{}, // упасть с дерева
rus_verbs:вернуться{}, // Он ещё не вернулся с работы.
rus_verbs:сдувать{}, // сдувать пух с одуванчиков
rus_verbs:свергать{}, // свергать царя с трона
rus_verbs:сбиться{}, // сбиться с пути
rus_verbs:стирать{}, // стирать тряпкой надпись с доски
rus_verbs:убирать{}, // убирать мусор c пола
rus_verbs:удалять{}, // удалять игрока с поля
rus_verbs:окружить{}, // Япония окружена со всех сторон морями.
rus_verbs:снимать{}, // Я снимаю с себя всякую ответственность за его поведение.
глагол:писаться{ aux stress="пис^аться" }, // Собственные имена пишутся с большой буквы.
прилагательное:спокойный{}, // С этой стороны я спокоен.
rus_verbs:спросить{}, // С тебя за всё спросят.
rus_verbs:течь{}, // С него течёт пот.
rus_verbs:дуть{}, // С моря дует ветер.
rus_verbs:капать{}, // С его лица капали крупные капли пота.
rus_verbs:опустить{}, // Она опустила ребёнка с рук на пол.
rus_verbs:спрыгнуть{}, // Она легко спрыгнула с коня.
rus_verbs:встать{}, // Все встали со стульев.
rus_verbs:сбросить{}, // Войдя в комнату, он сбросил с себя пальто.
rus_verbs:взять{}, // Возьми книгу с полки.
rus_verbs:спускаться{}, // Мы спускались с горы.
rus_verbs:уйти{}, // Он нашёл себе заместителя и ушёл со службы.
rus_verbs:порхать{}, // Бабочка порхает с цветка на цветок.
rus_verbs:отправляться{}, // Ваш поезд отправляется со второй платформы.
rus_verbs:двигаться{}, // Он не двигался с места.
rus_verbs:отходить{}, // мой поезд отходит с первого пути
rus_verbs:попасть{}, // Майкл попал в кольцо с десятиметровой дистанции
rus_verbs:падать{}, // снег падает с ветвей
rus_verbs:скрыться{} // Ее водитель, бросив машину, скрылся с места происшествия.
}
fact гл_предл
{
if context { Гл_С_Род предлог:с{} @regex("[a-z]+[0-9]*") }
then return true
}
fact гл_предл
{
if context { Гл_С_Род предлог:с{} *:*{падеж:род} }
then return true
}
fact гл_предл
{
if context { Гл_С_Род предлог:с{} *:*{падеж:парт} }
then return true
}
#endregion РОДИТЕЛЬНЫЙ
fact гл_предл
{
if context { * предлог:с{} *:*{ падеж:твор } }
then return false,-3
}
fact гл_предл
{
if context { * предлог:с{} *:*{ падеж:род } }
then return false,-4
}
fact гл_предл
{
if context { * предлог:с{} * }
then return false,-5
}
#endregion Предлог_С
/*
#region Предлог_ПОД
// -------------- ПРЕДЛОГ 'ПОД' -----------------------
fact гл_предл
{
if context { * предлог:под{} @regex("[a-z]+[0-9]*") }
then return true
}
// ПОД+вин.п. не может присоединяться к существительным, поэтому
// он присоединяется к любым глаголам.
fact гл_предл
{
if context { * предлог:под{} *:*{ падеж:вин } }
then return true
}
wordentry_set Гл_ПОД_твор=
{
rus_verbs:извиваться{}, // извивалась под его длинными усами
rus_verbs:РАСПРОСТРАНЯТЬСЯ{}, // Под густым ковром травы и плотным сплетением корней (РАСПРОСТРАНЯТЬСЯ)
rus_verbs:БРОСИТЬ{}, // чтобы ты его под деревом бросил? (БРОСИТЬ)
rus_verbs:БИТЬСЯ{}, // под моей щекой сильно билось его сердце (БИТЬСЯ)
rus_verbs:ОПУСТИТЬСЯ{}, // глаза его опустились под ее желтым взглядом (ОПУСТИТЬСЯ)
rus_verbs:ВЗДЫМАТЬСЯ{}, // его грудь судорожно вздымалась под ее рукой (ВЗДЫМАТЬСЯ)
rus_verbs:ПРОМЧАТЬСЯ{}, // Она промчалась под ними и исчезла за изгибом горы. (ПРОМЧАТЬСЯ)
rus_verbs:всплыть{}, // Наконец он всплыл под нависавшей кормой, так и не отыскав того, что хотел. (всплыть)
rus_verbs:КОНЧАТЬСЯ{}, // Он почти вертикально уходит в реку и кончается глубоко под водой. (КОНЧАТЬСЯ)
rus_verbs:ПОЛЗТИ{}, // Там они ползли под спутанным терновником и сквозь переплетавшиеся кусты (ПОЛЗТИ)
rus_verbs:ПРОХОДИТЬ{}, // Вольф проходил под гигантскими ветвями деревьев и мхов, свисавших с ветвей зелеными водопадами. (ПРОХОДИТЬ, ПРОПОЛЗТИ, ПРОПОЛЗАТЬ)
rus_verbs:ПРОПОЛЗТИ{}, //
rus_verbs:ПРОПОЛЗАТЬ{}, //
rus_verbs:ИМЕТЬ{}, // Эти предположения не имеют под собой никакой почвы (ИМЕТЬ)
rus_verbs:НОСИТЬ{}, // она носит под сердцем ребенка (НОСИТЬ)
rus_verbs:ПАСТЬ{}, // Рим пал под натиском варваров (ПАСТЬ)
rus_verbs:УТОНУТЬ{}, // Выступавшие старческие вены снова утонули под гладкой твердой плотью. (УТОНУТЬ)
rus_verbs:ВАЛЯТЬСЯ{}, // Под его кривыми серыми ветвями и пестрыми коричнево-зелеными листьями валялись пустые ореховые скорлупки и сердцевины плодов. (ВАЛЯТЬСЯ)
rus_verbs:вздрогнуть{}, // она вздрогнула под его взглядом
rus_verbs:иметься{}, // у каждого под рукой имелся арбалет
rus_verbs:ЖДАТЬ{}, // Сашка уже ждал под дождем (ЖДАТЬ)
rus_verbs:НОЧЕВАТЬ{}, // мне приходилось ночевать под открытым небом (НОЧЕВАТЬ)
rus_verbs:УЗНАТЬ{}, // вы должны узнать меня под этим именем (УЗНАТЬ)
rus_verbs:ЗАДЕРЖИВАТЬСЯ{}, // мне нельзя задерживаться под землей! (ЗАДЕРЖИВАТЬСЯ)
rus_verbs:ПОГИБНУТЬ{}, // под их копытами погибли целые армии! (ПОГИБНУТЬ)
rus_verbs:РАЗДАВАТЬСЯ{}, // под ногами у меня раздавался сухой хруст (РАЗДАВАТЬСЯ)
rus_verbs:КРУЖИТЬСЯ{}, // поверхность планеты кружилась у него под ногами (КРУЖИТЬСЯ)
rus_verbs:ВИСЕТЬ{}, // под глазами у него висели тяжелые складки кожи (ВИСЕТЬ)
rus_verbs:содрогнуться{}, // содрогнулся под ногами каменный пол (СОДРОГНУТЬСЯ)
rus_verbs:СОБИРАТЬСЯ{}, // темнота уже собиралась под деревьями (СОБИРАТЬСЯ)
rus_verbs:УПАСТЬ{}, // толстяк упал под градом ударов (УПАСТЬ)
rus_verbs:ДВИНУТЬСЯ{}, // лодка двинулась под водой (ДВИНУТЬСЯ)
rus_verbs:ЦАРИТЬ{}, // под его крышей царила холодная зима (ЦАРИТЬ)
rus_verbs:ПРОВАЛИТЬСЯ{}, // под копытами его лошади провалился мост (ПРОВАЛИТЬСЯ ПОД твор)
rus_verbs:ЗАДРОЖАТЬ{}, // земля задрожала под ногами (ЗАДРОЖАТЬ)
rus_verbs:НАХМУРИТЬСЯ{}, // государь нахмурился под маской (НАХМУРИТЬСЯ)
rus_verbs:РАБОТАТЬ{}, // работать под угрозой нельзя (РАБОТАТЬ)
rus_verbs:ШЕВЕЛЬНУТЬСЯ{}, // под ногой шевельнулся камень (ШЕВЕЛЬНУТЬСЯ)
rus_verbs:ВИДЕТЬ{}, // видел тебя под камнем. (ВИДЕТЬ)
rus_verbs:ОСТАТЬСЯ{}, // второе осталось под водой (ОСТАТЬСЯ)
rus_verbs:КИПЕТЬ{}, // вода кипела под копытами (КИПЕТЬ)
rus_verbs:СИДЕТЬ{}, // может сидит под деревом (СИДЕТЬ)
rus_verbs:МЕЛЬКНУТЬ{}, // под нами мелькнуло море (МЕЛЬКНУТЬ)
rus_verbs:ПОСЛЫШАТЬСЯ{}, // под окном послышался шум (ПОСЛЫШАТЬСЯ)
rus_verbs:ТЯНУТЬСЯ{}, // под нами тянулись облака (ТЯНУТЬСЯ)
rus_verbs:ДРОЖАТЬ{}, // земля дрожала под ним (ДРОЖАТЬ)
rus_verbs:ПРИЙТИСЬ{}, // хуже пришлось под землей (ПРИЙТИСЬ)
rus_verbs:ГОРЕТЬ{}, // лампа горела под потолком (ГОРЕТЬ)
rus_verbs:ПОЛОЖИТЬ{}, // положил под деревом плащ (ПОЛОЖИТЬ)
rus_verbs:ЗАГОРЕТЬСЯ{}, // под деревьями загорелся костер (ЗАГОРЕТЬСЯ)
rus_verbs:ПРОНОСИТЬСЯ{}, // под нами проносились крыши (ПРОНОСИТЬСЯ)
rus_verbs:ПОТЯНУТЬСЯ{}, // под кораблем потянулись горы (ПОТЯНУТЬСЯ)
rus_verbs:БЕЖАТЬ{}, // беги под серой стеной ночи (БЕЖАТЬ)
rus_verbs:РАЗДАТЬСЯ{}, // под окном раздалось тяжелое дыхание (РАЗДАТЬСЯ)
rus_verbs:ВСПЫХНУТЬ{}, // под потолком вспыхнула яркая лампа (ВСПЫХНУТЬ)
rus_verbs:СМОТРЕТЬ{}, // просто смотрите под другим углом (СМОТРЕТЬ ПОД)
rus_verbs:ДУТЬ{}, // теперь под деревьями дул ветерок (ДУТЬ)
rus_verbs:СКРЫТЬСЯ{}, // оно быстро скрылось под водой (СКРЫТЬСЯ ПОД)
rus_verbs:ЩЕЛКНУТЬ{}, // далеко под ними щелкнул выстрел (ЩЕЛКНУТЬ)
rus_verbs:ТРЕЩАТЬ{}, // осколки стекла трещали под ногами (ТРЕЩАТЬ)
rus_verbs:РАСПОЛАГАТЬСЯ{}, // под ними располагались разноцветные скамьи (РАСПОЛАГАТЬСЯ)
rus_verbs:ВЫСТУПИТЬ{}, // под ногтями выступили капельки крови (ВЫСТУПИТЬ)
rus_verbs:НАСТУПИТЬ{}, // под куполом базы наступила тишина (НАСТУПИТЬ)
rus_verbs:ОСТАНОВИТЬСЯ{}, // повозка остановилась под самым окном (ОСТАНОВИТЬСЯ)
rus_verbs:РАСТАЯТЬ{}, // магазин растаял под ночным дождем (РАСТАЯТЬ)
rus_verbs:ДВИГАТЬСЯ{}, // под водой двигалось нечто огромное (ДВИГАТЬСЯ)
rus_verbs:БЫТЬ{}, // под снегом могут быть трещины (БЫТЬ)
rus_verbs:ЗИЯТЬ{}, // под ней зияла ужасная рана (ЗИЯТЬ)
rus_verbs:ЗАЗВОНИТЬ{}, // под рукой водителя зазвонил телефон (ЗАЗВОНИТЬ)
rus_verbs:ПОКАЗАТЬСЯ{}, // внезапно под ними показалась вода (ПОКАЗАТЬСЯ)
rus_verbs:ЗАМЕРЕТЬ{}, // эхо замерло под высоким потолком (ЗАМЕРЕТЬ)
rus_verbs:ПОЙТИ{}, // затем под кораблем пошла пустыня (ПОЙТИ)
rus_verbs:ДЕЙСТВОВАТЬ{}, // боги всегда действуют под маской (ДЕЙСТВОВАТЬ)
rus_verbs:БЛЕСТЕТЬ{}, // мокрый мех блестел под луной (БЛЕСТЕТЬ)
rus_verbs:ЛЕТЕТЬ{}, // под ним летела серая земля (ЛЕТЕТЬ)
rus_verbs:СОГНУТЬСЯ{}, // содрогнулся под ногами каменный пол (СОГНУТЬСЯ)
rus_verbs:КИВНУТЬ{}, // четвертый слегка кивнул под капюшоном (КИВНУТЬ)
rus_verbs:УМЕРЕТЬ{}, // колдун умер под грудой каменных глыб (УМЕРЕТЬ)
rus_verbs:ОКАЗЫВАТЬСЯ{}, // внезапно под ногами оказывается знакомая тропинка (ОКАЗЫВАТЬСЯ)
rus_verbs:ИСЧЕЗАТЬ{}, // серая лента дороги исчезала под воротами (ИСЧЕЗАТЬ)
rus_verbs:СВЕРКНУТЬ{}, // голубые глаза сверкнули под густыми бровями (СВЕРКНУТЬ)
rus_verbs:СИЯТЬ{}, // под ним сияла белая пелена облаков (СИЯТЬ)
rus_verbs:ПРОНЕСТИСЬ{}, // тихий смех пронесся под куполом зала (ПРОНЕСТИСЬ)
rus_verbs:СКОЛЬЗИТЬ{}, // обломки судна медленно скользили под ними (СКОЛЬЗИТЬ)
rus_verbs:ВЗДУТЬСЯ{}, // под серой кожей вздулись шары мускулов (ВЗДУТЬСЯ)
rus_verbs:ПРОЙТИ{}, // обломок отлично пройдет под колесами слева (ПРОЙТИ)
rus_verbs:РАЗВЕВАТЬСЯ{}, // светлые волосы развевались под дыханием ветра (РАЗВЕВАТЬСЯ)
rus_verbs:СВЕРКАТЬ{}, // глаза огнем сверкали под темными бровями (СВЕРКАТЬ)
rus_verbs:КАЗАТЬСЯ{}, // деревянный док казался очень твердым под моими ногами (КАЗАТЬСЯ)
rus_verbs:ПОСТАВИТЬ{}, // четвертый маг торопливо поставил под зеркалом широкую чашу (ПОСТАВИТЬ)
rus_verbs:ОСТАВАТЬСЯ{}, // запасы остаются под давлением (ОСТАВАТЬСЯ ПОД)
rus_verbs:ПЕТЬ{}, // просто мы под землей любим петь. (ПЕТЬ ПОД)
rus_verbs:ПОЯВИТЬСЯ{}, // под их крыльями внезапно появился дым. (ПОЯВИТЬСЯ ПОД)
rus_verbs:ОКАЗАТЬСЯ{}, // мы снова оказались под солнцем. (ОКАЗАТЬСЯ ПОД)
rus_verbs:ПОДХОДИТЬ{}, // мы подходили под другим углом? (ПОДХОДИТЬ ПОД)
rus_verbs:СКРЫВАТЬСЯ{}, // кто под ней скрывается? (СКРЫВАТЬСЯ ПОД)
rus_verbs:ХЛЮПАТЬ{}, // под ногами Аллы хлюпала грязь (ХЛЮПАТЬ ПОД)
rus_verbs:ШАГАТЬ{}, // их отряд весело шагал под дождем этой музыки. (ШАГАТЬ ПОД)
rus_verbs:ТЕЧЬ{}, // под ее поверхностью медленно текла ярость. (ТЕЧЬ ПОД твор)
rus_verbs:ОЧУТИТЬСЯ{}, // мы очутились под стенами замка. (ОЧУТИТЬСЯ ПОД)
rus_verbs:ПОБЛЕСКИВАТЬ{}, // их латы поблескивали под солнцем. (ПОБЛЕСКИВАТЬ ПОД)
rus_verbs:ДРАТЬСЯ{}, // под столами дрались за кости псы. (ДРАТЬСЯ ПОД)
rus_verbs:КАЧНУТЬСЯ{}, // палуба качнулась у нас под ногами. (КАЧНУЛАСЬ ПОД)
rus_verbs:ПРИСЕСТЬ{}, // конь даже присел под тяжелым телом. (ПРИСЕСТЬ ПОД)
rus_verbs:ЖИТЬ{}, // они живут под землей. (ЖИТЬ ПОД)
rus_verbs:ОБНАРУЖИТЬ{}, // вы можете обнаружить ее под водой? (ОБНАРУЖИТЬ ПОД)
rus_verbs:ПЛЫТЬ{}, // Орёл плывёт под облаками. (ПЛЫТЬ ПОД)
rus_verbs:ИСЧЕЗНУТЬ{}, // потом они исчезли под водой. (ИСЧЕЗНУТЬ ПОД)
rus_verbs:держать{}, // оружие все держали под рукой. (держать ПОД)
rus_verbs:ВСТРЕТИТЬСЯ{}, // они встретились под водой. (ВСТРЕТИТЬСЯ ПОД)
rus_verbs:уснуть{}, // Миша уснет под одеялом
rus_verbs:пошевелиться{}, // пошевелиться под одеялом
rus_verbs:задохнуться{}, // задохнуться под слоем снега
rus_verbs:потечь{}, // потечь под избыточным давлением
rus_verbs:уцелеть{}, // уцелеть под завалами
rus_verbs:мерцать{}, // мерцать под лучами софитов
rus_verbs:поискать{}, // поискать под кроватью
rus_verbs:гудеть{}, // гудеть под нагрузкой
rus_verbs:посидеть{}, // посидеть под навесом
rus_verbs:укрыться{}, // укрыться под навесом
rus_verbs:утихнуть{}, // утихнуть под одеялом
rus_verbs:заскрипеть{}, // заскрипеть под тяжестью
rus_verbs:шелохнуться{}, // шелохнуться под одеялом
инфинитив:срезать{ вид:несоверш }, глагол:срезать{ вид:несоверш }, // срезать под корень
деепричастие:срезав{}, прилагательное:срезающий{ вид:несоверш },
инфинитив:срезать{ вид:соверш }, глагол:срезать{ вид:соверш },
деепричастие:срезая{}, прилагательное:срезавший{ вид:соверш },
rus_verbs:пониматься{}, // пониматься под успехом
rus_verbs:подразумеваться{}, // подразумеваться под правильным решением
rus_verbs:промокнуть{}, // промокнуть под проливным дождем
rus_verbs:засосать{}, // засосать под ложечкой
rus_verbs:подписаться{}, // подписаться под воззванием
rus_verbs:укрываться{}, // укрываться под навесом
rus_verbs:запыхтеть{}, // запыхтеть под одеялом
rus_verbs:мокнуть{}, // мокнуть под лождем
rus_verbs:сгибаться{}, // сгибаться под тяжестью снега
rus_verbs:намокнуть{}, // намокнуть под дождем
rus_verbs:подписываться{}, // подписываться под обращением
rus_verbs:тарахтеть{}, // тарахтеть под окнами
инфинитив:находиться{вид:несоверш}, глагол:находиться{вид:несоверш}, // Она уже несколько лет находится под наблюдением врача.
деепричастие:находясь{}, прилагательное:находившийся{вид:несоверш}, прилагательное:находящийся{},
rus_verbs:лежать{}, // лежать под капельницей
rus_verbs:вымокать{}, // вымокать под дождём
rus_verbs:вымокнуть{}, // вымокнуть под дождём
rus_verbs:проворчать{}, // проворчать под нос
rus_verbs:хмыкнуть{}, // хмыкнуть под нос
rus_verbs:отыскать{}, // отыскать под кроватью
rus_verbs:дрогнуть{}, // дрогнуть под ударами
rus_verbs:проявляться{}, // проявляться под нагрузкой
rus_verbs:сдержать{}, // сдержать под контролем
rus_verbs:ложиться{}, // ложиться под клиента
rus_verbs:таять{}, // таять под весенним солнцем
rus_verbs:покатиться{}, // покатиться под откос
rus_verbs:лечь{}, // он лег под навесом
rus_verbs:идти{}, // идти под дождем
прилагательное:известный{}, // Он известен под этим именем.
rus_verbs:стоять{}, // Ящик стоит под столом.
rus_verbs:отступить{}, // Враг отступил под ударами наших войск.
rus_verbs:царапаться{}, // Мышь царапается под полом.
rus_verbs:спать{}, // заяц спокойно спал у себя под кустом
rus_verbs:загорать{}, // мы загораем под солнцем
ГЛ_ИНФ(мыть), // мыть руки под струёй воды
ГЛ_ИНФ(закопать),
ГЛ_ИНФ(спрятать),
ГЛ_ИНФ(прятать),
ГЛ_ИНФ(перепрятать)
}
fact гл_предл
{
if context { Гл_ПОД_твор предлог:под{} *:*{ падеж:твор } }
then return true
}
// для глаголов вне списка - запрещаем.
fact гл_предл
{
if context { * предлог:под{} *:*{ падеж:твор } }
then return false,-10
}
fact гл_предл
{
if context { * предлог:под{} *:*{} }
then return false,-11
}
#endregion Предлог_ПОД
*/
#region Предлог_ОБ
// -------------- ПРЕДЛОГ 'ОБ' -----------------------
wordentry_set Гл_ОБ_предл=
{
rus_verbs:СВИДЕТЕЛЬСТВОВАТЬ{}, // Об их присутствии свидетельствовало лишь тусклое пурпурное пятно, проступавшее на камне. (СВИДЕТЕЛЬСТВОВАТЬ)
rus_verbs:ЗАДУМАТЬСЯ{}, // Промышленные гиганты задумались об экологии (ЗАДУМАТЬСЯ)
rus_verbs:СПРОСИТЬ{}, // Он спросил нескольких из пляжников об их кажущейся всеобщей юности. (СПРОСИТЬ)
rus_verbs:спрашивать{}, // как ты можешь еще спрашивать у меня об этом?
rus_verbs:забывать{}, // Мы не можем забывать об их участи.
rus_verbs:ГАДАТЬ{}, // теперь об этом можно лишь гадать (ГАДАТЬ)
rus_verbs:ПОВЕДАТЬ{}, // Градоначальник , выступая с обзором основных городских событий , поведал об этом депутатам (ПОВЕДАТЬ ОБ)
rus_verbs:СООБЩИТЬ{}, // Иран сообщил МАГАТЭ об ускорении обогащения урана (СООБЩИТЬ)
rus_verbs:ЗАЯВИТЬ{}, // Об их успешном окончании заявил генеральный директор (ЗАЯВИТЬ ОБ)
rus_verbs:слышать{}, // даже они слышали об этом человеке. (СЛЫШАТЬ ОБ)
rus_verbs:ДОЛОЖИТЬ{}, // вернувшиеся разведчики доложили об увиденном (ДОЛОЖИТЬ ОБ)
rus_verbs:ПОГОВОРИТЬ{}, // давай поговорим об этом. (ПОГОВОРИТЬ ОБ)
rus_verbs:ДОГАДАТЬСЯ{}, // об остальном нетрудно догадаться. (ДОГАДАТЬСЯ ОБ)
rus_verbs:ПОЗАБОТИТЬСЯ{}, // обещал обо всем позаботиться. (ПОЗАБОТИТЬСЯ ОБ)
rus_verbs:ПОЗАБЫТЬ{}, // Шура позабыл обо всем. (ПОЗАБЫТЬ ОБ)
rus_verbs:вспоминать{}, // Впоследствии он не раз вспоминал об этом приключении. (вспоминать об)
rus_verbs:сообщать{}, // Газета сообщает об открытии сессии парламента. (сообщать об)
rus_verbs:просить{}, // мы просили об отсрочке платежей (просить ОБ)
rus_verbs:ПЕТЬ{}, // эта же девушка пела обо всем совершенно открыто. (ПЕТЬ ОБ)
rus_verbs:сказать{}, // ты скажешь об этом капитану? (сказать ОБ)
rus_verbs:знать{}, // бы хотелось знать как можно больше об этом районе.
rus_verbs:кричать{}, // Все газеты кричат об этом событии.
rus_verbs:советоваться{}, // Она обо всём советуется с матерью.
rus_verbs:говориться{}, // об остальном говорилось легко.
rus_verbs:подумать{}, // нужно крепко обо всем подумать.
rus_verbs:напомнить{}, // черный дым напомнил об опасности.
rus_verbs:забыть{}, // забудь об этой роскоши.
rus_verbs:думать{}, // приходится обо всем думать самой.
rus_verbs:отрапортовать{}, // отрапортовать об успехах
rus_verbs:информировать{}, // информировать об изменениях
rus_verbs:оповестить{}, // оповестить об отказе
rus_verbs:убиваться{}, // убиваться об стену
rus_verbs:расшибить{}, // расшибить об стену
rus_verbs:заговорить{}, // заговорить об оплате
rus_verbs:отозваться{}, // Он отозвался об этой книге с большой похвалой.
rus_verbs:попросить{}, // попросить об услуге
rus_verbs:объявить{}, // объявить об отставке
rus_verbs:предупредить{}, // предупредить об аварии
rus_verbs:предупреждать{}, // предупреждать об опасности
rus_verbs:твердить{}, // твердить об обязанностях
rus_verbs:заявлять{}, // заявлять об экспериментальном подтверждении
rus_verbs:рассуждать{}, // рассуждать об абстрактных идеях
rus_verbs:говорить{}, // Не говорите об этом в присутствии третьих лиц.
rus_verbs:читать{}, // он читал об этом в журнале
rus_verbs:прочитать{}, // он читал об этом в учебнике
rus_verbs:узнать{}, // он узнал об этом из фильмов
rus_verbs:рассказать{}, // рассказать об экзаменах
rus_verbs:рассказывать{},
rus_verbs:договориться{}, // договориться об оплате
rus_verbs:договариваться{}, // договариваться об обмене
rus_verbs:болтать{}, // Не болтай об этом!
rus_verbs:проболтаться{}, // Не проболтайся об этом!
rus_verbs:заботиться{}, // кто заботится об урегулировании
rus_verbs:беспокоиться{}, // вы беспокоитесь об обороне
rus_verbs:помнить{}, // всем советую об этом помнить
rus_verbs:мечтать{} // Мечтать об успехе
}
fact гл_предл
{
if context { Гл_ОБ_предл предлог:об{} *:*{ падеж:предл } }
then return true
}
fact гл_предл
{
if context { * предлог:о{} @regex("[a-z]+[0-9]*") }
then return true
}
fact гл_предл
{
if context { * предлог:об{} @regex("[a-z]+[0-9]*") }
then return true
}
// остальные глаголы не могут связываться
fact гл_предл
{
if context { * предлог:об{} *:*{ падеж:предл } }
then return false, -4
}
wordentry_set Гл_ОБ_вин=
{
rus_verbs:СЛОМАТЬ{}, // потом об колено сломал (СЛОМАТЬ)
rus_verbs:разбить{}, // ты разбил щеку об угол ящика. (РАЗБИТЬ ОБ)
rus_verbs:опереться{}, // Он опёрся об стену.
rus_verbs:опираться{},
rus_verbs:постучать{}, // постучал лбом об пол.
rus_verbs:удариться{}, // бутылка глухо ударилась об землю.
rus_verbs:убиваться{}, // убиваться об стену
rus_verbs:расшибить{}, // расшибить об стену
rus_verbs:царапаться{} // Днище лодки царапалось обо что-то.
}
fact гл_предл
{
if context { Гл_ОБ_вин предлог:об{} *:*{ падеж:вин } }
then return true
}
fact гл_предл
{
if context { * предлог:об{} *:*{ падеж:вин } }
then return false,-4
}
fact гл_предл
{
if context { * предлог:об{} *:*{} }
then return false,-5
}
#endregion Предлог_ОБ
#region Предлог_О
// ------------------- С ПРЕДЛОГОМ 'О' ----------------------
wordentry_set Гл_О_Вин={
rus_verbs:шмякнуть{}, // Ей хотелось шмякнуть ими о стену.
rus_verbs:болтать{}, // Болтали чаще всего о пустяках.
rus_verbs:шваркнуть{}, // Она шваркнула трубкой о рычаг.
rus_verbs:опираться{}, // Мать приподнялась, с трудом опираясь о стол.
rus_verbs:бахнуться{}, // Бахнуться головой о стол.
rus_verbs:ВЫТЕРЕТЬ{}, // Вытащи нож и вытри его о траву. (ВЫТЕРЕТЬ/ВЫТИРАТЬ)
rus_verbs:ВЫТИРАТЬ{}, //
rus_verbs:РАЗБИТЬСЯ{}, // Прибой накатился и с шумом разбился о белый песок. (РАЗБИТЬСЯ)
rus_verbs:СТУКНУТЬ{}, // Сердце его глухо стукнуло о грудную кость (СТУКНУТЬ)
rus_verbs:ЛЯЗГНУТЬ{}, // Он кинулся наземь, покатился, и копье лязгнуло о стену. (ЛЯЗГНУТЬ/ЛЯЗГАТЬ)
rus_verbs:ЛЯЗГАТЬ{}, //
rus_verbs:звенеть{}, // стрелы уже звенели о прутья клетки
rus_verbs:ЩЕЛКНУТЬ{}, // камень щелкнул о скалу (ЩЕЛКНУТЬ)
rus_verbs:БИТЬ{}, // волна бьет о берег (БИТЬ)
rus_verbs:ЗАЗВЕНЕТЬ{}, // зазвенели мечи о щиты (ЗАЗВЕНЕТЬ)
rus_verbs:колотиться{}, // сердце его колотилось о ребра
rus_verbs:стучать{}, // глухо стучали о щиты рукояти мечей.
rus_verbs:биться{}, // биться головой о стену? (биться о)
rus_verbs:ударить{}, // вода ударила его о стену коридора. (ударила о)
rus_verbs:разбиваться{}, // волны разбивались о скалу
rus_verbs:разбивать{}, // Разбивает голову о прутья клетки.
rus_verbs:облокотиться{}, // облокотиться о стену
rus_verbs:точить{}, // точить о точильный камень
rus_verbs:спотыкаться{}, // спотыкаться о спрятавшийся в траве пень
rus_verbs:потереться{}, // потереться о дерево
rus_verbs:ушибиться{}, // ушибиться о дерево
rus_verbs:тереться{}, // тереться о ствол
rus_verbs:шмякнуться{}, // шмякнуться о землю
rus_verbs:убиваться{}, // убиваться об стену
rus_verbs:расшибить{}, // расшибить об стену
rus_verbs:тереть{}, // тереть о камень
rus_verbs:потереть{}, // потереть о колено
rus_verbs:удариться{}, // удариться о край
rus_verbs:споткнуться{}, // споткнуться о камень
rus_verbs:запнуться{}, // запнуться о камень
rus_verbs:запинаться{}, // запинаться о камни
rus_verbs:ударяться{}, // ударяться о бортик
rus_verbs:стукнуться{}, // стукнуться о бортик
rus_verbs:стукаться{}, // стукаться о бортик
rus_verbs:опереться{}, // Он опёрся локтями о стол.
rus_verbs:плескаться{} // Вода плещется о берег.
}
fact гл_предл
{
if context { Гл_О_Вин предлог:о{} *:*{ падеж:вин } }
then return true
}
fact гл_предл
{
if context { * предлог:о{} *:*{ падеж:вин } }
then return false,-5
}
wordentry_set Гл_О_предл={
rus_verbs:КРИЧАТЬ{}, // она кричала о смерти! (КРИЧАТЬ)
rus_verbs:РАССПРОСИТЬ{}, // Я расспросил о нем нескольких горожан. (РАССПРОСИТЬ/РАССПРАШИВАТЬ)
rus_verbs:РАССПРАШИВАТЬ{}, //
rus_verbs:слушать{}, // ты будешь слушать о них?
rus_verbs:вспоминать{}, // вспоминать о том разговоре ему было неприятно
rus_verbs:МОЛЧАТЬ{}, // О чём молчат девушки (МОЛЧАТЬ)
rus_verbs:ПЛАКАТЬ{}, // она плакала о себе (ПЛАКАТЬ)
rus_verbs:сложить{}, // о вас сложены легенды
rus_verbs:ВОЛНОВАТЬСЯ{}, // Я волнуюсь о том, что что-то серьёзно пошло не так (ВОЛНОВАТЬСЯ О)
rus_verbs:УПОМЯНУТЬ{}, // упомянул о намерении команды приобрести несколько новых футболистов (УПОМЯНУТЬ О)
rus_verbs:ОТЧИТЫВАТЬСЯ{}, // Судебные приставы продолжают отчитываться о борьбе с неплательщиками (ОТЧИТЫВАТЬСЯ О)
rus_verbs:ДОЛОЖИТЬ{}, // провести тщательное расследование взрыва в маршрутном такси во Владикавказе и доложить о результатах (ДОЛОЖИТЬ О)
rus_verbs:ПРОБОЛТАТЬ{}, // правительство страны больше проболтало о военной реформе (ПРОБОЛТАТЬ О)
rus_verbs:ЗАБОТИТЬСЯ{}, // Четверть россиян заботятся о здоровье путем просмотра телевизора (ЗАБОТИТЬСЯ О)
rus_verbs:ИРОНИЗИРОВАТЬ{}, // Вы иронизируете о ностальгии по тем временем (ИРОНИЗИРОВАТЬ О)
rus_verbs:СИГНАЛИЗИРОВАТЬ{}, // Кризис цен на продукты питания сигнализирует о неминуемой гиперинфляции (СИГНАЛИЗИРОВАТЬ О)
rus_verbs:СПРОСИТЬ{}, // Он спросил о моём здоровье. (СПРОСИТЬ О)
rus_verbs:НАПОМНИТЬ{}, // больной зуб опять напомнил о себе. (НАПОМНИТЬ О)
rus_verbs:осведомиться{}, // офицер осведомился о цели визита
rus_verbs:объявить{}, // В газете объявили о конкурсе. (объявить о)
rus_verbs:ПРЕДСТОЯТЬ{}, // о чем предстоит разговор? (ПРЕДСТОЯТЬ О)
rus_verbs:объявлять{}, // объявлять о всеобщей забастовке (объявлять о)
rus_verbs:зайти{}, // Разговор зашёл о политике.
rus_verbs:порассказать{}, // порассказать о своих путешествиях
инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть о неразделенной любви
деепричастие:спев{}, прилагательное:спевший{ вид:соверш },
прилагательное:спетый{},
rus_verbs:напеть{},
rus_verbs:разговаривать{}, // разговаривать с другом о жизни
rus_verbs:рассуждать{}, // рассуждать об абстрактных идеях
//rus_verbs:заботиться{}, // заботиться о престарелых родителях
rus_verbs:раздумывать{}, // раздумывать о новой работе
rus_verbs:договариваться{}, // договариваться о сумме компенсации
rus_verbs:молить{}, // молить о пощаде
rus_verbs:отзываться{}, // отзываться о книге
rus_verbs:подумывать{}, // подумывать о новом подходе
rus_verbs:поговаривать{}, // поговаривать о загадочном звере
rus_verbs:обмолвиться{}, // обмолвиться о проклятии
rus_verbs:условиться{}, // условиться о поддержке
rus_verbs:призадуматься{}, // призадуматься о последствиях
rus_verbs:известить{}, // известить о поступлении
rus_verbs:отрапортовать{}, // отрапортовать об успехах
rus_verbs:напевать{}, // напевать о любви
rus_verbs:помышлять{}, // помышлять о новом деле
rus_verbs:переговорить{}, // переговорить о правилах
rus_verbs:повествовать{}, // повествовать о событиях
rus_verbs:слыхивать{}, // слыхивать о чудище
rus_verbs:потолковать{}, // потолковать о планах
rus_verbs:проговориться{}, // проговориться о планах
rus_verbs:умолчать{}, // умолчать о штрафах
rus_verbs:хлопотать{}, // хлопотать о премии
rus_verbs:уведомить{}, // уведомить о поступлении
rus_verbs:горевать{}, // горевать о потере
rus_verbs:запамятовать{}, // запамятовать о важном мероприятии
rus_verbs:заикнуться{}, // заикнуться о прибавке
rus_verbs:информировать{}, // информировать о событиях
rus_verbs:проболтаться{}, // проболтаться о кладе
rus_verbs:поразмыслить{}, // поразмыслить о судьбе
rus_verbs:заикаться{}, // заикаться о деньгах
rus_verbs:оповестить{}, // оповестить об отказе
rus_verbs:печься{}, // печься о всеобщем благе
rus_verbs:разглагольствовать{}, // разглагольствовать о правах
rus_verbs:размечтаться{}, // размечтаться о будущем
rus_verbs:лепетать{}, // лепетать о невиновности
rus_verbs:грезить{}, // грезить о большой и чистой любви
rus_verbs:залепетать{}, // залепетать о сокровищах
rus_verbs:пронюхать{}, // пронюхать о бесплатной одежде
rus_verbs:протрубить{}, // протрубить о победе
rus_verbs:извещать{}, // извещать о поступлении
rus_verbs:трубить{}, // трубить о поимке разбойников
rus_verbs:осведомляться{}, // осведомляться о судьбе
rus_verbs:поразмышлять{}, // поразмышлять о неизбежном
rus_verbs:слагать{}, // слагать о подвигах викингов
rus_verbs:ходатайствовать{}, // ходатайствовать о выделении материальной помощи
rus_verbs:побеспокоиться{}, // побеспокоиться о правильном стимулировании
rus_verbs:закидывать{}, // закидывать сообщениями об ошибках
rus_verbs:базарить{}, // пацаны базарили о телках
rus_verbs:балагурить{}, // мужики балагурили о новом председателе
rus_verbs:балакать{}, // мужики балакали о новом председателе
rus_verbs:беспокоиться{}, // Она беспокоится о детях
rus_verbs:рассказать{}, // Кумир рассказал о криминале в Москве
rus_verbs:возмечтать{}, // возмечтать о счастливом мире
rus_verbs:вопить{}, // Кто-то вопил о несправедливости
rus_verbs:сказать{}, // сказать что-то новое о ком-то
rus_verbs:знать{}, // знать о ком-то что-то пикантное
rus_verbs:подумать{}, // подумать о чём-то
rus_verbs:думать{}, // думать о чём-то
rus_verbs:узнать{}, // узнать о происшествии
rus_verbs:помнить{}, // помнить о задании
rus_verbs:просить{}, // просить о коде доступа
rus_verbs:забыть{}, // забыть о своих обязанностях
rus_verbs:сообщить{}, // сообщить о заложенной мине
rus_verbs:заявить{}, // заявить о пропаже
rus_verbs:задуматься{}, // задуматься о смерти
rus_verbs:спрашивать{}, // спрашивать о поступлении товара
rus_verbs:догадаться{}, // догадаться о причинах
rus_verbs:договориться{}, // договориться о собеседовании
rus_verbs:мечтать{}, // мечтать о сцене
rus_verbs:поговорить{}, // поговорить о наболевшем
rus_verbs:размышлять{}, // размышлять о насущном
rus_verbs:напоминать{}, // напоминать о себе
rus_verbs:пожалеть{}, // пожалеть о содеянном
rus_verbs:ныть{}, // ныть о прибавке
rus_verbs:сообщать{}, // сообщать о победе
rus_verbs:догадываться{}, // догадываться о первопричине
rus_verbs:поведать{}, // поведать о тайнах
rus_verbs:умолять{}, // умолять о пощаде
rus_verbs:сожалеть{}, // сожалеть о случившемся
rus_verbs:жалеть{}, // жалеть о случившемся
rus_verbs:забывать{}, // забывать о случившемся
rus_verbs:упоминать{}, // упоминать о предках
rus_verbs:позабыть{}, // позабыть о своем обещании
rus_verbs:запеть{}, // запеть о любви
rus_verbs:скорбеть{}, // скорбеть о усопшем
rus_verbs:задумываться{}, // задумываться о смене работы
rus_verbs:позаботиться{}, // позаботиться о престарелых родителях
rus_verbs:докладывать{}, // докладывать о планах строительства целлюлозно-бумажного комбината
rus_verbs:попросить{}, // попросить о замене
rus_verbs:предупредить{}, // предупредить о замене
rus_verbs:предупреждать{}, // предупреждать о замене
rus_verbs:твердить{}, // твердить о замене
rus_verbs:заявлять{}, // заявлять о подлоге
rus_verbs:петь{}, // певица, поющая о лете
rus_verbs:проинформировать{}, // проинформировать о переговорах
rus_verbs:порассказывать{}, // порассказывать о событиях
rus_verbs:послушать{}, // послушать о новинках
rus_verbs:заговорить{}, // заговорить о плате
rus_verbs:отозваться{}, // Он отозвался о книге с большой похвалой.
rus_verbs:оставить{}, // Он оставил о себе печальную память.
rus_verbs:свидетельствовать{}, // страшно исхудавшее тело свидетельствовало о долгих лишениях
rus_verbs:спорить{}, // они спорили о законе
глагол:написать{ aux stress="напис^ать" }, инфинитив:написать{ aux stress="напис^ать" }, // Он написал о том, что видел во время путешествия.
глагол:писать{ aux stress="пис^ать" }, инфинитив:писать{ aux stress="пис^ать" }, // Он писал о том, что видел во время путешествия.
rus_verbs:прочитать{}, // Я прочитал о тебе
rus_verbs:услышать{}, // Я услышал о нем
rus_verbs:помечтать{}, // Девочки помечтали о принце
rus_verbs:слышать{}, // Мальчик слышал о приведениях
rus_verbs:вспомнить{}, // Девочки вспомнили о завтраке
rus_verbs:грустить{}, // Я грущу о тебе
rus_verbs:осведомить{}, // о последних достижениях науки
rus_verbs:рассказывать{}, // Антонио рассказывает о работе
rus_verbs:говорить{}, // говорим о трех больших псах
rus_verbs:идти{} // Вопрос идёт о войне.
}
fact гл_предл
{
if context { Гл_О_предл предлог:о{} *:*{ падеж:предл } }
then return true
}
// Мы поделились впечатлениями о выставке.
// ^^^^^^^^^^ ^^^^^^^^^^
fact гл_предл
{
if context { * предлог:о{} *:*{ падеж:предл } }
then return false,-3
}
fact гл_предл
{
if context { * предлог:о{} *:*{} }
then return false,-5
}
#endregion Предлог_О
#region Предлог_ПО
// ------------------- С ПРЕДЛОГОМ 'ПО' ----------------------
// для этих глаголов - запрещаем связывание с ПО+дат.п.
wordentry_set Глаг_ПО_Дат_Запр=
{
rus_verbs:предпринять{}, // предпринять шаги по стимулированию продаж
rus_verbs:увлечь{}, // увлечь в прогулку по парку
rus_verbs:закончить{},
rus_verbs:мочь{},
rus_verbs:хотеть{}
}
fact гл_предл
{
if context { Глаг_ПО_Дат_Запр предлог:по{} *:*{ падеж:дат } }
then return false,-10
}
// По умолчанию разрешаем связывание в паттернах типа
// Я иду по шоссе
fact гл_предл
{
if context { * предлог:по{} *:*{ падеж:дат } }
then return true
}
wordentry_set Глаг_ПО_Вин=
{
rus_verbs:ВОЙТИ{}, // лезвие вошло по рукоять (ВОЙТИ)
rus_verbs:иметь{}, // все месяцы имели по тридцать дней. (ИМЕТЬ ПО)
rus_verbs:материализоваться{}, // материализоваться по другую сторону барьера
rus_verbs:засадить{}, // засадить по рукоятку
rus_verbs:увязнуть{} // увязнуть по колено
}
fact гл_предл
{
if context { Глаг_ПО_Вин предлог:по{} *:*{ падеж:вин } }
then return true
}
// для остальных падежей запрещаем.
fact гл_предл
{
if context { * предлог:по{} *:*{ падеж:вин } }
then return false,-5
}
#endregion Предлог_ПО
#region Предлог_К
// ------------------- С ПРЕДЛОГОМ 'К' ----------------------
wordentry_set Гл_К_Дат={
rus_verbs:заявиться{}, // Сразу же после обеда к нам заявилась Юлия Михайловна.
rus_verbs:приставлять{} , // Приставляет дуло пистолета к виску.
прилагательное:НЕПРИГОДНЫЙ{}, // большинство компьютеров из этой партии оказались непригодными к эксплуатации (НЕПРИГОДНЫЙ)
rus_verbs:СБЕГАТЬСЯ{}, // Они чуяли воду и сбегались к ней отовсюду. (СБЕГАТЬСЯ)
rus_verbs:СБЕЖАТЬСЯ{}, // К бетонной скамье начали сбегаться люди. (СБЕГАТЬСЯ/СБЕЖАТЬСЯ)
rus_verbs:ПРИТИРАТЬСЯ{}, // Менее стойких водителей буквально сметало на другую полосу, и они впритык притирались к другим машинам. (ПРИТИРАТЬСЯ)
rus_verbs:РУХНУТЬ{}, // а потом ты без чувств рухнул к моим ногам (РУХНУТЬ)
rus_verbs:ПЕРЕНЕСТИ{}, // Они перенесли мясо к ручью и поджарили его на костре. (ПЕРЕНЕСТИ)
rus_verbs:ЗАВЕСТИ{}, // как путь мой завел меня к нему? (ЗАВЕСТИ)
rus_verbs:НАГРЯНУТЬ{}, // ФБР нагрянуло с обыском к сестре бостонских террористов (НАГРЯНУТЬ)
rus_verbs:ПРИСЛОНЯТЬСЯ{}, // Рабы ложились на пол, прислонялись к стене и спали. (ПРИСЛОНЯТЬСЯ,ПРИНОРАВЛИВАТЬСЯ,ПРИНОРОВИТЬСЯ)
rus_verbs:ПРИНОРАВЛИВАТЬСЯ{}, //
rus_verbs:ПРИНОРОВИТЬСЯ{}, //
rus_verbs:СПЛАНИРОВАТЬ{}, // Вскоре она остановила свое падение и спланировала к ним. (СПЛАНИРОВАТЬ,СПИКИРОВАТЬ,РУХНУТЬ)
rus_verbs:СПИКИРОВАТЬ{}, //
rus_verbs:ЗАБРАТЬСЯ{}, // Поэтому он забрался ко мне в квартиру с имевшимся у него полумесяцем. (ЗАБРАТЬСЯ К, В, С)
rus_verbs:ПРОТЯГИВАТЬ{}, // Оно протягивало свои длинные руки к молодому человеку, стоявшему на плоской вершине валуна. (ПРОТЯГИВАТЬ/ПРОТЯНУТЬ/ТЯНУТЬ)
rus_verbs:ПРОТЯНУТЬ{}, //
rus_verbs:ТЯНУТЬ{}, //
rus_verbs:ПЕРЕБИРАТЬСЯ{}, // Ее губы медленно перебирались к его уху. (ПЕРЕБИРАТЬСЯ,ПЕРЕБРАТЬСЯ,ПЕРЕБАЗИРОВАТЬСЯ,ПЕРЕМЕСТИТЬСЯ,ПЕРЕМЕЩАТЬСЯ)
rus_verbs:ПЕРЕБРАТЬСЯ{}, // ,,,
rus_verbs:ПЕРЕБАЗИРОВАТЬСЯ{}, //
rus_verbs:ПЕРЕМЕСТИТЬСЯ{}, //
rus_verbs:ПЕРЕМЕЩАТЬСЯ{}, //
rus_verbs:ТРОНУТЬСЯ{}, // Он отвернулся от нее и тронулся к пляжу. (ТРОНУТЬСЯ)
rus_verbs:ПРИСТАВИТЬ{}, // Он поднял одну из них и приставил верхний конец к краю шахты в потолке.
rus_verbs:ПРОБИТЬСЯ{}, // Отряд с невероятными приключениями, пытается пробиться к своему полку, попадает в плен и другие передряги (ПРОБИТЬСЯ)
rus_verbs:хотеть{},
rus_verbs:СДЕЛАТЬ{}, // Сделайте всё к понедельнику (СДЕЛАТЬ)
rus_verbs:ИСПЫТЫВАТЬ{}, // она испытывает ко мне только отвращение (ИСПЫТЫВАТЬ)
rus_verbs:ОБЯЗЫВАТЬ{}, // Это меня ни к чему не обязывает (ОБЯЗЫВАТЬ)
rus_verbs:КАРАБКАТЬСЯ{}, // карабкаться по горе от подножия к вершине (КАРАБКАТЬСЯ)
rus_verbs:СТОЯТЬ{}, // мужчина стоял ко мне спиной (СТОЯТЬ)
rus_verbs:ПОДАТЬСЯ{}, // наконец люк подался ко мне (ПОДАТЬСЯ)
rus_verbs:ПРИРАВНЯТЬ{}, // Усилия нельзя приравнять к результату (ПРИРАВНЯТЬ)
rus_verbs:ПРИРАВНИВАТЬ{}, // Усилия нельзя приравнивать к результату (ПРИРАВНИВАТЬ)
rus_verbs:ВОЗЛОЖИТЬ{}, // Путин в Пскове возложил цветы к памятнику воинам-десантникам, погибшим в Чечне (ВОЗЛОЖИТЬ)
rus_verbs:запустить{}, // Индия запустит к Марсу свой космический аппарат в 2013 г
rus_verbs:ПРИСТЫКОВАТЬСЯ{}, // Роботизированный российский грузовой космический корабль пристыковался к МКС (ПРИСТЫКОВАТЬСЯ)
rus_verbs:ПРИМАЗАТЬСЯ{}, // К челябинскому метеориту примазалась таинственная слизь (ПРИМАЗАТЬСЯ)
rus_verbs:ПОПРОСИТЬ{}, // Попросите Лизу к телефону (ПОПРОСИТЬ К)
rus_verbs:ПРОЕХАТЬ{}, // Порой школьные автобусы просто не имеют возможности проехать к некоторым населенным пунктам из-за бездорожья (ПРОЕХАТЬ К)
rus_verbs:ПОДЦЕПЛЯТЬСЯ{}, // Вагоны с пассажирами подцепляются к составу (ПОДЦЕПЛЯТЬСЯ К)
rus_verbs:ПРИЗВАТЬ{}, // Президент Афганистана призвал талибов к прямому диалогу (ПРИЗВАТЬ К)
rus_verbs:ПРЕОБРАЗИТЬСЯ{}, // Культовый столичный отель преобразился к юбилею (ПРЕОБРАЗИТЬСЯ К)
прилагательное:ЧУВСТВИТЕЛЬНЫЙ{}, // нейроны одного комплекса чувствительны к разным веществам (ЧУВСТВИТЕЛЬНЫЙ К)
безлич_глагол:нужно{}, // нам нужно к воротам (НУЖНО К)
rus_verbs:БРОСИТЬ{}, // огромный клюв бросил это мясо к моим ногам (БРОСИТЬ К)
rus_verbs:ЗАКОНЧИТЬ{}, // к пяти утра техники закончили (ЗАКОНЧИТЬ К)
rus_verbs:НЕСТИ{}, // к берегу нас несет! (НЕСТИ К)
rus_verbs:ПРОДВИГАТЬСЯ{}, // племена медленно продвигались к востоку (ПРОДВИГАТЬСЯ К)
rus_verbs:ОПУСКАТЬСЯ{}, // деревья опускались к самой воде (ОПУСКАТЬСЯ К)
rus_verbs:СТЕМНЕТЬ{}, // к тому времени стемнело (СТЕМНЕЛО К)
rus_verbs:ОТСКОЧИТЬ{}, // после отскочил к окну (ОТСКОЧИТЬ К)
rus_verbs:ДЕРЖАТЬСЯ{}, // к солнцу держались спинами (ДЕРЖАТЬСЯ К)
rus_verbs:КАЧНУТЬСЯ{}, // толпа качнулась к ступеням (КАЧНУТЬСЯ К)
rus_verbs:ВОЙТИ{}, // Андрей вошел к себе (ВОЙТИ К)
rus_verbs:ВЫБРАТЬСЯ{}, // мы выбрались к окну (ВЫБРАТЬСЯ К)
rus_verbs:ПРОВЕСТИ{}, // провел к стене спальни (ПРОВЕСТИ К)
rus_verbs:ВЕРНУТЬСЯ{}, // давай вернемся к делу (ВЕРНУТЬСЯ К)
rus_verbs:ВОЗВРАТИТЬСЯ{}, // Среди евреев, живших в диаспоре, всегда было распространено сильное стремление возвратиться к Сиону (ВОЗВРАТИТЬСЯ К)
rus_verbs:ПРИЛЕГАТЬ{}, // Задняя поверхность хрусталика прилегает к стекловидному телу (ПРИЛЕГАТЬ К)
rus_verbs:ПЕРЕНЕСТИСЬ{}, // мысленно Алёна перенеслась к заливу (ПЕРЕНЕСТИСЬ К)
rus_verbs:ПРОБИВАТЬСЯ{}, // сквозь болото к берегу пробивался ручей. (ПРОБИВАТЬСЯ К)
rus_verbs:ПЕРЕВЕСТИ{}, // необходимо срочно перевести стадо к воде. (ПЕРЕВЕСТИ К)
rus_verbs:ПРИЛЕТЕТЬ{}, // зачем ты прилетел к нам? (ПРИЛЕТЕТЬ К)
rus_verbs:ДОБАВИТЬ{}, // добавить ли ее к остальным? (ДОБАВИТЬ К)
rus_verbs:ПРИГОТОВИТЬ{}, // Матвей приготовил лук к бою. (ПРИГОТОВИТЬ К)
rus_verbs:РВАНУТЬ{}, // человек рванул ее к себе. (РВАНУТЬ К)
rus_verbs:ТАЩИТЬ{}, // они тащили меня к двери. (ТАЩИТЬ К)
глагол:быть{}, // к тебе есть вопросы.
прилагательное:равнодушный{}, // Он равнодушен к музыке.
rus_verbs:ПОЖАЛОВАТЬ{}, // скандально известный певец пожаловал к нам на передачу (ПОЖАЛОВАТЬ К)
rus_verbs:ПЕРЕСЕСТЬ{}, // Ольга пересела к Антону (ПЕРЕСЕСТЬ К)
инфинитив:СБЕГАТЬ{ вид:соверш }, глагол:СБЕГАТЬ{ вид:соверш }, // сбегай к Борису (СБЕГАТЬ К)
rus_verbs:ПЕРЕХОДИТЬ{}, // право хода переходит к Адаму (ПЕРЕХОДИТЬ К)
rus_verbs:прижаться{}, // она прижалась щекой к его шее. (прижаться+к)
rus_verbs:ПОДСКОЧИТЬ{}, // солдат быстро подскочил ко мне. (ПОДСКОЧИТЬ К)
rus_verbs:ПРОБРАТЬСЯ{}, // нужно пробраться к реке. (ПРОБРАТЬСЯ К)
rus_verbs:ГОТОВИТЬ{}, // нас готовили к этому. (ГОТОВИТЬ К)
rus_verbs:ТЕЧЬ{}, // река текла к морю. (ТЕЧЬ К)
rus_verbs:ОТШАТНУТЬСЯ{}, // епископ отшатнулся к стене. (ОТШАТНУТЬСЯ К)
rus_verbs:БРАТЬ{}, // брали бы к себе. (БРАТЬ К)
rus_verbs:СКОЛЬЗНУТЬ{}, // ковер скользнул к пещере. (СКОЛЬЗНУТЬ К)
rus_verbs:присохнуть{}, // Грязь присохла к одежде. (присохнуть к)
rus_verbs:просить{}, // Директор просит вас к себе. (просить к)
rus_verbs:вызывать{}, // шеф вызывал к себе. (вызывать к)
rus_verbs:присесть{}, // старик присел к огню. (присесть к)
rus_verbs:НАКЛОНИТЬСЯ{}, // Ричард наклонился к брату. (НАКЛОНИТЬСЯ К)
rus_verbs:выбираться{}, // будем выбираться к дороге. (выбираться к)
rus_verbs:отвернуться{}, // Виктор отвернулся к стене. (отвернуться к)
rus_verbs:СТИХНУТЬ{}, // огонь стих к полудню. (СТИХНУТЬ К)
rus_verbs:УПАСТЬ{}, // нож упал к ногам. (УПАСТЬ К)
rus_verbs:СЕСТЬ{}, // молча сел к огню. (СЕСТЬ К)
rus_verbs:ХЛЫНУТЬ{}, // народ хлынул к стенам. (ХЛЫНУТЬ К)
rus_verbs:покатиться{}, // они черной волной покатились ко мне. (покатиться к)
rus_verbs:ОБРАТИТЬ{}, // она обратила к нему свое бледное лицо. (ОБРАТИТЬ К)
rus_verbs:СКЛОНИТЬ{}, // Джон слегка склонил голову к плечу. (СКЛОНИТЬ К)
rus_verbs:СВЕРНУТЬ{}, // дорожка резко свернула к южной стене. (СВЕРНУТЬ К)
rus_verbs:ЗАВЕРНУТЬ{}, // Он завернул к нам по пути к месту службы. (ЗАВЕРНУТЬ К)
rus_verbs:подходить{}, // цвет подходил ей к лицу.
rus_verbs:БРЕСТИ{}, // Ричард покорно брел к отцу. (БРЕСТИ К)
rus_verbs:ПОПАСТЬ{}, // хочешь попасть к нему? (ПОПАСТЬ К)
rus_verbs:ПОДНЯТЬ{}, // Мартин поднял ружье к плечу. (ПОДНЯТЬ К)
rus_verbs:ПОТЕРЯТЬ{}, // просто потеряла к нему интерес. (ПОТЕРЯТЬ К)
rus_verbs:РАЗВЕРНУТЬСЯ{}, // они сразу развернулись ко мне. (РАЗВЕРНУТЬСЯ К)
rus_verbs:ПОВЕРНУТЬ{}, // мальчик повернул к ним голову. (ПОВЕРНУТЬ К)
rus_verbs:вызвать{}, // или вызвать к жизни? (вызвать к)
rus_verbs:ВЫХОДИТЬ{}, // их земли выходят к морю. (ВЫХОДИТЬ К)
rus_verbs:ЕХАТЬ{}, // мы долго ехали к вам. (ЕХАТЬ К)
rus_verbs:опуститься{}, // Алиса опустилась к самому дну. (опуститься к)
rus_verbs:подняться{}, // они молча поднялись к себе. (подняться к)
rus_verbs:ДВИНУТЬСЯ{}, // толстяк тяжело двинулся к ним. (ДВИНУТЬСЯ К)
rus_verbs:ПОПЯТИТЬСЯ{}, // ведьмак осторожно попятился к лошади. (ПОПЯТИТЬСЯ К)
rus_verbs:РИНУТЬСЯ{}, // мышелов ринулся к черной стене. (РИНУТЬСЯ К)
rus_verbs:ТОЛКНУТЬ{}, // к этому толкнул ее ты. (ТОЛКНУТЬ К)
rus_verbs:отпрыгнуть{}, // Вадим поспешно отпрыгнул к борту. (отпрыгнуть к)
rus_verbs:отступить{}, // мы поспешно отступили к стене. (отступить к)
rus_verbs:ЗАБРАТЬ{}, // мы забрали их к себе. (ЗАБРАТЬ к)
rus_verbs:ВЗЯТЬ{}, // потом возьму тебя к себе. (ВЗЯТЬ К)
rus_verbs:лежать{}, // наш путь лежал к ним. (лежать к)
rus_verbs:поползти{}, // ее рука поползла к оружию. (поползти к)
rus_verbs:требовать{}, // вас требует к себе император. (требовать к)
rus_verbs:поехать{}, // ты должен поехать к нему. (поехать к)
rus_verbs:тянуться{}, // мордой животное тянулось к земле. (тянуться к)
rus_verbs:ЖДАТЬ{}, // жди их завтра к утру. (ЖДАТЬ К)
rus_verbs:ПОЛЕТЕТЬ{}, // они стремительно полетели к земле. (ПОЛЕТЕТЬ К)
rus_verbs:подойти{}, // помоги мне подойти к столу. (подойти к)
rus_verbs:РАЗВЕРНУТЬ{}, // мужик развернул к нему коня. (РАЗВЕРНУТЬ К)
rus_verbs:ПРИВЕЗТИ{}, // нас привезли прямо к королю. (ПРИВЕЗТИ К)
rus_verbs:отпрянуть{}, // незнакомец отпрянул к стене. (отпрянуть к)
rus_verbs:побежать{}, // Cергей побежал к двери. (побежать к)
rus_verbs:отбросить{}, // сильный удар отбросил его к стене. (отбросить к)
rus_verbs:ВЫНУДИТЬ{}, // они вынудили меня к сотрудничеству (ВЫНУДИТЬ К)
rus_verbs:подтянуть{}, // он подтянул к себе стул и сел на него (подтянуть к)
rus_verbs:сойти{}, // по узкой тропинке путники сошли к реке. (сойти к)
rus_verbs:являться{}, // по ночам к нему являлись призраки. (являться к)
rus_verbs:ГНАТЬ{}, // ледяной ветер гнал их к югу. (ГНАТЬ К)
rus_verbs:ВЫВЕСТИ{}, // она вывела нас точно к месту. (ВЫВЕСТИ К)
rus_verbs:выехать{}, // почти сразу мы выехали к реке.
rus_verbs:пододвигаться{}, // пододвигайся к окну
rus_verbs:броситься{}, // большая часть защитников стен бросилась к воротам.
rus_verbs:представить{}, // Его представили к ордену.
rus_verbs:двигаться{}, // между тем чудище неторопливо двигалось к берегу.
rus_verbs:выскочить{}, // тем временем они выскочили к реке.
rus_verbs:выйти{}, // тем временем они вышли к лестнице.
rus_verbs:потянуть{}, // Мальчик схватил верёвку и потянул её к себе.
rus_verbs:приложить{}, // приложить к детали повышенное усилие
rus_verbs:пройти{}, // пройти к стойке регистрации (стойка регистрации - проверить проверку)
rus_verbs:отнестись{}, // отнестись к животным с сочуствием
rus_verbs:привязать{}, // привязать за лапу веревкой к колышку, воткнутому в землю
rus_verbs:прыгать{}, // прыгать к хозяину на стол
rus_verbs:приглашать{}, // приглашать к доктору
rus_verbs:рваться{}, // Чужие люди рвутся к власти
rus_verbs:понестись{}, // понестись к обрыву
rus_verbs:питать{}, // питать привязанность к алкоголю
rus_verbs:заехать{}, // Коля заехал к Оле
rus_verbs:переехать{}, // переехать к родителям
rus_verbs:ползти{}, // ползти к дороге
rus_verbs:сводиться{}, // сводиться к элементарному действию
rus_verbs:добавлять{}, // добавлять к общей сумме
rus_verbs:подбросить{}, // подбросить к потолку
rus_verbs:призывать{}, // призывать к спокойствию
rus_verbs:пробираться{}, // пробираться к партизанам
rus_verbs:отвезти{}, // отвезти к родителям
rus_verbs:применяться{}, // применяться к уравнению
rus_verbs:сходиться{}, // сходиться к точному решению
rus_verbs:допускать{}, // допускать к сдаче зачета
rus_verbs:свести{}, // свести к нулю
rus_verbs:придвинуть{}, // придвинуть к мальчику
rus_verbs:подготовить{}, // подготовить к печати
rus_verbs:подобраться{}, // подобраться к оленю
rus_verbs:заторопиться{}, // заторопиться к выходу
rus_verbs:пристать{}, // пристать к берегу
rus_verbs:поманить{}, // поманить к себе
rus_verbs:припасть{}, // припасть к алтарю
rus_verbs:притащить{}, // притащить к себе домой
rus_verbs:прижимать{}, // прижимать к груди
rus_verbs:подсесть{}, // подсесть к симпатичной девочке
rus_verbs:придвинуться{}, // придвинуться к окну
rus_verbs:отпускать{}, // отпускать к другу
rus_verbs:пригнуться{}, // пригнуться к земле
rus_verbs:пристроиться{}, // пристроиться к колонне
rus_verbs:сгрести{}, // сгрести к себе
rus_verbs:удрать{}, // удрать к цыганам
rus_verbs:прибавиться{}, // прибавиться к общей сумме
rus_verbs:присмотреться{}, // присмотреться к покупке
rus_verbs:подкатить{}, // подкатить к трюму
rus_verbs:клонить{}, // клонить ко сну
rus_verbs:проследовать{}, // проследовать к выходу
rus_verbs:пододвинуть{}, // пододвинуть к себе
rus_verbs:применять{}, // применять к сотрудникам
rus_verbs:прильнуть{}, // прильнуть к экранам
rus_verbs:подвинуть{}, // подвинуть к себе
rus_verbs:примчаться{}, // примчаться к папе
rus_verbs:подкрасться{}, // подкрасться к жертве
rus_verbs:привязаться{}, // привязаться к собаке
rus_verbs:забирать{}, // забирать к себе
rus_verbs:прорваться{}, // прорваться к кассе
rus_verbs:прикасаться{}, // прикасаться к коже
rus_verbs:уносить{}, // уносить к себе
rus_verbs:подтянуться{}, // подтянуться к месту
rus_verbs:привозить{}, // привозить к ветеринару
rus_verbs:подползти{}, // подползти к зайцу
rus_verbs:приблизить{}, // приблизить к глазам
rus_verbs:применить{}, // применить к уравнению простое преобразование
rus_verbs:приглядеться{}, // приглядеться к изображению
rus_verbs:приложиться{}, // приложиться к ручке
rus_verbs:приставать{}, // приставать к девчонкам
rus_verbs:запрещаться{}, // запрещаться к показу
rus_verbs:прибегать{}, // прибегать к насилию
rus_verbs:побудить{}, // побудить к действиям
rus_verbs:притягивать{}, // притягивать к себе
rus_verbs:пристроить{}, // пристроить к полезному делу
rus_verbs:приговорить{}, // приговорить к смерти
rus_verbs:склоняться{}, // склоняться к прекращению разработки
rus_verbs:подъезжать{}, // подъезжать к вокзалу
rus_verbs:привалиться{}, // привалиться к забору
rus_verbs:наклоняться{}, // наклоняться к щенку
rus_verbs:подоспеть{}, // подоспеть к обеду
rus_verbs:прилипнуть{}, // прилипнуть к окну
rus_verbs:приволочь{}, // приволочь к себе
rus_verbs:устремляться{}, // устремляться к вершине
rus_verbs:откатиться{}, // откатиться к исходным позициям
rus_verbs:побуждать{}, // побуждать к действиям
rus_verbs:прискакать{}, // прискакать к кормежке
rus_verbs:присматриваться{}, // присматриваться к новичку
rus_verbs:прижиматься{}, // прижиматься к борту
rus_verbs:жаться{}, // жаться к огню
rus_verbs:передвинуть{}, // передвинуть к окну
rus_verbs:допускаться{}, // допускаться к экзаменам
rus_verbs:прикрепить{}, // прикрепить к корпусу
rus_verbs:отправлять{}, // отправлять к специалистам
rus_verbs:перебежать{}, // перебежать к врагам
rus_verbs:притронуться{}, // притронуться к реликвии
rus_verbs:заспешить{}, // заспешить к семье
rus_verbs:ревновать{}, // ревновать к сопернице
rus_verbs:подступить{}, // подступить к горлу
rus_verbs:уводить{}, // уводить к ветеринару
rus_verbs:побросать{}, // побросать к ногам
rus_verbs:подаваться{}, // подаваться к ужину
rus_verbs:приписывать{}, // приписывать к достижениям
rus_verbs:относить{}, // относить к растениям
rus_verbs:принюхаться{}, // принюхаться к ароматам
rus_verbs:подтащить{}, // подтащить к себе
rus_verbs:прислонить{}, // прислонить к стене
rus_verbs:подплыть{}, // подплыть к бую
rus_verbs:опаздывать{}, // опаздывать к стилисту
rus_verbs:примкнуть{}, // примкнуть к деомнстрантам
rus_verbs:стекаться{}, // стекаются к стенам тюрьмы
rus_verbs:подготовиться{}, // подготовиться к марафону
rus_verbs:приглядываться{}, // приглядываться к новичку
rus_verbs:присоединяться{}, // присоединяться к сообществу
rus_verbs:клониться{}, // клониться ко сну
rus_verbs:привыкать{}, // привыкать к хорошему
rus_verbs:принудить{}, // принудить к миру
rus_verbs:уплыть{}, // уплыть к далекому берегу
rus_verbs:утащить{}, // утащить к детенышам
rus_verbs:приплыть{}, // приплыть к финишу
rus_verbs:подбегать{}, // подбегать к хозяину
rus_verbs:лишаться{}, // лишаться средств к существованию
rus_verbs:приступать{}, // приступать к операции
rus_verbs:пробуждать{}, // пробуждать лекцией интерес к математике
rus_verbs:подключить{}, // подключить к трубе
rus_verbs:подключиться{}, // подключиться к сети
rus_verbs:прилить{}, // прилить к лицу
rus_verbs:стучаться{}, // стучаться к соседям
rus_verbs:пристегнуть{}, // пристегнуть к креслу
rus_verbs:присоединить{}, // присоединить к сети
rus_verbs:отбежать{}, // отбежать к противоположной стене
rus_verbs:подвезти{}, // подвезти к набережной
rus_verbs:прибегнуть{}, // прибегнуть к хитрости
rus_verbs:приучить{}, // приучить к туалету
rus_verbs:подталкивать{}, // подталкивать к выходу
rus_verbs:прорываться{}, // прорываться к выходу
rus_verbs:увозить{}, // увозить к ветеринару
rus_verbs:засеменить{}, // засеменить к выходу
rus_verbs:крепиться{}, // крепиться к потолку
rus_verbs:прибрать{}, // прибрать к рукам
rus_verbs:пристраститься{}, // пристраститься к наркотикам
rus_verbs:поспеть{}, // поспеть к обеду
rus_verbs:привязывать{}, // привязывать к дереву
rus_verbs:прилагать{}, // прилагать к документам
rus_verbs:переправить{}, // переправить к дедушке
rus_verbs:подогнать{}, // подогнать к воротам
rus_verbs:тяготеть{}, // тяготеть к социализму
rus_verbs:подбираться{}, // подбираться к оленю
rus_verbs:подступать{}, // подступать к горлу
rus_verbs:примыкать{}, // примыкать к первому элементу
rus_verbs:приладить{}, // приладить к велосипеду
rus_verbs:подбрасывать{}, // подбрасывать к потолку
rus_verbs:перевозить{}, // перевозить к новому месту дислокации
rus_verbs:усаживаться{}, // усаживаться к окну
rus_verbs:приближать{}, // приближать к глазам
rus_verbs:попроситься{}, // попроситься к бабушке
rus_verbs:прибить{}, // прибить к доске
rus_verbs:перетащить{}, // перетащить к себе
rus_verbs:прицепить{}, // прицепить к паровозу
rus_verbs:прикладывать{}, // прикладывать к ране
rus_verbs:устареть{}, // устареть к началу войны
rus_verbs:причалить{}, // причалить к пристани
rus_verbs:приспособиться{}, // приспособиться к опозданиям
rus_verbs:принуждать{}, // принуждать к миру
rus_verbs:соваться{}, // соваться к директору
rus_verbs:протолкаться{}, // протолкаться к прилавку
rus_verbs:приковать{}, // приковать к батарее
rus_verbs:подкрадываться{}, // подкрадываться к суслику
rus_verbs:подсадить{}, // подсадить к арестонту
rus_verbs:прикатить{}, // прикатить к финишу
rus_verbs:протащить{}, // протащить к владыке
rus_verbs:сужаться{}, // сужаться к основанию
rus_verbs:присовокупить{}, // присовокупить к пожеланиям
rus_verbs:пригвоздить{}, // пригвоздить к доске
rus_verbs:отсылать{}, // отсылать к первоисточнику
rus_verbs:изготовиться{}, // изготовиться к прыжку
rus_verbs:прилагаться{}, // прилагаться к покупке
rus_verbs:прицепиться{}, // прицепиться к вагону
rus_verbs:примешиваться{}, // примешиваться к вину
rus_verbs:переселить{}, // переселить к старшекурсникам
rus_verbs:затрусить{}, // затрусить к выходе
rus_verbs:приспособить{}, // приспособить к обогреву
rus_verbs:примериться{}, // примериться к аппарату
rus_verbs:прибавляться{}, // прибавляться к пенсии
rus_verbs:подкатиться{}, // подкатиться к воротам
rus_verbs:стягивать{}, // стягивать к границе
rus_verbs:дописать{}, // дописать к роману
rus_verbs:подпустить{}, // подпустить к корове
rus_verbs:склонять{}, // склонять к сотрудничеству
rus_verbs:припечатать{}, // припечатать к стене
rus_verbs:охладеть{}, // охладеть к музыке
rus_verbs:пришить{}, // пришить к шинели
rus_verbs:принюхиваться{}, // принюхиваться к ветру
rus_verbs:подрулить{}, // подрулить к барышне
rus_verbs:наведаться{}, // наведаться к оракулу
rus_verbs:клеиться{}, // клеиться к конверту
rus_verbs:перетянуть{}, // перетянуть к себе
rus_verbs:переметнуться{}, // переметнуться к конкурентам
rus_verbs:липнуть{}, // липнуть к сокурсницам
rus_verbs:поковырять{}, // поковырять к выходу
rus_verbs:подпускать{}, // подпускать к пульту управления
rus_verbs:присосаться{}, // присосаться к источнику
rus_verbs:приклеить{}, // приклеить к стеклу
rus_verbs:подтягивать{}, // подтягивать к себе
rus_verbs:подкатывать{}, // подкатывать к даме
rus_verbs:притрагиваться{}, // притрагиваться к опухоли
rus_verbs:слетаться{}, // слетаться к водопою
rus_verbs:хаживать{}, // хаживать к батюшке
rus_verbs:привлекаться{}, // привлекаться к административной ответственности
rus_verbs:подзывать{}, // подзывать к себе
rus_verbs:прикладываться{}, // прикладываться к иконе
rus_verbs:подтягиваться{}, // подтягиваться к парламенту
rus_verbs:прилепить{}, // прилепить к стенке холодильника
rus_verbs:пододвинуться{}, // пододвинуться к экрану
rus_verbs:приползти{}, // приползти к дереву
rus_verbs:запаздывать{}, // запаздывать к обеду
rus_verbs:припереть{}, // припереть к стене
rus_verbs:нагибаться{}, // нагибаться к цветку
инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять к воротам
деепричастие:сгоняв{},
rus_verbs:поковылять{}, // поковылять к выходу
rus_verbs:привалить{}, // привалить к столбу
rus_verbs:отпроситься{}, // отпроситься к родителям
rus_verbs:приспосабливаться{}, // приспосабливаться к новым условиям
rus_verbs:прилипать{}, // прилипать к рукам
rus_verbs:подсоединить{}, // подсоединить к приборам
rus_verbs:приливать{}, // приливать к голове
rus_verbs:подселить{}, // подселить к другим новичкам
rus_verbs:прилепиться{}, // прилепиться к шкуре
rus_verbs:подлетать{}, // подлетать к пункту назначения
rus_verbs:пристегнуться{}, // пристегнуться к креслу ремнями
rus_verbs:прибиться{}, // прибиться к стае, улетающей на юг
rus_verbs:льнуть{}, // льнуть к заботливому хозяину
rus_verbs:привязываться{}, // привязываться к любящему хозяину
rus_verbs:приклеиться{}, // приклеиться к спине
rus_verbs:стягиваться{}, // стягиваться к сенату
rus_verbs:подготавливать{}, // подготавливать к выходу на арену
rus_verbs:приглашаться{}, // приглашаться к доктору
rus_verbs:причислять{}, // причислять к отличникам
rus_verbs:приколоть{}, // приколоть к лацкану
rus_verbs:наклонять{}, // наклонять к горизонту
rus_verbs:припадать{}, // припадать к первоисточнику
rus_verbs:приобщиться{}, // приобщиться к культурному наследию
rus_verbs:придираться{}, // придираться к мелким ошибкам
rus_verbs:приучать{}, // приучать к лотку
rus_verbs:промотать{}, // промотать к началу
rus_verbs:прихлынуть{}, // прихлынуть к голове
rus_verbs:пришвартоваться{}, // пришвартоваться к первому пирсу
rus_verbs:прикрутить{}, // прикрутить к велосипеду
rus_verbs:подплывать{}, // подплывать к лодке
rus_verbs:приравниваться{}, // приравниваться к побегу
rus_verbs:подстрекать{}, // подстрекать к вооруженной борьбе с оккупантами
rus_verbs:изготовляться{}, // изготовляться к прыжку из стратосферы
rus_verbs:приткнуться{}, // приткнуться к первой группе туристов
rus_verbs:приручить{}, // приручить котика к лотку
rus_verbs:приковывать{}, // приковывать к себе все внимание прессы
rus_verbs:приготовляться{}, // приготовляться к первому экзамену
rus_verbs:остыть{}, // Вода остынет к утру.
rus_verbs:приехать{}, // Он приедет к концу будущей недели.
rus_verbs:подсаживаться{},
rus_verbs:успевать{}, // успевать к стилисту
rus_verbs:привлекать{}, // привлекать к себе внимание
прилагательное:устойчивый{}, // переводить в устойчивую к перегреву форму
rus_verbs:прийтись{}, // прийтись ко двору
инфинитив:адаптировать{вид:несоверш}, // машина была адаптирована к условиям крайнего севера
инфинитив:адаптировать{вид:соверш},
глагол:адаптировать{вид:несоверш},
глагол:адаптировать{вид:соверш},
деепричастие:адаптировав{},
деепричастие:адаптируя{},
прилагательное:адаптирующий{},
прилагательное:адаптировавший{ вид:соверш },
//+прилагательное:адаптировавший{ вид:несоверш },
прилагательное:адаптированный{},
инфинитив:адаптироваться{вид:соверш}, // тело адаптировалось к условиям суровой зимы
инфинитив:адаптироваться{вид:несоверш},
глагол:адаптироваться{вид:соверш},
глагол:адаптироваться{вид:несоверш},
деепричастие:адаптировавшись{},
деепричастие:адаптируясь{},
прилагательное:адаптировавшийся{вид:соверш},
//+прилагательное:адаптировавшийся{вид:несоверш},
прилагательное:адаптирующийся{},
rus_verbs:апеллировать{}, // оратор апеллировал к патриотизму своих слушателей
rus_verbs:близиться{}, // Шторм близится к побережью
rus_verbs:доставить{}, // Эскиз ракеты, способной доставить корабль к Луне
rus_verbs:буксировать{}, // Буксир буксирует танкер к месту стоянки
rus_verbs:причислить{}, // Мы причислили его к числу экспертов
rus_verbs:вести{}, // Наша партия ведет народ к процветанию
rus_verbs:взывать{}, // Учителя взывают к совести хулигана
rus_verbs:воззвать{}, // воззвать соплеменников к оружию
rus_verbs:возревновать{}, // возревновать к поклонникам
rus_verbs:воспылать{}, // Коля воспылал к Оле страстной любовью
rus_verbs:восходить{}, // восходить к вершине
rus_verbs:восшествовать{}, // восшествовать к вершине
rus_verbs:успеть{}, // успеть к обеду
rus_verbs:повернуться{}, // повернуться к кому-то
rus_verbs:обратиться{}, // обратиться к охраннику
rus_verbs:звать{}, // звать к столу
rus_verbs:отправиться{}, // отправиться к парикмахеру
rus_verbs:обернуться{}, // обернуться к зовущему
rus_verbs:явиться{}, // явиться к следователю
rus_verbs:уехать{}, // уехать к родне
rus_verbs:прибыть{}, // прибыть к перекличке
rus_verbs:привыкнуть{}, // привыкнуть к голоду
rus_verbs:уходить{}, // уходить к цыганам
rus_verbs:привести{}, // привести к себе
rus_verbs:шагнуть{}, // шагнуть к славе
rus_verbs:относиться{}, // относиться к прежним периодам
rus_verbs:подослать{}, // подослать к врагам
rus_verbs:поспешить{}, // поспешить к обеду
rus_verbs:зайти{}, // зайти к подруге
rus_verbs:позвать{}, // позвать к себе
rus_verbs:потянуться{}, // потянуться к рычагам
rus_verbs:пускать{}, // пускать к себе
rus_verbs:отвести{}, // отвести к врачу
rus_verbs:приблизиться{}, // приблизиться к решению задачи
rus_verbs:прижать{}, // прижать к стене
rus_verbs:отправить{}, // отправить к доктору
rus_verbs:падать{}, // падать к многолетним минимумам
rus_verbs:полезть{}, // полезть к дерущимся
rus_verbs:лезть{}, // Ты сама ко мне лезла!
rus_verbs:направить{}, // направить к майору
rus_verbs:приводить{}, // приводить к дантисту
rus_verbs:кинуться{}, // кинуться к двери
rus_verbs:поднести{}, // поднести к глазам
rus_verbs:подниматься{}, // подниматься к себе
rus_verbs:прибавить{}, // прибавить к результату
rus_verbs:зашагать{}, // зашагать к выходу
rus_verbs:склониться{}, // склониться к земле
rus_verbs:стремиться{}, // стремиться к вершине
rus_verbs:лететь{}, // лететь к родственникам
rus_verbs:ездить{}, // ездить к любовнице
rus_verbs:приближаться{}, // приближаться к финише
rus_verbs:помчаться{}, // помчаться к стоматологу
rus_verbs:прислушаться{}, // прислушаться к происходящему
rus_verbs:изменить{}, // изменить к лучшему собственную жизнь
rus_verbs:проявить{}, // проявить к погибшим сострадание
rus_verbs:подбежать{}, // подбежать к упавшему
rus_verbs:терять{}, // терять к партнерам доверие
rus_verbs:пропустить{}, // пропустить к певцу
rus_verbs:подвести{}, // подвести к глазам
rus_verbs:меняться{}, // меняться к лучшему
rus_verbs:заходить{}, // заходить к другу
rus_verbs:рвануться{}, // рвануться к воде
rus_verbs:привлечь{}, // привлечь к себе внимание
rus_verbs:присоединиться{}, // присоединиться к сети
rus_verbs:приезжать{}, // приезжать к дедушке
rus_verbs:дернуться{}, // дернуться к борту
rus_verbs:подъехать{}, // подъехать к воротам
rus_verbs:готовиться{}, // готовиться к дождю
rus_verbs:убежать{}, // убежать к маме
rus_verbs:поднимать{}, // поднимать к источнику сигнала
rus_verbs:отослать{}, // отослать к руководителю
rus_verbs:приготовиться{}, // приготовиться к худшему
rus_verbs:приступить{}, // приступить к выполнению обязанностей
rus_verbs:метнуться{}, // метнуться к фонтану
rus_verbs:прислушиваться{}, // прислушиваться к голосу разума
rus_verbs:побрести{}, // побрести к выходу
rus_verbs:мчаться{}, // мчаться к успеху
rus_verbs:нестись{}, // нестись к обрыву
rus_verbs:попадать{}, // попадать к хорошему костоправу
rus_verbs:опоздать{}, // опоздать к психотерапевту
rus_verbs:посылать{}, // посылать к доктору
rus_verbs:поплыть{}, // поплыть к берегу
rus_verbs:подтолкнуть{}, // подтолкнуть к активной работе
rus_verbs:отнести{}, // отнести животное к ветеринару
rus_verbs:прислониться{}, // прислониться к стволу
rus_verbs:наклонить{}, // наклонить к миске с молоком
rus_verbs:прикоснуться{}, // прикоснуться к поверхности
rus_verbs:увезти{}, // увезти к бабушке
rus_verbs:заканчиваться{}, // заканчиваться к концу путешествия
rus_verbs:подозвать{}, // подозвать к себе
rus_verbs:улететь{}, // улететь к теплым берегам
rus_verbs:ложиться{}, // ложиться к мужу
rus_verbs:убираться{}, // убираться к чертовой бабушке
rus_verbs:класть{}, // класть к другим документам
rus_verbs:доставлять{}, // доставлять к подъезду
rus_verbs:поворачиваться{}, // поворачиваться к источнику шума
rus_verbs:заглядывать{}, // заглядывать к любовнице
rus_verbs:занести{}, // занести к заказчикам
rus_verbs:прибежать{}, // прибежать к папе
rus_verbs:притянуть{}, // притянуть к причалу
rus_verbs:переводить{}, // переводить в устойчивую к перегреву форму
rus_verbs:подать{}, // он подал лимузин к подъезду
rus_verbs:подавать{}, // она подавала соус к мясу
rus_verbs:приобщаться{}, // приобщаться к культуре
прилагательное:неспособный{}, // Наша дочка неспособна к учению.
прилагательное:неприспособленный{}, // Эти устройства неприспособлены к работе в жару
прилагательное:предназначенный{}, // Старый дом предназначен к сносу.
прилагательное:внимательный{}, // Она всегда внимательна к гостям.
прилагательное:назначенный{}, // Дело назначено к докладу.
прилагательное:разрешенный{}, // Эта книга разрешена к печати.
прилагательное:снисходительный{}, // Этот учитель снисходителен к ученикам.
прилагательное:готовый{}, // Я готов к экзаменам.
прилагательное:требовательный{}, // Он очень требователен к себе.
прилагательное:жадный{}, // Он жаден к деньгам.
прилагательное:глухой{}, // Он глух к моей просьбе.
прилагательное:добрый{}, // Он добр к детям.
rus_verbs:проявлять{}, // Он всегда проявлял живой интерес к нашим делам.
rus_verbs:плыть{}, // Пароход плыл к берегу.
rus_verbs:пойти{}, // я пошел к доктору
rus_verbs:придти{}, // придти к выводу
rus_verbs:заглянуть{}, // Я заглянул к вам мимоходом.
rus_verbs:принадлежать{}, // Это существо принадлежит к разряду растений.
rus_verbs:подготавливаться{}, // Ученики подготавливаются к экзаменам.
rus_verbs:спускаться{}, // Улица круто спускается к реке.
rus_verbs:спуститься{}, // Мы спустились к реке.
rus_verbs:пустить{}, // пускать ко дну
rus_verbs:приговаривать{}, // Мы приговариваем тебя к пожизненному веселью!
rus_verbs:отойти{}, // Дом отошёл к племяннику.
rus_verbs:отходить{}, // Коля отходил ко сну.
rus_verbs:приходить{}, // местные жители к нему приходили лечиться
rus_verbs:кидаться{}, // не кидайся к столу
rus_verbs:ходить{}, // Она простудилась и сегодня ходила к врачу.
rus_verbs:закончиться{}, // Собрание закончилось к вечеру.
rus_verbs:послать{}, // Они выбрали своих депутатов и послали их к заведующему.
rus_verbs:направиться{}, // Мы сошли на берег и направились к городу.
rus_verbs:направляться{},
rus_verbs:свестись{}, // Всё свелось к нулю.
rus_verbs:прислать{}, // Пришлите кого-нибудь к ней.
rus_verbs:присылать{}, // Он присылал к должнику своих головорезов
rus_verbs:подлететь{}, // Самолёт подлетел к лесу.
rus_verbs:возвращаться{}, // он возвращается к старой работе
глагол:находиться{ вид:несоверш }, инфинитив:находиться{ вид:несоверш }, деепричастие:находясь{},
прилагательное:находившийся{}, прилагательное:находящийся{}, // Япония находится к востоку от Китая.
rus_verbs:возвращать{}, // возвращать к жизни
rus_verbs:располагать{}, // Атмосфера располагает к работе.
rus_verbs:возвратить{}, // Колокольный звон возвратил меня к прошлому.
rus_verbs:поступить{}, // К нам поступила жалоба.
rus_verbs:поступать{}, // К нам поступают жалобы.
rus_verbs:прыгнуть{}, // Белка прыгнула к дереву
rus_verbs:торопиться{}, // пассажиры торопятся к выходу
rus_verbs:поторопиться{}, // поторопитесь к выходу
rus_verbs:вернуть{}, // вернуть к активной жизни
rus_verbs:припирать{}, // припирать к стенке
rus_verbs:проваливать{}, // Проваливай ко всем чертям!
rus_verbs:вбежать{}, // Коля вбежал ко мне
rus_verbs:вбегать{}, // Коля вбегал ко мне
глагол:забегать{ вид:несоверш }, // Коля забегал ко мне
rus_verbs:постучаться{}, // Коля постучался ко мне.
rus_verbs:повести{}, // Спросил я озорного Антонио и повел его к дому
rus_verbs:понести{}, // Мы понесли кота к ветеринару
rus_verbs:принести{}, // Я принес кота к ветеринару
rus_verbs:устремиться{}, // Мы устремились к ручью.
rus_verbs:подводить{}, // Учитель подводил детей к аквариуму
rus_verbs:следовать{}, // Я получил приказ следовать к месту нового назначения.
rus_verbs:пригласить{}, // Я пригласил к себе товарищей.
rus_verbs:собираться{}, // Я собираюсь к тебе в гости.
rus_verbs:собраться{}, // Маша собралась к дантисту
rus_verbs:сходить{}, // Я схожу к врачу.
rus_verbs:идти{}, // Маша уверенно шла к Пете
rus_verbs:измениться{}, // Основные индексы рынка акций РФ почти не изменились к закрытию.
rus_verbs:отыграть{}, // Российский рынок акций отыграл падение к закрытию.
rus_verbs:заканчивать{}, // Заканчивайте к обеду
rus_verbs:обращаться{}, // Обращайтесь ко мне в любое время
rus_verbs:окончить{}, //
rus_verbs:дозвониться{}, // Я не мог к вам дозвониться.
глагол:прийти{}, инфинитив:прийти{}, // Антонио пришел к Элеонор
rus_verbs:уйти{}, // Антонио ушел к Элеонор
rus_verbs:бежать{}, // Антонио бежит к Элеонор
rus_verbs:спешить{}, // Антонио спешит к Элеонор
rus_verbs:скакать{}, // Антонио скачет к Элеонор
rus_verbs:красться{}, // Антонио крадётся к Элеонор
rus_verbs:поскакать{}, // беглецы поскакали к холмам
rus_verbs:перейти{} // Антонио перешел к Элеонор
}
fact гл_предл
{
if context { Гл_К_Дат предлог:к{} *:*{ падеж:дат } }
then return true
}
fact гл_предл
{
if context { Гл_К_Дат предлог:к{} @regex("[a-z]+[0-9]*") }
then return true
}
// для остальных падежей запрещаем.
fact гл_предл
{
if context { * предлог:к{} *:*{} }
then return false,-5
}
#endregion Предлог_К
#region Предлог_ДЛЯ
// ------------------- С ПРЕДЛОГОМ 'ДЛЯ' ----------------------
wordentry_set Гл_ДЛЯ_Род={
частица:нет{}, // для меня нет других путей.
частица:нету{},
rus_verbs:ЗАДЕРЖАТЬ{}, // полиция может задержать их для выяснения всех обстоятельств и дальнейшего опознания. (ЗАДЕРЖАТЬ)
rus_verbs:ДЕЛАТЬСЯ{}, // это делалось для людей (ДЕЛАТЬСЯ)
rus_verbs:обернуться{}, // обернулась для греческого рынка труда банкротствами предприятий и масштабными сокращениями (обернуться)
rus_verbs:ПРЕДНАЗНАЧАТЬСЯ{}, // Скорее всего тяжелый клинок вообще не предназначался для бросков (ПРЕДНАЗНАЧАТЬСЯ)
rus_verbs:ПОЛУЧИТЬ{}, // ты можешь получить его для нас? (ПОЛУЧИТЬ)
rus_verbs:ПРИДУМАТЬ{}, // Ваш босс уже придумал для нас веселенькую смерть. (ПРИДУМАТЬ)
rus_verbs:оказаться{}, // это оказалось для них тяжелой задачей
rus_verbs:ГОВОРИТЬ{}, // теперь она говорила для нас обоих (ГОВОРИТЬ)
rus_verbs:ОСВОБОДИТЬ{}, // освободить ее для тебя? (ОСВОБОДИТЬ)
rus_verbs:работать{}, // Мы работаем для тех, кто ценит удобство
rus_verbs:СТАТЬ{}, // кем она станет для него? (СТАТЬ)
rus_verbs:ЯВИТЬСЯ{}, // вы для этого явились сюда? (ЯВИТЬСЯ)
rus_verbs:ПОТЕРЯТЬ{}, // жизнь потеряла для меня всякий смысл (ПОТЕРЯТЬ)
rus_verbs:УТРАТИТЬ{}, // мой мир утратил для меня всякое подобие смысла (УТРАТИТЬ)
rus_verbs:ДОСТАТЬ{}, // ты должен достать ее для меня! (ДОСТАТЬ)
rus_verbs:БРАТЬ{}, // некоторые берут для себя (БРАТЬ)
rus_verbs:ИМЕТЬ{}, // имею для вас новость (ИМЕТЬ)
rus_verbs:ЖДАТЬ{}, // тебя ждут для разговора (ЖДАТЬ)
rus_verbs:ПРОПАСТЬ{}, // совсем пропал для мира (ПРОПАСТЬ)
rus_verbs:ПОДНЯТЬ{}, // нас подняли для охоты (ПОДНЯТЬ)
rus_verbs:ОСТАНОВИТЬСЯ{}, // время остановилось для нее (ОСТАНОВИТЬСЯ)
rus_verbs:НАЧИНАТЬСЯ{}, // для него начинается новая жизнь (НАЧИНАТЬСЯ)
rus_verbs:КОНЧИТЬСЯ{}, // кончились для него эти игрушки (КОНЧИТЬСЯ)
rus_verbs:НАСТАТЬ{}, // для него настало время действовать (НАСТАТЬ)
rus_verbs:СТРОИТЬ{}, // для молодых строили новый дом (СТРОИТЬ)
rus_verbs:ВЗЯТЬ{}, // возьми для защиты этот меч (ВЗЯТЬ)
rus_verbs:ВЫЯСНИТЬ{}, // попытаюсь выяснить для вас всю цепочку (ВЫЯСНИТЬ)
rus_verbs:ПРИГОТОВИТЬ{}, // давай попробуем приготовить для них сюрприз (ПРИГОТОВИТЬ)
rus_verbs:ПОДХОДИТЬ{}, // берег моря мертвых подходил для этого идеально (ПОДХОДИТЬ)
rus_verbs:ОСТАТЬСЯ{}, // внешний вид этих тварей остался для нас загадкой (ОСТАТЬСЯ)
rus_verbs:ПРИВЕЗТИ{}, // для меня привезли пиво (ПРИВЕЗТИ)
прилагательное:ХАРАКТЕРНЫЙ{}, // Для всей территории края характерен умеренный континентальный климат (ХАРАКТЕРНЫЙ)
rus_verbs:ПРИВЕСТИ{}, // для меня белую лошадь привели (ПРИВЕСТИ ДЛЯ)
rus_verbs:ДЕРЖАТЬ{}, // их держат для суда (ДЕРЖАТЬ ДЛЯ)
rus_verbs:ПРЕДОСТАВИТЬ{}, // вьетнамец предоставил для мигрантов места проживания в ряде вологодских общежитий (ПРЕДОСТАВИТЬ ДЛЯ)
rus_verbs:ПРИДУМЫВАТЬ{}, // придумывая для этого разнообразные причины (ПРИДУМЫВАТЬ ДЛЯ)
rus_verbs:оставить{}, // или вообще решили оставить планету для себя
rus_verbs:оставлять{},
rus_verbs:ВОССТАНОВИТЬ{}, // как ты можешь восстановить это для меня? (ВОССТАНОВИТЬ ДЛЯ)
rus_verbs:ТАНЦЕВАТЬ{}, // а вы танцевали для меня танец семи покрывал (ТАНЦЕВАТЬ ДЛЯ)
rus_verbs:ДАТЬ{}, // твой принц дал мне это для тебя! (ДАТЬ ДЛЯ)
rus_verbs:ВОСПОЛЬЗОВАТЬСЯ{}, // мужчина из лагеря решил воспользоваться для передвижения рекой (ВОСПОЛЬЗОВАТЬСЯ ДЛЯ)
rus_verbs:СЛУЖИТЬ{}, // они служили для разговоров (СЛУЖИТЬ ДЛЯ)
rus_verbs:ИСПОЛЬЗОВАТЬСЯ{}, // Для вычисления радиуса поражения ядерных взрывов используется формула (ИСПОЛЬЗОВАТЬСЯ ДЛЯ)
rus_verbs:ПРИМЕНЯТЬСЯ{}, // Применяется для изготовления алкогольных коктейлей (ПРИМЕНЯТЬСЯ ДЛЯ)
rus_verbs:СОВЕРШАТЬСЯ{}, // Для этого совершался специальный магический обряд (СОВЕРШАТЬСЯ ДЛЯ)
rus_verbs:ПРИМЕНИТЬ{}, // а здесь попробуем применить ее для других целей. (ПРИМЕНИТЬ ДЛЯ)
rus_verbs:ПОЗВАТЬ{}, // ты позвал меня для настоящей работы. (ПОЗВАТЬ ДЛЯ)
rus_verbs:НАЧАТЬСЯ{}, // очередной денек начался для Любки неудачно (НАЧАТЬСЯ ДЛЯ)
rus_verbs:ПОСТАВИТЬ{}, // вас здесь для красоты поставили? (ПОСТАВИТЬ ДЛЯ)
rus_verbs:умереть{}, // или умерла для всяких чувств? (умереть для)
rus_verbs:ВЫБРАТЬ{}, // ты сам выбрал для себя этот путь. (ВЫБРАТЬ ДЛЯ)
rus_verbs:ОТМЕТИТЬ{}, // тот же отметил для себя другое. (ОТМЕТИТЬ ДЛЯ)
rus_verbs:УСТРОИТЬ{}, // мы хотим устроить для них школу. (УСТРОИТЬ ДЛЯ)
rus_verbs:БЫТЬ{}, // у меня есть для тебя работа. (БЫТЬ ДЛЯ)
rus_verbs:ВЫЙТИ{}, // для всего нашего поколения так вышло. (ВЫЙТИ ДЛЯ)
прилагательное:ВАЖНЫЙ{}, // именно твое мнение для нас крайне важно. (ВАЖНЫЙ ДЛЯ)
прилагательное:НУЖНЫЙ{}, // для любого племени нужна прежде всего сила. (НУЖЕН ДЛЯ)
прилагательное:ДОРОГОЙ{}, // эти места были дороги для них обоих. (ДОРОГОЙ ДЛЯ)
rus_verbs:НАСТУПИТЬ{}, // теперь для больших людей наступило время действий. (НАСТУПИТЬ ДЛЯ)
rus_verbs:ДАВАТЬ{}, // старый пень давал для этого хороший огонь. (ДАВАТЬ ДЛЯ)
rus_verbs:ГОДИТЬСЯ{}, // доброе старое время годится лишь для воспоминаний. (ГОДИТЬСЯ ДЛЯ)
rus_verbs:ТЕРЯТЬ{}, // время просто теряет для вас всякое значение. (ТЕРЯТЬ ДЛЯ)
rus_verbs:ЖЕНИТЬСЯ{}, // настало время жениться для пользы твоего клана. (ЖЕНИТЬСЯ ДЛЯ)
rus_verbs:СУЩЕСТВОВАТЬ{}, // весь мир перестал существовать для них обоих. (СУЩЕСТВОВАТЬ ДЛЯ)
rus_verbs:ЖИТЬ{}, // жить для себя или жить для них. (ЖИТЬ ДЛЯ)
rus_verbs:открыть{}, // двери моего дома всегда открыты для вас. (ОТКРЫТЫЙ ДЛЯ)
rus_verbs:закрыть{}, // этот мир будет закрыт для них. (ЗАКРЫТЫЙ ДЛЯ)
rus_verbs:ТРЕБОВАТЬСЯ{}, // для этого требуется огромное количество энергии. (ТРЕБОВАТЬСЯ ДЛЯ)
rus_verbs:РАЗОРВАТЬ{}, // Алексей разорвал для этого свою рубаху. (РАЗОРВАТЬ ДЛЯ)
rus_verbs:ПОДОЙТИ{}, // вполне подойдет для начала нашей экспедиции. (ПОДОЙТИ ДЛЯ)
прилагательное:опасный{}, // сильный холод опасен для открытой раны. (ОПАСЕН ДЛЯ)
rus_verbs:ПРИЙТИ{}, // для вас пришло очень важное сообщение. (ПРИЙТИ ДЛЯ)
rus_verbs:вывести{}, // мы специально вывели этих животных для мяса.
rus_verbs:убрать{}, // В вагонах метро для комфорта пассажиров уберут сиденья (УБРАТЬ В, ДЛЯ)
rus_verbs:оставаться{}, // механизм этого воздействия остается для меня загадкой. (остается для)
rus_verbs:ЯВЛЯТЬСЯ{}, // Чай является для китайцев обычным ежедневным напитком (ЯВЛЯТЬСЯ ДЛЯ)
rus_verbs:ПРИМЕНЯТЬ{}, // Для оценок будущих изменений климата применяют модели общей циркуляции атмосферы. (ПРИМЕНЯТЬ ДЛЯ)
rus_verbs:ПОВТОРЯТЬ{}, // повторяю для Пети (ПОВТОРЯТЬ ДЛЯ)
rus_verbs:УПОТРЕБЛЯТЬ{}, // Краски, употребляемые для живописи (УПОТРЕБЛЯТЬ ДЛЯ)
rus_verbs:ВВЕСТИ{}, // Для злостных нарушителей предложили ввести повышенные штрафы (ВВЕСТИ ДЛЯ)
rus_verbs:найтись{}, // у вас найдется для него работа?
rus_verbs:заниматься{}, // они занимаются этим для развлечения. (заниматься для)
rus_verbs:заехать{}, // Коля заехал для обсуждения проекта
rus_verbs:созреть{}, // созреть для побега
rus_verbs:наметить{}, // наметить для проверки
rus_verbs:уяснить{}, // уяснить для себя
rus_verbs:нанимать{}, // нанимать для разовой работы
rus_verbs:приспособить{}, // приспособить для удовольствия
rus_verbs:облюбовать{}, // облюбовать для посиделок
rus_verbs:прояснить{}, // прояснить для себя
rus_verbs:задействовать{}, // задействовать для патрулирования
rus_verbs:приготовлять{}, // приготовлять для проверки
инфинитив:использовать{ вид:соверш }, // использовать для достижения цели
инфинитив:использовать{ вид:несоверш },
глагол:использовать{ вид:соверш },
глагол:использовать{ вид:несоверш },
прилагательное:использованный{},
деепричастие:используя{},
деепричастие:использовав{},
rus_verbs:напрячься{}, // напрячься для решительного рывка
rus_verbs:одобрить{}, // одобрить для использования
rus_verbs:одобрять{}, // одобрять для использования
rus_verbs:пригодиться{}, // пригодиться для тестирования
rus_verbs:готовить{}, // готовить для выхода в свет
rus_verbs:отобрать{}, // отобрать для участия в конкурсе
rus_verbs:потребоваться{}, // потребоваться для подтверждения
rus_verbs:пояснить{}, // пояснить для слушателей
rus_verbs:пояснять{}, // пояснить для экзаменаторов
rus_verbs:понадобиться{}, // понадобиться для обоснования
инфинитив:адаптировать{вид:несоверш}, // машина была адаптирована для условий крайнего севера
инфинитив:адаптировать{вид:соверш},
глагол:адаптировать{вид:несоверш},
глагол:адаптировать{вид:соверш},
деепричастие:адаптировав{},
деепричастие:адаптируя{},
прилагательное:адаптирующий{},
прилагательное:адаптировавший{ вид:соверш },
//+прилагательное:адаптировавший{ вид:несоверш },
прилагательное:адаптированный{},
rus_verbs:найти{}, // Папа нашел для детей няню
прилагательное:вредный{}, // Это вредно для здоровья.
прилагательное:полезный{}, // Прогулки полезны для здоровья.
прилагательное:обязательный{}, // Этот пункт обязателен для исполнения
прилагательное:бесполезный{}, // Это лекарство бесполезно для него
прилагательное:необходимый{}, // Это лекарство необходимо для выздоровления
rus_verbs:создать{}, // Он не создан для этого дела.
прилагательное:сложный{}, // задача сложна для младших школьников
прилагательное:несложный{},
прилагательное:лёгкий{},
прилагательное:сложноватый{},
rus_verbs:становиться{},
rus_verbs:представлять{}, // Это не представляет для меня интереса.
rus_verbs:значить{}, // Я рос в деревне и хорошо знал, что для деревенской жизни значат пруд или речка
rus_verbs:пройти{}, // День прошёл спокойно для него.
rus_verbs:проходить{},
rus_verbs:высадиться{}, // большой злой пират и его отчаянные помощники высадились на необитаемом острове для поиска зарытых сокровищ
rus_verbs:высаживаться{},
rus_verbs:прибавлять{}, // Он любит прибавлять для красного словца.
rus_verbs:прибавить{},
rus_verbs:составить{}, // Ряд тригонометрических таблиц был составлен для астрономических расчётов.
rus_verbs:составлять{},
rus_verbs:стараться{}, // Я старался для вас
rus_verbs:постараться{}, // Я постарался для вас
rus_verbs:сохраниться{}, // Старик хорошо сохранился для своего возраста.
rus_verbs:собраться{}, // собраться для обсуждения
rus_verbs:собираться{}, // собираться для обсуждения
rus_verbs:уполномочивать{},
rus_verbs:уполномочить{}, // его уполномочили для ведения переговоров
rus_verbs:принести{}, // Я принёс эту книгу для вас.
rus_verbs:делать{}, // Я это делаю для удовольствия.
rus_verbs:сделать{}, // Я сделаю это для удовольствия.
rus_verbs:подготовить{}, // я подготовил для друзей сюрприз
rus_verbs:подготавливать{}, // я подготавливаю для гостей новый сюрприз
rus_verbs:закупить{}, // Руководство района обещало закупить новые комбайны для нашего села
rus_verbs:купить{}, // Руководство района обещало купить новые комбайны для нашего села
rus_verbs:прибыть{} // они прибыли для участия
}
fact гл_предл
{
if context { Гл_ДЛЯ_Род предлог:для{} *:*{ падеж:род } }
then return true
}
fact гл_предл
{
if context { Гл_ДЛЯ_Род предлог:для{} @regex("[a-z]+[0-9]*") }
then return true
}
// для остальных падежей запрещаем.
fact гл_предл
{
if context { * предлог:для{} *:*{} }
then return false,-4
}
#endregion Предлог_ДЛЯ
#region Предлог_ОТ
// попробуем иную стратегию - запретить связывание с ОТ для отдельных глаголов, разрешив для всех остальных.
wordentry_set Глаг_ОТ_Род_Запр=
{
rus_verbs:наслаждаться{}, // свободой от обязательств
rus_verbs:насладиться{},
rus_verbs:мочь{}, // Он не мог удержаться от смеха.
// rus_verbs:хотеть{},
rus_verbs:желать{},
rus_verbs:чувствовать{}, // все время от времени чувствуют его.
rus_verbs:планировать{},
rus_verbs:приняться{} // мы принялись обниматься от радости.
}
fact гл_предл
{
if context { Глаг_ОТ_Род_Запр предлог:от{} * }
then return false
}
#endregion Предлог_ОТ
#region Предлог_БЕЗ
/*
// запретить связывание с БЕЗ для отдельных глаголов, разрешив для всех остальных.
wordentry_set Глаг_БЕЗ_Род_Запр=
{
rus_verbs:мочь{}, // Он мог читать часами без отдыха.
rus_verbs:хотеть{},
rus_verbs:желать{},
rus_verbs:планировать{},
rus_verbs:приняться{}
}
fact гл_предл
{
if context { Глаг_БЕЗ_Род_Запр предлог:без{} * }
then return false
}
*/
#endregion Предлог_БЕЗ
#region Предлог_КРОМЕ
fact гл_предл
{
if context { * ПредлогДляВсе * }
then return false,-5
}
#endregion Предлог_КРОМЕ
// ------------------------------------
// По умолчанию разрешаем все остальные сочетания.
fact гл_предл
{
if context { * * * }
then return true
}
|
Наш пароход держал курс прямо на север.
|
rus_verbs:держать{},
| 5,486,541 |
[
1,
145,
256,
145,
113,
146,
235,
225,
145,
128,
145,
113,
146,
227,
145,
127,
146,
232,
145,
127,
145,
117,
225,
145,
117,
145,
118,
146,
227,
145,
119,
145,
113,
145,
124,
225,
145,
123,
146,
230,
146,
227,
146,
228,
225,
145,
128,
146,
227,
146,
242,
145,
125,
145,
127,
225,
145,
126,
145,
113,
225,
146,
228,
145,
118,
145,
115,
145,
118,
146,
227,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
436,
407,
67,
502,
2038,
30,
145,
117,
145,
118,
146,
227,
145,
119,
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
] |
pragma solidity ^0.5.8;
/**
*
* Manages data storage for a single CypherPoker hand (round), and provides some publicly-available utility functions.
*
* (C)opyright 2016
*
* This source code is protected by copyright and distributed under license.
* Please see the root LICENSE file for terms and conditions.
*
*/
contract PokerHandData {
//Single card definition including card's sorting index within the entire deck (1-52), suit value (0 to 3), and value (1 to 13 or 14 if aces are high)
struct Card {
uint index;
uint suit;
uint value;
}
//A group of Card structs.
struct CardGroup {
Card[] cards;
}
//Encryption / decryption key definition including the encryption key, decryption key, and prime modulus.
struct Key {
uint256 encKey;
uint256 decKey;
uint256 prime;
}
address public owner; //the contract's owner / publisher
address[] public authorizedGameContracts; //the "PokerHand*" contracts exclusively authorized to make changes in this contract's data. This value may only be changed when initReady is ready.
uint public numAuthorizedContracts; //set when authorizedGameContracts is set
address[] public players; //players, in order of play, who must agree to contract before game play may begin; the last player is the dealer, player 1 (index 0) is small blind, player 2 (index 2) is the big blind
uint256 public buyIn; //buy-in value, in wei, required in order to agree to the contract
mapping (address => bool) public agreed; //true for all players who agreed to this contract; only players in "players" struct may agree
uint256 public prime; //shared prime modulus
uint256 public baseCard; //base or first plaintext card in the deck (all subsequent cards are quadratic residues modulo prime)
mapping (address => uint256) public playerBets; //stores cumulative bets per betting round (reset before next)
mapping (address => uint256) public playerChips; //the players' chips, wallets, or purses on which players draw on to make bets, currently equivalent to the wei value sent to the contract.
mapping (address => bool) public playerHasBet; //true if the player has placed a bet during the current active betting round (since bets of 0 are valid)
bool public bigBlindHasBet; //set to true after initial big blind commitment in order to allow big blind to raise during first round
uint256 public pot; //total cumulative pot for hand
uint public betPosition; //current betting player index (in players array)
mapping (address => uint256[52]) public encryptedDeck; //incrementally encrypted decks; deck of players[players.length-1] is the final encrypted deck
mapping (address => uint256[2]) public privateCards; //selected encrypted private/hole cards per player
struct DecryptPrivateCardsStruct {
address sourceAddr; //the source player providing the partially decrypted cards
address targetAddr; //the target player for whom the partially decrypted cards are intended
uint256[2] cards; //the two partially decrypted private/hole cards
}
DecryptPrivateCardsStruct[] public privateDecryptCards; //stores partially decrypted private/hole cards for players
uint256[5] public publicCards; //selected encrypted public cards
mapping (address => uint256[5]) public publicDecryptCards; //stores partially decrypted public/community cards
mapping (address => Key[]) public playerKeys; //players' crypto keypairs
//Indexes to the cards comprising the players' best hands. Indexes 0 and 1 are the players' private cards and 2 to 6 are indexes
//of public cards. All five values are supplied during teh final L1Validate call and must be unique and be in the range 0 to 6 in order to be valid.
mapping (address => uint[5]) public playerBestHands;
mapping (address => Card[]) public playerCards; //final decrypted cards for players (as generated from playerBestHands)
mapping (address => uint256) public results; //hand ranks per player or numeric score representing actions (1=fold lost, 2=fold win, 3=concede loss, 4=concede win, otherwise hand score)
mapping (address => address) public declaredWinner; //address of the self-declared winner of the contract (may be challenged)
address[] public winner; //address of the hand's/contract's resolved or actual winner(s)
uint public lastActionBlock; //block number of the last valid player action that was committed. This value is set to the current block on every new valid action.
uint public timeoutBlocks; //the number of blocks that may elapse before the next valid player's (lack of) action is considered to have timed out
uint public initBlock; //the block number on which the "initialize" function was called; used to validate signed transactions
mapping (address => uint) public nonces; //unique nonces used per contract to ensure that signed transactions aren't re-used
mapping (address => uint) public validationIndex; //highest successfully completed validation index for each player
address public challenger; //the address of the current contract challenger / validation initiator
bool public complete; //contract is completed.
bool public initReady; //contract is ready for initialization call (all data reset)
/**
* Phase values:
* 0 - Agreement (not all players have agreed to contract yet)contract
* 1 - Encrypted deck storage (all players have agreed to contract)
* 2 - Private/hole cards selection
* 3 - Interim private cards decryption
* 4 - Betting
* 5 - Flop cards selection
* 6 - Interim flop cards decryption
* 7 - Betting
* 8 - Turn card selection
* 9 - Interim turn card decryption
* 10 - Betting
* 11 - River card selection
* 12 - Interim river card decryption
* 13 - Betting
* 14 - Declare winner
* 15 - Resolution
* 16 - Level 1 challenge - submit crypto keys
* 17 - Level 2 challenge - full contract verification
* 18 - Payout / hand complete
* 19 - Mid-game challenge
* 20 - Hand complete (unchallenged / signed contract game)
* 21 - Contract complete (unchallenged / signed contract game)
*/
mapping (address => uint8) public phases;
/**
* Contract constructor.
*/
constructor() public {
owner = msg.sender;
complete = true;
initReady = true; //ready for initialize
}
/**
* Modifier for functions to allow access only by addresses contained in the "authorizedGameContracts" array.
*/
modifier onlyAuthorized {
uint allowedContractsFound = 0;
for (uint count=0; count<authorizedGameContracts.length; count++) {
if (msg.sender == authorizedGameContracts[count]) {
allowedContractsFound++;
}
}
if (allowedContractsFound == 0) {
revert();
}
_;
}
/**
* Anonymous fallback function.
*/
function () external {
revert();
}
/*
* Sets the "agreed" flag to true for the transaction sender. Only accounts registered during the "initialize"
* call are allowed to agree. Once all valid players have agreed the block timeout is started and the next
* player must commit the next valid action before the timeout has elapsed.
*
* The value sent with this function invocation must equal the "buyIn" value (wei) exactly, otherwise
* an exception is thrown and any included value is refunded. Only when the buy-in value is matched exactly
* will the "agreed" flag for the player be set and the phase updated to 1.
*
* @param nonce A unique nonce to store for the player for this contract. This value must not be re-used until the contract is closed
* and paid-out in order to prevent re-use of signed transactions.
*/
function agreeToContract(uint256 nonce) payable public {
bool found = false;
for (uint count=0; count<players.length; count++) {
if (msg.sender == players[count]) {
found = true;
}
}
if (found == false) {
revert();
}
if (playerChips[msg.sender] == 0) {
if (msg.value != buyIn) {
revert();
}
//include additional validation deposit calculations here if desired
playerChips[msg.sender] = msg.value;
}
agreed[msg.sender]=true;
phases[msg.sender]=1;
playerBets[msg.sender] = 0;
playerHasBet[msg.sender] = false;
validationIndex[msg.sender] = 0;
nonces[msg.sender] = nonce;
}
/**
* Initializes the data contract.
*
* @param primeVal The shared prime modulus on which plaintext card values are based and from which encryption/decryption keys are derived.
* @param baseCardVal The value of the base or first card of the plaintext deck. The next 51 ascending quadratic residues modulo primeVal are assumed to
* comprise the remainder of the deck (see "getCardIndex" for calculations).
* @param buyInVal The exact per-player buy-in value, in wei, that must be sent when agreeing to the contract. Must be greater than 0.
* @param timeoutBlocksVal The number of blocks that elapse between the current block and lastActionBlock before the current valid player is
* considered to have timed / dropped out if they haven't committed a valid action. A minimum of 2 blocks (roughly 24 seconds), is imposed but
* a slightly higher value is highly recommended.
*
*/
function initialize(uint256 primeVal, uint256 baseCardVal, uint256 buyInVal, uint timeoutBlocksVal) public onlyAuthorized {
prime = primeVal;
baseCard = baseCardVal;
buyIn = buyInVal;
timeoutBlocks = timeoutBlocksVal;
initBlock = block.number;
initReady = false;
}
/**
* Accesses partially decrypted private/hole cards for a player that has agreed to the contract.
*
* @param sourceAddr The source player that provided the partially decrypted cards for the target.
* @param targetAddr The target player for whom the partially descrypted cards were intended.
* @param cardIndex The index of the card (0 or 1) to retrieve.
*
* @return The partially decrypted private card record found at the specified index for the specified player.
*/
function getPrivateDecryptCard(address sourceAddr, address targetAddr, uint cardIndex) view public returns (uint256) {
for (uint8 count=0; count < privateDecryptCards.length; count++) {
if ((privateDecryptCards[count].sourceAddr == sourceAddr) && (privateDecryptCards[count].targetAddr == targetAddr)) {
return (privateDecryptCards[count].cards[cardIndex]);
}
}
}
/**
* Checks if all valild/agreed players are at a specific game phase.
*
* @param phaseNum The phase number that all agreed players should be at.
*
* @return True if all agreed players are at the specified game phase, false otherwise.
*/
function allPlayersAtPhase(uint phaseNum) public view returns (bool) {
for (uint count=0; count < players.length; count++) {
if (phases[players[count]] != phaseNum) {
return (false);
}
}
return (true);
}
//---------------------------------------------------
// PUBLICLY ACCESSIBLE UTILITY FUNCTIONS
//---------------------------------------------------
/**
* @return The number of players in the 'players' array.
*/
function num_Players() public view returns (uint) {
return (players.length);
}
/**
* @param target The address of the target agreed player for which to retrieve the number of stored keypairs.
*
* @return The number of keypairs stored for the target player address.
*/
function num_Keys(address target) public view returns (uint) {
return (playerKeys[target].length);
}
/**
* @param target The address of the target agreed player for which to retrieve the number of cards in the 'playerCards' array.
*
* @return The number of cards stored for the target player in the 'playerCards' array.
*/
function num_PlayerCards(address target) public view returns (uint) {
return (playerCards[target].length);
}
/**
* @param targetAddr The address of the target agreed player for which to retrieve the number of cards in the 'privateCards' array.
*
* @return The number of cards stored for the target player in the 'privateCards' array.
*/
function num_PrivateCards(address targetAddr) public returns (uint) {
return (DataUtils.arrayLength2(privateCards[targetAddr]));
}
/**
* @return The number of cards stored in the 'publicCards' array.
*/
function num_PublicCards() public returns (uint) {
return (DataUtils.arrayLength5(publicCards));
}
/**
* @param sourceAddr The source or sending address of the player who stored the partially-decrypted private cards for the
* player specified by the 'targetAddr' address.
* @param targetAddr The target address of the player for whom the partially-decrypted cards are being stored by the 'sourceAddr'
* player's address.
*
* @return The number of partially-decrypted private cards stored for the 'targetAddr' player by the 'sourceAddr' player.
*/
function num_PrivateDecryptCards(address sourceAddr, address targetAddr) public returns (uint) {
for (uint8 count=0; count < privateDecryptCards.length; count++) {
if ((privateDecryptCards[count].sourceAddr == sourceAddr) && (privateDecryptCards[count].targetAddr == targetAddr)) {
return (privateDecryptCards[count].cards.length);
}
}
return (0);
}
/**
* @return The number of addresses stored in the 'winner' array.
*/
function num_winner() public returns (uint) {
return (winner.length);
}
/**
* Sets the 'authorizedGameContracts' array to the specified addresses. The 'initReady' and 'complete' flags must
* be trued before this function is invoked otherwise an exception is thrown.
*
* @param contractAddresses An array of addresses that are to be authorized to invoke functions in this contract once it's
* been initialized. Typically these are addresses of external "PokerHand*" contracts but may include standard account
* addresses as well.
*/
function setAuthorizedGameContracts (address[] memory contractAddresses) public {
if ((initReady == false) || (complete == false)) {
revert();
}
authorizedGameContracts=contractAddresses;
numAuthorizedContracts = authorizedGameContracts.length;
}
//---------------------------------------------------
// AUTHORIZED CONTRACT / ADDRESS UTILITY FUNCTIONS
//---------------------------------------------------
/**
* Adds a card for a specific player to the end of the 'playerCards' array.
*
* @param playerAddress The target address of the agreed player for whom to store the card.
* @param index The index value of the card to store.
* @param suit The suit value of the card to store.
* @param value The face value of the card to store.
*/
function add_playerCard(address playerAddress, uint index, uint suit, uint value) public onlyAuthorized {
playerCards[playerAddress].push(Card(index, suit, value));
}
/**
* Updates a card for a specific player within the 'playerCards' array.
*
* @param playerAddress The target address of the agreed player for whom to update the card.
* @param cardIndex The index of the card within the 'playerCards' array for the 'playerAddress' player.
* @param index The index value of the card to update.
* @param suit The suit value of the card to update.
* @param value The face value of the card to update.
*/
function update_playerCard(address playerAddress, uint cardIndex, uint index, uint suit, uint value) public onlyAuthorized {
playerCards[playerAddress][cardIndex].index = index;
playerCards[playerAddress][cardIndex].suit = suit;
playerCards[playerAddress][cardIndex].value = value;
}
/**
* Sets the validation index value for a specific player address.
*
* @param playerAddress The address of the player to set the validation index value for.
* @param index The validation index value to set.
*/
function set_validationIndex(address playerAddress, uint index) public onlyAuthorized {
if (index == 0) {
} else {
validationIndex[playerAddress] = index;
}
}
/**
* Sets or resets a result value for an agreed player in the 'results' array.
*
* @param playerAddress The address of the player to set the result for.
* @param result The result value to set. If 0 the entry is removed from the 'results' array.
*/
function set_result(address playerAddress, uint256 result) public onlyAuthorized {
if (result == 0) {
delete results[playerAddress];
} else {
results[playerAddress] = result;
}
}
/**
* Sets the 'complete' flag value.
*
* @param completeSet The value to set the 'complete' flag to.
*/
function set_complete (bool completeSet) public onlyAuthorized {
complete = completeSet;
}
/**
* Sets a public card value in the 'publicCards' array.
*
* @param card The card value to set.
* @param index The index within the 'publicCards' array to set the value to.
*/
function set_publicCard (uint256 card, uint index) public onlyAuthorized {
publicCards[index] = card;
}
/**
* Adds newly encrypted cards for an address or clears out the 'encryptedDeck' data for the address.
*
* @param fromAddr The target address of the player for which to set the encrypted cdeck values.
* @param cards The array of cards encrypted by the 'fromAddr' player to store in the 'encryptedDeck' array. If this is
* an empty array the elements for the 'fromAddr' player address are cleared from the 'encryptedDeck' array.
*/
function set_encryptedDeck (address fromAddr, uint256[] memory cards) public onlyAuthorized {
if (cards.length == 0) {
/*
for (uint count2=0; count2<52; count2++) {
delete encryptedDeck[fromAddr][count2];
}
*/
delete encryptedDeck[fromAddr];
} else {
for (uint8 count=0; count < cards.length; count++) {
encryptedDeck[fromAddr][DataUtils.arrayLength52(encryptedDeck[fromAddr])] = cards[count];
}
}
}
/**
* Adds or resets private card selection(s) for a player address to the 'privateCards' array.
*
* @param fromAddr The player address for which to add private card selections.
* @param cards The card(s) to add to the 'privateCards' array for the 'fromAddr' player address. If this is an
* empty array the existing elements in 'privateCards' for the 'fromAddr' address are cleared.
*/
function set_privateCards (address fromAddr, uint256[] memory cards) public onlyAuthorized {
if (cards.length == 0) {
for (uint8 count=0; count<2; count++) {
delete privateCards[fromAddr][count];
}
delete privateCards[fromAddr];
for (uint8 count= 0; count<playerCards[fromAddr].length; count++) {
delete playerCards[fromAddr][count];
}
delete playerCards[fromAddr];
} else {
for (uint8 count=0; count<cards.length; count++) {
privateCards[fromAddr][DataUtils.arrayLength2(privateCards[fromAddr])] = cards[count];
}
}
}
/**
* Sets the betting position as an offset within the players array. The current betting player address is 'players[betPosition]'.
*
* @param betPositionVal The bet position value to assign to the 'betPosition' variable.
*/
function set_betPosition (uint betPositionVal) public onlyAuthorized {
betPosition = betPositionVal;
}
/**
* Sets the 'bigBlindHasBet' flag value. When true this flag indicates that at least one complete round of betting has completed.
*
* @param bigBlindHasBetVal The value to assign to the 'bigBlindHasBet' variable.
*
*/
function set_bigBlindHasBet (bool bigBlindHasBetVal) public onlyAuthorized {
bigBlindHasBet = bigBlindHasBetVal;
}
/**
* Sets the 'playerHasBet' flag for a specific agreed player address. When true this flag indicates that the associated player
* has bet during this round of betting.
*
* @param fromAddr The agreed player address to set the 'playerHasBet' flag for.
* @param hasBet The value to assign to the 'playerHasBet' array for the 'fromAddr' player address.
*/
function set_playerHasBet (address fromAddr, bool hasBet) public onlyAuthorized {
playerHasBet[fromAddr] = hasBet;
}
/**
* Sets the bet value for a player in the 'playerBets' array.
*
* @param fromAddr The address of the agreed player for which to set the bet value.
* @param betVal The bet value, in wei, to set for the 'fromAddr' player address.
*/
function set_playerBets (address fromAddr, uint betVal) public onlyAuthorized {
playerBets[fromAddr] = betVal;
}
/**
* Sets the chips value for a player in the 'playerChips' array.
*
* @param forAddr The agreed player address for which to set the chips value.
* @param numChips The number of chips, in wei, to set for the 'forAddr' player address.
*/
function set_playerChips (address forAddr, uint numChips) public onlyAuthorized {
playerChips[forAddr] = numChips;
}
/**
* Sets the 'pot' variable value.
*
* @param potVal The pot value, in wei, to assign to the 'pot' variable.
*/
function set_pot (uint potVal) public onlyAuthorized {
pot = potVal;
}
/**
* Sets the contract agreed value of a player in the 'agreed' array.
*
* @param fromAddr The address of the player for which to set the agreement flag. This player should
* appear in the 'players' array.
* @param agreedVal The value to assign to the 'agreed' array for the 'fromAddr' player address.
*/
function set_agreed (address fromAddr, bool agreedVal) public onlyAuthorized {
agreed[fromAddr] = agreedVal;
}
/**
* Adds a winning player's address to the end of the 'winner' array.
*
* @param winnerAddress The agreed player address to add to the end of the 'winner' array.
*/
function add_winner (address winnerAddress) public onlyAuthorized {
winner.push(winnerAddress);
}
/**
* Clears/resets the contents of the 'winner' array.
*/
function clear_winner () public onlyAuthorized {
winner.length=0;
}
/**
* Sets or resets the 'players' array with the addresses supplied, optionally resetting 'nonces' and 'initReady' values.
*
* @param newPlayers The addresses of the players to assign to the 'players' array. Each of these
* addresses must agree to the contract before a game can begin. If an empty array is supplied, the 'players'
* and 'nonces' arrays are cleared/reset, and the 'initReady' flag is set to true.
*/
function new_players (address[] memory newPlayers) public onlyAuthorized {
if (newPlayers.length == 0) {
for (uint count=0; count<players.length; count++) {
delete nonces[players[count]];
}
}
players = newPlayers;
if (newPlayers.length == 0) {
initReady=true;
}
}
/**
* Sets the game phase in the 'phases' array for a specific player address.
*
* @param fromAddr The agreed player address for which to set the phase value.
* @param phaseNum The phase number to set for the 'fromAddr' player address.
*/
function set_phase (address fromAddr, uint8 phaseNum) public onlyAuthorized {
phases[fromAddr] = phaseNum;
}
/**
* Sets the last action block time value, 'lastActionBlock', for this contract.
*
* @param blockNum The block number to assign to the 'lastActionlock' variable.
*/
function set_lastActionBlock(uint blockNum) public onlyAuthorized {
lastActionBlock = blockNum;
}
/**
* Sets or resets the partial private card decryptions in the 'privateDecryptCards' array for a player address from a decrypting player.
*
* @param fromAddr The sending or decrypting agreed player address that is supplying the partially-decrypted card values.
* @param cards The partially-decrypted cards being stored for the 'targetAddr' player address. If this is an empty array
* all of the elements of 'privateDecryptCards' are cleared / reset (for all players).
* @param targetAddr The target agreed player address to whom the partially-decrypted card selections belong.
*/
function set_privateDecryptCards (address fromAddr, uint256[] memory cards, address targetAddr) public onlyAuthorized {
if (cards.length == 0) {
for (uint8 count=0; count < privateDecryptCards.length; count++) {
delete privateDecryptCards[count];
}
} else {
uint structIndex = privateDecryptCardsIndex(fromAddr, targetAddr);
for (uint8 count=0; count < cards.length; count++) {
privateDecryptCards[structIndex].cards[DataUtils.arrayLength2(privateDecryptCards[structIndex].cards)] = cards[count];
}
}
}
/**
* Adds or resets encrypted public card selections to the 'publicCards' array.
*
* @param fromAddr The sending agreed player address storing the public card values.
* @param cards The encrypted public card(s) selection(s) to add to the 'publicCards' array. If this array is empty then the entire
* 'publicCards' array is reset.
*/
function set_publicCards (address fromAddr, uint256[] memory cards) public onlyAuthorized {
if (cards.length == 0) {
for (uint8 count = 0; count < 5; count++) {
publicCards[count]=1;
}
} else {
for (uint8 count=0; count < cards.length; count++) {
publicCards[DataUtils.arrayLength5(publicCards)] = cards[count];
}
}
}
/**
* Stores up to 5 partially decrypted public or community cards from a target player. The player must must have agreed to the
* contract, and must be at phase 6, 9, or 12. Multiple invocations may be used to store cards during the multi-card
* phase (6) if desired.
*
* In order to correlate decryptions during subsequent rounds cards are stored at matching indexes for players involved.
* To illustrate this, in the following example players 1 and 2 decrypted the first three cards and players 2 and 3 decrypted the following
* two cards:
*
* publicDecryptCards(player 1) = [0x32] [0x22] [0x5A] [ 0x0] [ 0x0] <- partially decrypted only the first three cards
* publicDecryptCards(player 2) = [0x75] [0xF5] [0x9B] [0x67] [0xF1] <- partially decrypted all five cards
* publicDecryptCards(player 3) = [ 0x0] [ 0x0] [ 0x0] [0x1C] [0x22] <- partially decrypted only the last two cards
*
* The number of players involved in the partial decryption of any card at a specific index should be the total number of players minus one
* (players.length - 1), since the final decryption results in the fully decrypted card and therefore doesn't need to be stored.
*
* @param fromAddr The sending or decrypting agreed player storing the partially-decrypted public card values.
* @param cards The partially-decrypted card value(s) to store. If this parameter is an empty array the 'publicDecrypCards' and
* 'playerBestHands' arrays are reset/cleared.
*/
function set_publicDecryptCards (address fromAddr, uint256[] memory cards) public onlyAuthorized {
if (cards.length == 0) {
/*
for (uint count=0; count<5; count++) {
delete publicDecryptCards[fromAddr][count];
delete playerBestHands[fromAddr][count];
}
*/
delete publicDecryptCards[fromAddr];
delete playerBestHands[fromAddr];
} else {
(uint maxLength, uint playersAtMaxLength) = publicDecryptCardsInfo();
//adjust maxLength value to use as index
if ((playersAtMaxLength < (players.length - 1)) && (maxLength > 0)) {
maxLength--;
}
for (uint count=0; count < cards.length; count++) {
publicDecryptCards[fromAddr][maxLength] = cards[count];
maxLength++;
}
}
}
/**
* Sets the 'declaredWinner' address declared by a player.
*
* @param fromAddr The agreed player address storing a declared winner address.
* @param winnerAddr The declared agreed player address being stored by the 'fromAddr' player address.
*/
function add_declaredWinner(address fromAddr, address winnerAddr) public onlyAuthorized {
if (winnerAddr == address(0)) {
delete declaredWinner[fromAddr];
} else {
declaredWinner[fromAddr] = winnerAddr;
}
}
/**
* Returns the index / position of the 'privateDecryptCards' struct for a specific source and target player address
* combination. If the combination doesn't exist it is created and the index of the new element is returned.
*
* @param sourceAddr The address of the source or sending player.
* @param targetAddr The address of the target player to whom the associated partially decrypted cards belong.
*
* @return The index of the element within the privateDecryptCards array that matched the source and target addresses.
* The element may be new if no matching element can be found.
*/
function privateDecryptCardsIndex (address sourceAddr, address targetAddr) public onlyAuthorized returns (uint) {
for (uint count=0; count < privateDecryptCards.length; count++) {
if ((privateDecryptCards[count].sourceAddr == sourceAddr) && (privateDecryptCards[count].targetAddr == targetAddr)) {
return (count);
}
}
//none found, create a new one
uint256[2] memory tmp;
privateDecryptCards.push(DecryptPrivateCardsStruct(sourceAddr, targetAddr, tmp));
return (privateDecryptCards.length - 1);
}
/**
* Sets an encrypted card in the 'playerBestHands' array for a specific player address.
*
* @param fromAddr The player for which to store the encrypted card.
* @param cardIndex The 0-based card index within the 'playerBestHands' array for the 'fromAddr' address to set.
* @param card The encrypted card value to set for the 'fromAddr' player at index 'cardIndex' within the 'playerBestHands' array.
*/
function set_playerBestHands(address fromAddr, uint cardIndex, uint256 card) public onlyAuthorized {
playerBestHands[fromAddr][cardIndex] = card;
}
/**
* Adds encryption and decryption keys to the 'playerKeys' array for an agreed player address.
*
* @param fromAddr The agreed player address for which to set the encryption and decryption keys.
* @param encKeys The encryption keys to store for the 'fromAddr' player address.
* @param decKeys The decryption keys to store for the 'fromAddr' player address.
*/
function add_playerKeys(address fromAddr, uint256[] memory encKeys, uint256[] memory decKeys) public onlyAuthorized {
//caller guarantees that the number of encryption keys matches number decryption keys
for (uint count=0; count<encKeys.length; count++) {
playerKeys[fromAddr].push(Key(encKeys[count], decKeys[count], prime));
}
}
/**
* Deletes / clears the 'playerKeys' array for an agreed player address.
*
* @param fromAddr The agreed player address for which to clear entries (encryption and decryption keys), from the 'playerKeys' array.
*/
function remove_playerKeys(address fromAddr) public onlyAuthorized {
delete playerKeys[fromAddr];
}
/**
* Sets the 'challenger' address.
*
* @param challengerAddr The address of the challenging player to assign to the 'challenger' variable.
*/
function set_challenger(address challengerAddr) public onlyAuthorized {
challenger = challengerAddr;
}
/**
* Send an amount, up to and including the current contract's value, to an address. This address does not need to be a player address.
*
* @param toAddr The address to send some or all of the contract's value to.
* @param amount The amount, in wei, to send to the 'toAddr' address.
*
* @return The result of the "toAddr.send" operation.
*/
function pay (address payable toAddr, uint amount) public onlyAuthorized returns (bool) {
if (toAddr.send(amount)) {
return (true);
}
return (false);
}
/**
* @return Information about the 'publicDecryptCards' array. The tuple includes a 'maxLength' property which
* is the maximum length of 'publicDecryptCards' for all agreed players (some players may have stored fewer cards), and
* 'playersAtMaxLength' which is a count of players that have stored 'maxLength' cards in the 'publicDecryptCards' array.
*/
function publicDecryptCardsInfo() public returns (uint maxLength, uint playersAtMaxLength) {
uint currentLength = 0;
maxLength = 0;
for (uint8 count=0; count < players.length; count++) {
currentLength = DataUtils.arrayLength5(publicDecryptCards[players[count]]);
if (currentLength > maxLength) {
maxLength = currentLength;
}
}
playersAtMaxLength = 0;
for (uint8 count=0; count < players.length; count++) {
currentLength = DataUtils.arrayLength5(publicDecryptCards[players[count]]);
if (currentLength == maxLength) {
playersAtMaxLength++;
}
}
}
/**
* Returns the length number of elements stored by a player address in the 'encryptedDeck' array.
*
* @param fromAddr The address for which to retrieve the number of stored elements.
*
* @return The number of elements stored by 'fromAddr' in the 'encryptedDeck' array.
*/
function length_encryptedDeck(address fromAddr) public returns (uint) {
return (DataUtils.arrayLength52(encryptedDeck[fromAddr]));
}
}
library DataUtils {
/**
* Returns the number of elements in a non-dynamic, 52-element array. The final element in the array that is
* greater than 1 is considered the end of the array even if all preceeding elements are less than 2.
*
* @param inputArray The non-dynamic storage array to check for length.
*
*/
function arrayLength52(uint[52] memory inputArray) internal returns (uint) {
for (uint count=52; count>0; count--) {
if ((inputArray[count-1] > 1)) {
return (count);
}
}
return (0);
}
/**
* Returns the number of elements in a non-dynamic, 5-element array. The final element in the array that is
* greater than 1 is considered the end of the array even if all preceeding elements are less than 2.
*
* @param inputArray The non-dynamic storage array to check for length..
*
*/
function arrayLength5(uint[5] memory inputArray) internal returns (uint) {
for (uint count=5; count>0; count--) {
if ((inputArray[count-1] > 1)) {
return (count);
}
}
return (0);
}
/**
* Returns the number of elements in a non-dynamic, 2-element array. The final element in the array that is
* greater than 1 is considered the end of the array even if all preceeding elements are less than 2.
*
* @param inputArray The non-dynamic storage array to check for length.
*
*/
function arrayLength2(uint[2] memory inputArray) internal returns (uint) {
for (uint count=2; count>0; count--) {
if ((inputArray[count-1] > 1)) {
return (count);
}
}
return (0);
}
}
contract PokerHandValidator {
struct Card {
uint index;
uint suit;
uint value;
}
struct Key {
uint256 encKey;
uint256 decKey;
uint256 prime;
}
address public owner;
address public lastSender;
PokerHandData public pokerHandData;
Card[5] public workCards;
Card[] public sortedGroup;
Card[][] public sortedGroups;
Card[][15] public cardGroups;
// function PokerHandValidator () {}
function () external {}
modifier isAuthorized {
PokerHandData handData = PokerHandData(msg.sender);
bool found = false;
for (uint count=0; count<handData.numAuthorizedContracts(); count++) {
if (handData.authorizedGameContracts(count) == msg.sender) {
found = true;
break;
}
}
if (!found) {
revert();
}
_;
}
function challenge (address dataAddr, address challenger) public isAuthorized returns (bool) {}
function validate(address dataAddr, address msgSender) public isAuthorized returns (bool) {}
function decryptCard(address target, uint cardIndex) private {}
function validateCard(address target, uint cardIndex) private {}
function generateScore(address target) private {}
function checkDecryptedCard (address sender, uint256 cardValue) private returns (bool) {}
function modExp(uint256 base, uint256 exp, uint256 mod) internal returns (uint256 result) {}
function getCardIndex(uint256 value, uint256 baseCard, uint256 prime) public view returns (uint256 index) {}
function calculateHandScore() private returns (uint256) {}
function groupWorkCards(bool byValue) private {}
function clearGroups() private {}
function sortWorkCards(bool acesHigh) private {}
function scoreStraights(bool acesHigh) private returns (uint256) {}
function scoreGroups(bool valueGroups, bool acesHigh) private returns (uint256) {}
function checkGroupExists(uint8 memberCount) private returns (bool) {}
function addCardValues(uint256 startingValue, bool acesHigh) private returns (uint256) {}
function getSortedGroupLength32(uint8 index) private returns (uint32) {}
}
|
A group of Card structs.
|
struct CardGroup {
Card[] cards;
}
| 15,866,838 |
[
1,
37,
1041,
434,
14338,
8179,
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,
202,
1697,
14338,
1114,
288,
203,
4202,
14338,
8526,
18122,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.11;
import "zeppelin-solidity/contracts/token/StandardToken.sol";
/**
* @title Burnable
*
* @dev Standard ERC20 token
*/
contract Burnable is StandardToken {
using SafeMath for uint;
/* This notifies clients about the amount burnt */
event Burn(address indexed from, uint256 value);
function burn(uint256 _value) returns (bool success) {
require(balances[msg.sender] >= _value); // Check if the sender has enough
balances[msg.sender] = balances[msg.sender].sub(_value);// Subtract from the sender
totalSupply = totalSupply.sub(_value); // Updates totalSupply
Burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) returns (bool success) {
require(balances[_from] >= _value); // Check if the sender has enough
require(_value <= allowed[_from][msg.sender]); // Check allowance
balances[_from] = balances[_from].sub(_value); // Subtract from the sender
totalSupply = totalSupply.sub(_value); // Updates totalSupply
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Burn(_from, _value);
return true;
}
function transfer(address _to, uint _value) returns (bool success) {
require(_to != 0x0); //use burn
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint _value) returns (bool success) {
require(_to != 0x0); //use burn
return super.transferFrom(_from, _to, _value);
}
}
|
Subtract from the sender
|
balances[msg.sender] = balances[msg.sender].sub(_value);
| 1,760,721 |
[
1,
27904,
628,
326,
5793,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
324,
26488,
63,
3576,
18,
15330,
65,
273,
324,
26488,
63,
3576,
18,
15330,
8009,
1717,
24899,
1132,
1769,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/80001/0x152aF7cC4960193b744f53BEAA80f6BD3FFdaB3E/sources/contracts/EthBio.sol
|
Remember to implement the access control function example implementation:
|
function _canSetContractURI() internal view override onlyOwner returns (bool) {
return true;
}
| 9,440,501 |
[
1,
28810,
358,
2348,
326,
2006,
3325,
445,
3454,
4471,
30,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
4169,
694,
8924,
3098,
1435,
2713,
1476,
3849,
1338,
5541,
1135,
261,
6430,
13,
288,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x0CCd2Cc53fd94A65867d33BcC19064a59572bd5e/sources/contracts/MyFLashLoan.sol
|
import './interfaces/IERC20.sol';
|
import '@uniswap/lib/contracts/libraries/FullMath.sol';
| 844,917 |
[
1,
5666,
12871,
15898,
19,
45,
654,
39,
3462,
18,
18281,
13506,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5666,
4622,
318,
291,
91,
438,
19,
2941,
19,
16351,
87,
19,
31417,
19,
5080,
10477,
18,
18281,
13506,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x4A50456D5Fc24C6399A90e122366F73C0679416c/sources/contracts/NFTFactory.sol
|
* @dev Function to change the proxy admin for future collections, callable only by owner @param _newProxyAdmin New proxy admin address/
|
function changeProxyAdmin(address _newProxyAdmin) external onlyOperator {
if (_newProxyAdmin == address(0)) revert NFTFactoryNewProxyAdminIsZeroAddress();
if (_newProxyAdmin == proxyAdmin) revert NFTFactoryNewProxyAdminIsSameAddress();
proxyAdmin = _newProxyAdmin;
emit ProxyAdminChanged(_newProxyAdmin);
}
| 1,917,027 |
[
1,
2083,
358,
2549,
326,
2889,
3981,
364,
3563,
6980,
16,
4140,
1338,
635,
3410,
225,
389,
2704,
3886,
4446,
1166,
2889,
3981,
1758,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
2549,
3886,
4446,
12,
2867,
389,
2704,
3886,
4446,
13,
3903,
1338,
5592,
288,
203,
3639,
309,
261,
67,
2704,
3886,
4446,
422,
1758,
12,
20,
3719,
15226,
423,
4464,
1733,
1908,
3886,
4446,
2520,
7170,
1887,
5621,
203,
3639,
309,
261,
67,
2704,
3886,
4446,
422,
2889,
4446,
13,
15226,
423,
4464,
1733,
1908,
3886,
4446,
2520,
8650,
1887,
5621,
203,
3639,
2889,
4446,
273,
389,
2704,
3886,
4446,
31,
203,
203,
3639,
3626,
7659,
4446,
5033,
24899,
2704,
3886,
4446,
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
] |
//SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
import "hardhat/console.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./interfaces/IPool.sol";
import "./interfaces/IPayOut.sol";
import "./interfaces/IStake.sol";
import "./interfaces/IStrategyManager.sol";
contract Insurance is IPool, Ownable {
using SafeMath for uint256;
IERC20 public override token;
IStake public stakeToken;
IStrategyManager public strategyManager;
bool public redirectStakeToStrategy;
struct ProtocolProfile {
// translated to the value of the native erc20 of the pool
uint256 maxFundsCovered;
// percentage of funds covered
uint256 percentagePremiumPerBlock;
}
struct StakeWithdraw {
uint256 blockInitiated;
uint256 stake;
}
mapping(bytes32 => bool) public protocolsCovered;
bytes32[] public protocols;
mapping(bytes32 => ProtocolProfile) public profiles;
mapping(bytes32 => uint256) public profileBalances;
mapping(bytes32 => uint256) public profilePremiumLastPaid;
mapping(address => StakeWithdraw) public stakesWithdraw;
// in case of apy on funds. this will be added to total funds
uint256 internal totalStakedFunds;
// time lock for withdraw period in blocks
uint256 public timeLock;
constructor(
address _token,
address _stakeToken,
address _strategyManager
) public {
token = IERC20(_token);
stakeToken = IStake(_stakeToken);
strategyManager = IStrategyManager(_strategyManager);
}
function amountOfProtocolsCovered() public view returns (uint256) {
return protocols.length;
}
function getTotalStakedFunds() public view returns (uint256) {
return totalStakedFunds.add(strategyManager.balanceOfNative());
}
function _depositStrategyManager(uint256 _amount) internal {
require(
token.transfer(address(strategyManager), _amount),
"INSUFFICIENT_FUNDS"
);
totalStakedFunds = totalStakedFunds.sub(_amount);
strategyManager.deposit(address(token));
}
function _withdrawStrategyManager(uint256 _amount) internal {
strategyManager.withdraw(address(token), _amount);
totalStakedFunds = totalStakedFunds.add(_amount);
}
function withdrawStrategyManager(uint256 _amount) external onlyOwner {
_withdrawStrategyManager(_amount);
}
function depositStrategyManager(uint256 _amount) external onlyOwner {
_depositStrategyManager(_amount);
}
function setStrategyManager(address _strategyManager) external onlyOwner {
//todo withdraw all funds
strategyManager = IStrategyManager(_strategyManager);
}
function setRedirectStakeToStrategy(bool _redirect) external onlyOwner {
redirectStakeToStrategy = _redirect;
}
function setTimeLock(uint256 _timeLock) external onlyOwner {
timeLock = _timeLock;
}
// a governing contract will call the update profiles
// protocols can do a insurance request against this contract
function updateProfiles(
bytes32 _protocol,
uint256 _maxFundsCovered,
uint256 _percentagePremiumPerBlock,
uint256 _premiumLastPaid,
bool _forceOpenDebtPay
) external onlyOwner {
require(_protocol != bytes32(0), "INVALID_PROTOCOL");
require(_maxFundsCovered != 0, "INVALID_FUND");
require(_percentagePremiumPerBlock != 0, "INVALID_RISK");
if (_forceOpenDebtPay) {
require(tryPayOffDebt(_protocol, true), "FAILED_TO_PAY_DEBT");
}
profiles[_protocol] = ProtocolProfile(
_maxFundsCovered,
_percentagePremiumPerBlock
);
if (!protocolsCovered[_protocol]) {
protocolsCovered[_protocol] = true;
protocols.push(_protocol);
}
if (_premiumLastPaid == 0) {
// dont update
require(profilePremiumLastPaid[_protocol] > 0, "INVALID_LAST_PAID");
return;
}
if (_premiumLastPaid == uint256(-1)) {
profilePremiumLastPaid[_protocol] = block.number;
} else {
profilePremiumLastPaid[_protocol] = _premiumLastPaid;
}
}
function removeProtocol(
bytes32 _protocol,
uint256 _index,
bool _forceOpenDebtPay,
address _balanceReceiver
) external onlyOwner {
// do the index logic outside of solidity
require(protocols[_index] == _protocol, "INVALID_INDEX");
if (_forceOpenDebtPay) {
require(tryPayOffDebt(_protocol, true), "FAILED_TO_PAY_DEBT");
}
// transfer remaining balance to user
require(
token.transferFrom(
address(this),
_balanceReceiver,
profileBalances[_protocol]
),
"INSUFFICIENT_FUNDS"
);
delete profiles[_protocol];
delete profileBalances[_protocol];
delete profilePremiumLastPaid[_protocol];
protocolsCovered[_protocol] = false;
// set last element to current index
protocols[_index] = protocols[protocols.length - 1];
// remove last element
delete protocols[protocols.length - 1];
protocols.pop();
}
function insurancePayout(
bytes32 _protocol,
uint256 _amount,
address _payout
) external onlyOwner {
require(coveredFunds(_protocol) >= _amount, "INSUFFICIENT_COVERAGE");
require(token.transfer(_payout, _amount), "INSUFFICIENT_FUNDS");
IPayOut payout = IPayOut(_payout);
payout.deposit(address(token));
totalStakedFunds = totalStakedFunds.sub(_amount);
}
function stakeFunds(uint256 _amount) external {
require(
token.transferFrom(msg.sender, address(this), _amount),
"INSUFFICIENT_FUNDS"
);
// TODO, test this calculation with multiple scenarios
uint256 totalStake = stakeToken.totalSupply();
uint256 stake;
if (totalStake == 0) {
// mint initial stake
stake = _amount;
} else {
// TODO, decicde if _tryPayOffDebtAll(true); should be called here
// As this will give a better representation of the users stake
// But will also (significantly) increase gas costs
// mint stake based on funds in pool
stake = _amount.mul(totalStake).div(getTotalStakedFunds());
}
totalStakedFunds = totalStakedFunds.add(_amount);
stakeToken.mint(msg.sender, stake);
if (redirectStakeToStrategy) {
_depositStrategyManager(_amount);
}
}
//@ todo, add view stake
function getFunds(address _staker) external view returns (uint256) {
return
stakeToken.balanceOf(_staker).mul(getTotalStakedFunds()).div(
stakeToken.totalSupply()
);
}
// to withdraw funds, add them to a vesting schedule
function withdrawStake(uint256 _amount) external {
require(
stakesWithdraw[msg.sender].blockInitiated == 0,
"WITHDRAW_ACTIVE"
);
require(
stakeToken.transferFrom(msg.sender, address(this), _amount),
"TRANSFER_FAILED"
);
// totalStake sub? no right
stakesWithdraw[msg.sender] = StakeWithdraw(block.number, _amount);
}
function cancelWithdraw() external {
StakeWithdraw memory withdraw = stakesWithdraw[msg.sender];
require(withdraw.blockInitiated != 0, "WITHDRAW_NOT_ACTIVE");
require(
withdraw.blockInitiated.add(timeLock) > block.number,
"TIMELOCK_EXPIRED"
);
// if this one fails, contract is broken
stakeToken.transfer(msg.sender, withdraw.stake);
delete stakesWithdraw[msg.sender];
}
// to claim the withdrawed funds, if the vesting period is ended
// everyone can execute a claim for any staker
// this fights the game design where people call withdraw to skip the timeLock.
// And only claim when a hack occurs.
function claimFunds(address _staker) external {
StakeWithdraw memory withdraw = stakesWithdraw[_staker];
require(withdraw.blockInitiated != 0, "WITHDRAW_NOT_ACTIVE");
require(
withdraw.blockInitiated.add(timeLock) <= block.number,
"TIMELOCK_ACTIVE"
);
// don't redirect to strategy manager
// as this will be done a couple lines later
_tryPayOffDebtAll(false);
uint256 funds = withdraw.stake.mul(getTotalStakedFunds()).div(
stakeToken.totalSupply()
);
if (funds > totalStakedFunds) {
_withdrawStrategyManager(funds.sub(totalStakedFunds));
} else if (redirectStakeToStrategy && funds < totalStakedFunds) {
_depositStrategyManager(totalStakedFunds.sub(funds));
}
// if this one fails, contract is broken
token.transfer(_staker, funds);
stakeToken.burn(address(this), withdraw.stake);
delete stakesWithdraw[_staker];
}
function addProfileBalance(bytes32 _protocol, uint256 _amount) external {
require(
token.transferFrom(msg.sender, address(this), _amount),
"INSUFFICIENT_FUNDS"
);
profileBalances[_protocol] = profileBalances[_protocol].add(_amount);
}
function tryPayOffDebt(bytes32 _protocol, bool _useRedirect)
internal
returns (bool)
{
uint256 debt = accruedDebt(_protocol);
if (debt > profileBalances[_protocol]) {
return false;
}
profileBalances[_protocol] = profileBalances[_protocol].sub(debt);
// move funds to the staker pool
totalStakedFunds = totalStakedFunds.add(debt);
profilePremiumLastPaid[_protocol] = block.number;
// sent paid debt to strategy manager
if (_useRedirect && redirectStakeToStrategy) {
_depositStrategyManager(debt);
}
return true;
}
function payOffDebt(bytes32 _protocol) external {
require(tryPayOffDebt(_protocol, true), "INSUFFICIENT_PROFILE_BALANCE");
}
function _tryPayOffDebtAll(bool _useRedirect) internal {
for (uint256 i = 0; i < protocols.length; i++) {
tryPayOffDebt(protocols[i], _useRedirect);
}
}
function tryPayOffDebtAll() external {
_tryPayOffDebtAll(true);
}
function accruedDebt(bytes32 _protocol) public view returns (uint256) {
return
block.number.sub(profilePremiumLastPaid[_protocol]).mul(
premiumPerBlock(_protocol)
);
}
function premiumPerBlock(bytes32 _protocol) public view returns (uint256) {
ProtocolProfile memory p = profiles[_protocol];
return
coveredFunds(_protocol).mul(p.percentagePremiumPerBlock).div(
10**18
);
}
function coveredFunds(bytes32 _protocol) public view returns (uint256) {
ProtocolProfile memory p = profiles[_protocol];
require(p.maxFundsCovered > 0, "PROFILE_NOT_FOUND");
if (getTotalStakedFunds() > p.maxFundsCovered) {
return p.maxFundsCovered;
}
return getTotalStakedFunds();
}
}
|
in case of apy on funds. this will be added to total funds
|
uint256 internal totalStakedFunds;
| 13,078,789 |
[
1,
267,
648,
434,
513,
93,
603,
284,
19156,
18,
333,
903,
506,
3096,
358,
2078,
284,
19156,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2254,
5034,
2713,
2078,
510,
9477,
42,
19156,
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.4.25;
/**
Правила игр eSmart
* Процентная ставка 120%
* Фиксированный размер депозита; 0.05 eth, 0.1eth, 1eth
* Ежедневные старты, 5 раундов для каждой категории депозитов
* Распределение баланса
- 90% на выплаты участникам
- 7% делится поровну и распределяется между последними депозитами которые не прошли круг
(возврат 20% от депозита)
- 1% Джекпот
- 2% маркетинг и техническая поддержка
* Джекпот выигрывает участник который сделает больше всех транзакций с оборота за 5 раундов, в каждой категории отдельно.
* Раунд заканчивается через 10 минут от последней входящей транзакции на смарт контракт.
* eSmart предлагает самые эффективные умножители с высокой вероятностью прохождения круга!
* В играх eSmart нет проигравших, так как в каждом раунде все транзакции получают выплаты
- 77% первых транзакций 120% от депозита
- 23% последних транзакций в очереди 20% от депозита
* Играй в честные игры с eSmart
*/
contract ESmart {
uint constant public INVESTMENT = 0.05 ether;
uint constant private START_TIME = 1541435400; // 2018-11-05 19:30 MSK (GMT+3)
//Address for tech expences
address constant private TECH = 0x9A5B6966379a61388068bb765c518E5bC4D9B509;
//Address for promo expences
address constant private PROMO = 0xD6104cEca65db37925541A800870aEe09C8Fd78D;
//Address for promo expences
address constant private LAST_FUND = 0x357b9046f99eEC7E705980F328F00BAab4b3b6Be;
//Percent for first multiplier donation
uint constant public JACKPOT_PERCENT = 1;
uint constant public TECH_PERCENT = 7; //0.7%
uint constant public PROMO_PERCENT = 13; //1.3%
uint constant public LAST_FUND_PERCENT = 10;
uint constant public MAX_IDLE_TIME = 10 minutes; //Maximum time the deposit should remain the last to receive prize
uint constant public NEXT_ROUND_TIME = 30 minutes; //Time to next round since the last deposit
//How many percent for your deposit to be multiplied
uint constant public MULTIPLIER = 120;
//The deposit structure holds all the info about the deposit made
struct Deposit {
address depositor; //The depositor address
uint128 deposit; //The deposit amount
uint128 expect; //How much we should pay out (initially it is 120% of deposit)
}
struct LastDepositInfo {
uint128 index;
uint128 time;
}
struct MaxDepositInfo {
address depositor;
uint count;
}
Deposit[] private queue; //The queue
uint public currentReceiverIndex = 0; //The index of the first depositor in the queue. The receiver of investments!
uint public currentQueueSize = 0; //The current size of queue (may be less than queue.length)
LastDepositInfo public lastDepositInfo; //The time last deposit made at
MaxDepositInfo public maxDepositInfo; //The pretender for jackpot
uint private startTime = START_TIME;
mapping(address => uint) public depCount; //Number of deposits made
uint public jackpotAmount = 0; //Prize amount accumulated for the last depositor
int public stage = 0; //Number of contract runs
//This function receives all the deposits
//stores them and make immediate payouts
function () public payable {
//If money are from first multiplier, just add them to the balance
//All these money will be distributed to current investors
if(msg.value > 0){
require(gasleft() >= 220000, "We require more gas!"); //We need gas to process queue
require(msg.value >= INVESTMENT, "The investment is too small!");
require(stage < 5); //Only 5 rounds!!!
checkAndUpdateStage();
//Check that we can accept deposits
require(getStartTime() <= now, "Deposits are not accepted before time");
addDeposit(msg.sender, msg.value);
//Pay to first investors in line
pay();
}else if(msg.value == 0){
withdrawPrize();
}
}
//Used to pay to current investors
//Each new transaction processes 1 - 4+ investors in the head of queue
//depending on balance and gas left
function pay() private {
//Try to send all the money on contract to the first investors in line
uint balance = address(this).balance;
uint128 money = 0;
if(balance > (jackpotAmount)) //The opposite is impossible, however the check will not do any harm
money = uint128(balance - jackpotAmount);
//We will do cycle on the queue
for(uint i=currentReceiverIndex; i<currentQueueSize; i++){
Deposit storage dep = queue[i]; //get the info of the first investor
if(money >= dep.expect){ //If we have enough money on the contract to fully pay to investor
dep.depositor.send(dep.expect); //Send money to him
money -= dep.expect; //update money left
//this investor is fully paid, so remove him
delete queue[i];
}else{
//Here we don't have enough money so partially pay to investor
dep.depositor.send(money); //Send to him everything we have
dep.expect -= money; //Update the expected amount
break; //Exit cycle
}
if(gasleft() <= 50000) //Check the gas left. If it is low, exit the cycle
break; //The next investor will process the line further
}
currentReceiverIndex = i; //Update the index of the current first investor
}
function addDeposit(address depositor, uint value) private {
require(stage < 5); //Only 5 rounds!!!
//If you are applying for the prize you should invest more than minimal amount
//Otherwize it doesn't count
if(value > INVESTMENT){ //Fixed deposit
depositor.transfer(value - INVESTMENT);
value = INVESTMENT;
}
lastDepositInfo.index = uint128(currentQueueSize);
lastDepositInfo.time = uint128(now);
//Add the investor into the queue. Mark that he expects to receive 120% of deposit back
push(depositor, value, value*MULTIPLIER/100);
depCount[depositor]++;
//Check if candidate for jackpot changed
uint count = depCount[depositor];
if(maxDepositInfo.count < count){
maxDepositInfo.count = count;
maxDepositInfo.depositor = depositor;
}
//Save money for prize and father multiplier
jackpotAmount += value*(JACKPOT_PERCENT)/100;
uint lastFund = value*LAST_FUND_PERCENT/100;
LAST_FUND.send(lastFund);
//Send small part to tech support
uint support = value*TECH_PERCENT/1000;
TECH.send(support);
uint adv = value*PROMO_PERCENT/1000;
PROMO.send(adv);
}
function checkAndUpdateStage() private{
int _stage = getCurrentStageByTime();
require(_stage >= stage, "We should only go forward in time");
if(_stage != stage){
proceedToNewStage(_stage);
}
}
function proceedToNewStage(int _stage) private {
//Clean queue info
//The prize amount on the balance is left the same if not withdrawn
startTime = getStageStartTime(_stage);
assert(startTime > 0);
stage = _stage;
currentQueueSize = 0; //Instead of deleting queue just reset its length (gas economy)
currentReceiverIndex = 0;
delete lastDepositInfo;
}
function withdrawPrize() private {
require(getCurrentStageByTime() >= 5); //Only after 5 rounds!
require(maxDepositInfo.count > 0, "The max depositor is not confirmed yet");
uint balance = address(this).balance;
if(jackpotAmount > balance) //Impossible but better check it
jackpotAmount = balance;
maxDepositInfo.depositor.send(jackpotAmount);
selfdestruct(TECH); //5 rounds are over, so we can clean the contract
}
//Pushes investor to the queue
function push(address depositor, uint deposit, uint expect) private {
//Add the investor into the queue
Deposit memory dep = Deposit(depositor, uint128(deposit), uint128(expect));
assert(currentQueueSize <= queue.length); //Assert queue size is not corrupted
if(queue.length == currentQueueSize)
queue.push(dep);
else
queue[currentQueueSize] = dep;
currentQueueSize++;
}
//Get the deposit info by its index
//You can get deposit index from
function getDeposit(uint idx) public view returns (address depositor, uint deposit, uint expect){
Deposit storage dep = queue[idx];
return (dep.depositor, dep.deposit, dep.expect);
}
//Get the count of deposits of specific investor
function getDepositsCount(address depositor) public view returns (uint) {
uint c = 0;
for(uint i=currentReceiverIndex; i<currentQueueSize; ++i){
if(queue[i].depositor == depositor)
c++;
}
return c;
}
//Get all deposits (index, deposit, expect) of a specific investor
function getDeposits(address depositor) public view returns (uint[] idxs, uint128[] deposits, uint128[] expects) {
uint c = getDepositsCount(depositor);
idxs = new uint[](c);
deposits = new uint128[](c);
expects = new uint128[](c);
if(c > 0) {
uint j = 0;
for(uint i=currentReceiverIndex; i<currentQueueSize; ++i){
Deposit storage dep = queue[i];
if(dep.depositor == depositor){
idxs[j] = i;
deposits[j] = dep.deposit;
expects[j] = dep.expect;
j++;
}
}
}
}
//Get current queue size
function getQueueLength() public view returns (uint) {
return currentQueueSize - currentReceiverIndex;
}
function getCurrentStageByTime() public view returns (int) {
if(lastDepositInfo.time > 0 && lastDepositInfo.time + MAX_IDLE_TIME <= now){
return stage + 1; //Move to next stage if last deposit is too old
}
return stage;
}
function getStageStartTime(int _stage) public view returns (uint) {
if(_stage >= 5)
return 0;
if(_stage == stage)
return startTime;
if(lastDepositInfo.time == 0)
return 0;
if(_stage == stage + 1)
return lastDepositInfo.time + NEXT_ROUND_TIME;
return 0;
}
function getStartTime() public view returns (uint) {
return getStageStartTime(getCurrentStageByTime());
}
}
|
If you are applying for the prize you should invest more than minimal amountOtherwize it doesn't count
|
function addDeposit(address depositor, uint value) private {
depositor.transfer(value - INVESTMENT);
value = INVESTMENT;
}
| 6,400,157 |
[
1,
2047,
1846,
854,
13650,
364,
326,
846,
554,
1846,
1410,
2198,
395,
1898,
2353,
16745,
3844,
8290,
91,
554,
518,
3302,
1404,
1056,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
527,
758,
1724,
12,
2867,
443,
1724,
280,
16,
2254,
460,
13,
3238,
288,
203,
5411,
443,
1724,
280,
18,
13866,
12,
1132,
300,
2120,
3412,
882,
3212,
1769,
203,
5411,
460,
273,
2120,
3412,
882,
3212,
31,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// Copyright (c) 2016 Chronicled, Inc. All rights reserved.
// http://explorer.chronicled.org
// http://demo.chronicled.org
// http://chronicled.org
contract Registrar {
address public registrar;
/**
* Created event, gets triggered when a new registrant gets created
* event
* @param registrant - The registrant address.
* @param registrar - The registrar address.
* @param data - The data of the registrant.
*/
event Created(address indexed registrant, address registrar, bytes data);
/**
* Updated event, gets triggered when a new registrant id Updated
* event
* @param registrant - The registrant address.
* @param registrar - The registrar address.
* @param data - The data of the registrant.
*/
event Updated(address indexed registrant, address registrar, bytes data, bool active);
/**
* Error event.
* event
* @param code - The error code.
* 1: Permission denied.
* 2: Duplicate Registrant address.
* 3: No such Registrant.
*/
event Error(uint code);
struct Registrant {
address addr;
bytes data;
bool active;
}
mapping(address => uint) public registrantIndex;
Registrant[] public registrants;
/**
* Function can't have ether.
* modifier
*/
modifier noEther() {
if (msg.value > 0) throw;
_
}
modifier isRegistrar() {
if (msg.sender != registrar) {
Error(1);
return;
}
else {
_
}
}
/**
* Construct registry with and starting registrants lenght of one, and registrar as msg.sender
* constructor
*/
function Registrar() {
registrar = msg.sender;
registrants.length++;
}
/**
* Add a registrant, only registrar allowed
* public_function
* @param _registrant - The registrant address.
* @param _data - The registrant data string.
*/
function add(address _registrant, bytes _data) isRegistrar noEther returns (bool) {
if (registrantIndex[_registrant] > 0) {
Error(2); // Duplicate registrant
return false;
}
uint pos = registrants.length++;
registrants[pos] = Registrant(_registrant, _data, true);
registrantIndex[_registrant] = pos;
Created(_registrant, msg.sender, _data);
return true;
}
/**
* Edit a registrant, only registrar allowed
* public_function
* @param _registrant - The registrant address.
* @param _data - The registrant data string.
*/
function edit(address _registrant, bytes _data, bool _active) isRegistrar noEther returns (bool) {
if (registrantIndex[_registrant] == 0) {
Error(3); // No such registrant
return false;
}
Registrant registrant = registrants[registrantIndex[_registrant]];
registrant.data = _data;
registrant.active = _active;
Updated(_registrant, msg.sender, _data, _active);
return true;
}
/**
* Set new registrar address, only registrar allowed
* public_function
* @param _registrar - The new registrar address.
*/
function setNextRegistrar(address _registrar) isRegistrar noEther returns (bool) {
registrar = _registrar;
return true;
}
/**
* Get if a regsitrant is active or not.
* constant_function
* @param _registrant - The registrant address.
*/
function isActiveRegistrant(address _registrant) constant returns (bool) {
uint pos = registrantIndex[_registrant];
return (pos > 0 && registrants[pos].active);
}
/**
* Get all the registrants.
* constant_function
*/
function getRegistrants() constant returns (address[]) {
address[] memory result = new address[](registrants.length-1);
for (uint j = 1; j < registrants.length; j++) {
result[j-1] = registrants[j].addr;
}
return result;
}
/**
* Function to reject value sends to the contract.
* fallback_function
*/
function () noEther {}
/**
* Desctruct the smart contract. Since this is first, alpha release of Open Registry for IoT, updated versions will follow.
* Registry's discontinue must be executed first.
*/
function discontinue() isRegistrar noEther {
selfdestruct(msg.sender);
}
}
contract Registry {
// Address of the Registrar contract which holds all the Registrants
address public registrarAddress;
// Address of the account which deployed the contract. Used only to configure contract.
address public deployerAddress;
/**
* Creation event that gets triggered when a thing is created.
* event
* @param ids - The identity of the thing.
* @param owner - The owner address.
*/
event Created(bytes32[] ids, address indexed owner);
/**
* Update event that gets triggered when a thing is updated.
* event
* @param ids - The identity of the thing.
* @param owner - The owner address.
* @param isValid - The validity of the thing.
*/
event Updated(bytes32[] ids, address indexed owner, bool isValid);
/**
* Delete event, triggered when Thing is deleted.
* event
* @param ids - The identity of the thing.
* @param owner - The owner address.
*/
event Deleted(bytes32[] ids, address indexed owner);
/**
* Generic error event.
* event
* @param code - The error code.
* @param reference - Related references data for the Error event, e.g.: Identity, Address, etc.
* 1: Identity collision, already assigned to another Thing.
* 2: Not found, identity does not exist.
* 3: Unauthorized, modification only by owner.
* 4: Unknown schema specified.
* 5: Incorrect input, at least one identity is required.
* 6: Incorrect input, data is required.
* 7: Incorrect format of the identity, schema length and identity length cannot be empty.
* 8: Incorrect format of the identity, identity must be padded with trailing 0s.
* 9: Contract already configured
*/
event Error(uint code, bytes32[] reference);
struct Thing {
// All identities of a Thing. e.g.: BLE ID, public key, etc.
bytes32[] identities;
// Metadata of the Thing. Hex of ProtoBuffer structure.
bytes32[] data;
// Registrant address, who have added the thing.
address ownerAddress;
// Index of ProtoBuffer schema used. Optimized to fit in one bytes32.
uint88 schemaIndex;
// Status of the Thing. false if compromised, revoked, etc.
bool isValid;
}
// Things are stored in the array
Thing[] public things;
// Identity to Thing index pointer for lookups and duplicates prevention.
mapping(bytes32 => uint) public idToThing;
// Content of ProtoBuffer schema.
bytes[] public schemas;
/**
* Function can't contain Ether value.
* modifier
*/
modifier noEther() {
if (msg.value > 0) throw;
_
}
/**
* Allow only registrants to exec the function.
* modifier
*/
modifier isRegistrant() {
Registrar registrar = Registrar(registrarAddress);
if (registrar.isActiveRegistrant(msg.sender)) {
_
}
}
/**
* Allow only registrar to exec the function.
* modifier
*/
modifier isRegistrar() {
Registrar registrar = Registrar(registrarAddress);
if (registrar.registrar() == msg.sender) {
_
}
}
/**
* Initialization of the contract
* constructor
*/
function Registry() {
// Initialize arrays. Leave first element empty, since mapping points non-existent keys to 0.
things.length++;
schemas.length++;
deployerAddress = msg.sender;
}
/**
* Add Identities to already existing Thing.
* internal_function
* @param _thingIndex - The position of the Thing in the array.
* @param _ids - Identities of the Thing in chunked format. Maximum size of one Identity is 2057 bytes32 elements.
*/
function _addIdentities(uint _thingIndex, bytes32[] _ids) internal returns(bool){
// Checks if there's duplicates and creates references
if (false == _rewireIdentities(_ids, 0, _thingIndex, 0)) {
return false;
}
// Thing don't have Identities yet.
if (things[_thingIndex].identities.length == 0) {
// Copy directly. Cheaper than one by one.
things[_thingIndex].identities = _ids;
}
else {
// _ids array current element pointer.
// uint32 technically allows to put 128Gb of Identities into one Thing.
uint32 cell = uint32(things[_thingIndex].identities.length);
// Copy new IDs to the end of array one by one
things[_thingIndex].identities.length += _ids.length;
// If someone will provide _ids array with more than 2^32, it will go into infinite loop at a caller's expense.
for (uint32 k = 0; k < _ids.length; k++) {
things[_thingIndex].identities[cell++] = _ids[k];
}
}
return true;
}
/**
* Point provided Identities to the desired "things" array index in the lookup hash table idToThing.
* internal_function
* @param _ids - Identities of the Thing.
* @param _oldIndex - Previous index that this Identities pointed to, prevents accidental rewiring and duplicate Identities.
* @param _newIndex - things array index the Identities should point to.
* @param _newIndex - things array index the Identities should point to.
* @param _idsForcedLength — Internal use only. Zero by default. Used to revert side effects if execution fails at any point.
* Prevents infinity loop in recursion. Though recursion is not desirable, it's used to avoid over-complication of the code.
*/
function _rewireIdentities(bytes32[] _ids, uint _oldIndex, uint _newIndex, uint32 _idsForcedLength) internal returns(bool) {
// Current ID cell pointer
uint32 cell = 0;
// Length of namespace part of the Identity in URN format
uint16 urnNamespaceLength;
// Length of ID part of the Identity, though only uint16 needed but extended to uint24 for correct calculations.
uint24 idLength;
// Array cells used for current ID. uint24 to match idLength type, so no conversions needed.
uint24 cellsPerId;
// Hash of current ID
bytes32 idHash;
// How many bytes of payload are there in the last cell of single ID.
uint8 lastCellBytesCnt;
// Number of elements that needs to be processed in _ids array
uint32 idsLength = _idsForcedLength > 0 ? _idsForcedLength : uint32(_ids.length);
// No Identities provided
if (idsLength == 0) {
Error(5, _ids);
return false;
}
// Each ID
while (cell < idsLength) {
// Get length of schema. First byte of packed ID.
// Means that next urnNamespaceLength bytes is the schema definition.
urnNamespaceLength = uint8(_ids[cell][0]);
// Length of ID part of this URN Identity.
idLength =
// First byte
uint16(_ids[cell + (urnNamespaceLength + 1) / 32][(urnNamespaceLength + 1) % 32]) * 2 ** 8 |
// Second byte
uint8(_ids[cell + (urnNamespaceLength + 2) / 32][(urnNamespaceLength + 2) % 32]);
// We deal with the new Identity (instead rewiring after deletion)
if (_oldIndex == 0 && (urnNamespaceLength == 0 || idLength == 0)) {
// Incorrect Identity structure.
Error(7, _ids);
// If at least one Identity already wired. And if this is not a recursive call.
if (cell > 0 && _idsForcedLength == 0) {
_rewireIdentities(_ids, _newIndex, _oldIndex, cell); // Revert changes made so far
}
return false;
}
// Total bytes32 cells devoted for this ID. Maximum 2057 is possible.
cellsPerId = (idLength + urnNamespaceLength + 3) / 32;
if ((idLength + urnNamespaceLength + 3) % 32 != 0) {
// Identity uses one more cell partially
cellsPerId++;
// For new identity, ensure that complies with the format, specifically padding is done with 0s.
// This prevents from adding duplicated identities, which might be accepted because generate a different hash.
if (_oldIndex == 0) {
// How many bytes the ID occupies in the last cell.
lastCellBytesCnt = uint8((idLength + urnNamespaceLength + 3) % 32);
// Check if padded with zeros. Explicitly converting 2 into uint256 for correct calculations.
if (uint256(_ids[cell + cellsPerId - 1]) * (uint256(2) ** (lastCellBytesCnt * 8)) > 0) { // Bitwise left shift, result have to be 0
// Identity is not padded with 0s
Error(8, _ids);
// If at least one Identity already wired. And if this is not a recursive call.
if (cell > 0 && _idsForcedLength == 0) {
_rewireIdentities(_ids, _newIndex, _oldIndex, cell); // Revert changes made so far
}
return false;
}
}
}
// Single Identity array
bytes32[] memory id = new bytes32[](cellsPerId);
for (uint8 j = 0; j < cellsPerId; j++) {
id[j] = _ids[cell++];
}
// Uniqueness check and reference for lookups
idHash = sha3(id);
// If it points to where it's expected.
if (idToThing[idHash] == _oldIndex) {
// Wire Identity
idToThing[idHash] = _newIndex;
} else {
// References to a wrong Thing, e.g. Identity already exists, etc.
Error(1, _ids);
// If at least one Identity already wired. And if this is not a recursive call.
if (cell - cellsPerId > 0 && _idsForcedLength == 0) {
_rewireIdentities(_ids, _newIndex, _oldIndex, cell - cellsPerId); // Revert changes made so far
}
return false;
}
}
return true;
}
//
// Public Functions
//
/**
* Set the registrar address for the contract, (This function can be called only once).
* public_function
* @param _registrarAddress - The Registrar contract address.
*/
function configure(address _registrarAddress) noEther returns(bool) {
// Convert into array to properly generate Error event
bytes32[] memory ref = new bytes32[](1);
ref[0] = bytes32(registrarAddress);
if (msg.sender != deployerAddress) {
Error(3, ref);
return false;
}
if (registrarAddress != 0x0) {
Error(9, ref);
return false;
}
registrarAddress = _registrarAddress;
return true;
}
/**
* Create a new Thing in the Registry, only for registrants.
* public_function
* @param _ids - The chunked identities array.
* @param _data - Thing chunked data array.
* @param _schemaIndex - Index of the schema to parse Thing's data.
*/
function createThing(bytes32[] _ids, bytes32[] _data, uint88 _schemaIndex) isRegistrant returns(bool) {
// No data provided
if (_data.length == 0) {
Error(6, _ids);
return false;
}
if (_schemaIndex >= schemas.length || _schemaIndex == 0) {
Error(4, _ids);
return false;
}
// Wiring identities to non-existent Thing.
// This optimization reduces transaction cost by 100k of gas on avg (or by 3x), in case if _rewireIdentities will fail.
// Which leads to less damage to the caller, who provided incorrect data.
if (false == _rewireIdentities(_ids, 0, things.length, 0)) {
// Incorrect IDs format or duplicate Identities provided.
return false;
}
// Now after all verifications passed we can add a the Thing.
things.length++;
// Creating structure in-place is 11k gas cheaper than assigning parameters separately.
// That's why methods like updateThingData, addIdentities are not reused here.
things[things.length - 1] = Thing(_ids, _data, msg.sender, _schemaIndex, true);
// "Broadcast" event
Created(_ids, msg.sender);
return true;
}
/**
* Create multiple Things at once.
* Review: user should be aware that if there will be not enough identities transaction will run out of gas.
* Review: user should be aware that providing too many identities will result in some of them not being used.
* public_function
* @param _ids - The Thing's IDs to be added in bytes32 chunks
* @param _idsPerThing — number of IDs per thing, in relevant order
* @param _data - The data chunks
* @param _dataLength - The data length of every Thing to add, in relevant order
* @param _schemaIndex -Index of the schema to parse Thing's data
*/
function createThings(bytes32[] _ids, uint16[] _idsPerThing, bytes32[] _data, uint16[] _dataLength, uint88 _schemaIndex) isRegistrant noEther {
// Current _id array index
uint16 idIndex = 0;
// Current _data array index
uint16 dataIndex = 0;
// Counter of total id cells per one thing
uint24 idCellsPerThing = 0;
// Length of namespace part of the Identity in URN format
uint16 urnNamespaceLength;
// Length of ID part of the Identity, though only uint16 needed but extended to uint24 for correct calculations.
uint24 idLength;
// Each Thing
for (uint16 i = 0; i < _idsPerThing.length; i++) {
// Reset for each thing
idCellsPerThing = 0;
// Calculate number of cells for current Thing
for (uint16 j = 0; j < _idsPerThing[i]; j++) {
urnNamespaceLength = uint8(_ids[idIndex + idCellsPerThing][0]);
idLength =
// First byte
uint16(_ids[idIndex + idCellsPerThing + (urnNamespaceLength + 1) / 32][(urnNamespaceLength + 1) % 32]) * 2 ** 8 |
// Second byte
uint8(_ids[idIndex + idCellsPerThing + (urnNamespaceLength + 2) / 32][(urnNamespaceLength + 2) % 32]);
idCellsPerThing += (idLength + urnNamespaceLength + 3) / 32;
if ((idLength + urnNamespaceLength + 3) % 32 != 0) {
idCellsPerThing++;
}
}
// Extract ids for a single Thing
bytes32[] memory ids = new bytes32[](idCellsPerThing);
// Reusing var name to maintain stack size in limits
for (j = 0; j < idCellsPerThing; j++) {
ids[j] = _ids[idIndex++];
}
bytes32[] memory data = new bytes32[](_dataLength[i]);
for (j = 0; j < _dataLength[i]; j++) {
data[j] = _data[dataIndex++];
}
createThing(ids, data, _schemaIndex);
}
}
/**
* Add new IDs to the Thing, only registrants allowed.
* public_function
* @param _id - ID of the existing Thing
* @param _newIds - IDs to be added.
*/
function addIdentities(bytes32[] _id, bytes32[] _newIds) isRegistrant noEther returns(bool) {
var index = idToThing[sha3(_id)];
// There no Thing with such ID
if (index == 0) {
Error(2, _id);
return false;
}
if (_newIds.length == 0) {
Error(5, _id);
return false;
}
if (things[index].ownerAddress != 0x0 && things[index].ownerAddress != msg.sender) {
Error(3, _id);
return false;
}
if (_addIdentities(index, _newIds)) {
Updated(_id, things[index].ownerAddress, things[index].isValid);
return true;
}
return false;
}
/**
* Update Thing's data.
* public_function
* @param _id - The identity array.
* @param _data - Thing data array.
* @param _schemaIndex - The schema index of the schema to parse the thing.
*/
function updateThingData(bytes32[] _id, bytes32[] _data, uint88 _schemaIndex) isRegistrant noEther returns(bool) {
uint index = idToThing[sha3(_id)];
if (index == 0) {
Error(2, _id);
return false;
}
if (things[index].ownerAddress != 0x0 && things[index].ownerAddress != msg.sender) {
Error(3, _id);
return false;
}
if (_schemaIndex > schemas.length || _schemaIndex == 0) {
Error(4, _id);
return false;
}
if (_data.length == 0) {
Error(6, _id);
return false;
}
things[index].schemaIndex = _schemaIndex;
things[index].data = _data;
Updated(_id, things[index].ownerAddress, things[index].isValid);
return true;
}
/**
* Set validity of a thing, only registrants allowed.
* public_function
* @param _id - The identity to change.
* @param _isValid - The new validity of the thing.
*/
function setThingValid(bytes32[] _id, bool _isValid) isRegistrant noEther returns(bool) {
uint index = idToThing[sha3(_id)];
if (index == 0) {
Error(2, _id);
return false;
}
if (things[index].ownerAddress != msg.sender) {
Error(3, _id);
return false;
}
things[index].isValid = _isValid;
// Broadcast event
Updated(_id, things[index].ownerAddress, things[index].isValid);
return true;
}
/**
* Delete previously added Thing
* public_function
* @param _id - One of Thing's Identities.
*/
function deleteThing(bytes32[] _id) isRegistrant noEther returns(bool) {
uint index = idToThing[sha3(_id)];
if (index == 0) {
Error(2, _id);
return false;
}
if (things[index].ownerAddress != msg.sender) {
Error(3, _id);
return false;
}
// Rewire Thing's identities to index 0, e.g. delete.
if (false == _rewireIdentities(things[index].identities, index, 0, 0)) {
// Cannot rewire, should never happen
return false;
}
// Put last element in place of deleted one
if (index != things.length - 1) {
// Rewire identities of the last Thing to the new prospective index.
if (false == _rewireIdentities(things[things.length - 1].identities, things.length - 1, index, 0)) {
// Cannot rewire, should never happen
_rewireIdentities(things[index].identities, 0, index, 0); // Rollback
return false;
}
// "Broadcast" event with identities before they're lost.
Deleted(things[index].identities, things[index].ownerAddress);
// Move last Thing to the place of deleted one.
things[index] = things[things.length - 1];
}
// Delete last Thing
things.length--;
return true;
}
/**
* Get length of the schemas array
* constant_function
*/
function getSchemasLenght() constant returns(uint) {
return schemas.length;
}
/**
* Get Thing's information
* constant_function
* @param _id - identity of the thing.
*/
function getThing(bytes32[] _id) constant returns(bytes32[], bytes32[], uint88, bytes, address, bool) {
var index = idToThing[sha3(_id)];
// No such Thing
if (index == 0) {
Error(2, _id);
return;
}
Thing thing = things[index];
return (thing.identities, thing.data, thing.schemaIndex, schemas[thing.schemaIndex], thing.ownerAddress, thing.isValid);
}
/**
* Check if Thing is present in the registry by it's ID
* constant_function
* @param _id - identity for lookup.
*/
// Todo: reevaluate this method. Do we need it?
function thingExist(bytes32[] _id) constant returns(bool) {
return idToThing[sha3(_id)] > 0;
}
/**
* Create a new schema. Provided as hex of ProtoBuf-encoded schema data.
* public_function
* @param _schema - New schema string to add.
*/
function createSchema(bytes _schema) isRegistrar noEther returns(uint) {
uint pos = schemas.length++;
schemas[pos] = _schema;
return pos;
}
/**
* Fallback
*/
function () noEther {}
/**
* Desctruct the smart contract. Since this is first, alpha release of Open Registry for IoT, updated versions will follow.
* Execute this prior to Registrar's contract discontinue()
*/
function discontinue() isRegistrar noEther returns(bool) {
selfdestruct(msg.sender);
return true;
}
}
|
Reset for each thing Calculate number of cells for current Thing First byte Second byte Reusing var name to maintain stack size in limits
|
for (uint16 i = 0; i < _idsPerThing.length; i++) {
idCellsPerThing = 0;
for (uint16 j = 0; j < _idsPerThing[i]; j++) {
urnNamespaceLength = uint8(_ids[idIndex + idCellsPerThing][0]);
idLength =
uint16(_ids[idIndex + idCellsPerThing + (urnNamespaceLength + 1) / 32][(urnNamespaceLength + 1) % 32]) * 2 ** 8 |
uint8(_ids[idIndex + idCellsPerThing + (urnNamespaceLength + 2) / 32][(urnNamespaceLength + 2) % 32]);
idCellsPerThing += (idLength + urnNamespaceLength + 3) / 32;
if ((idLength + urnNamespaceLength + 3) % 32 != 0) {
idCellsPerThing++;
}
}
for (j = 0; j < idCellsPerThing; j++) {
ids[j] = _ids[idIndex++];
}
bytes32[] memory data = new bytes32[](_dataLength[i]);
for (j = 0; j < _dataLength[i]; j++) {
data[j] = _data[dataIndex++];
}
createThing(ids, data, _schemaIndex);
}
| 1,088,035 |
[
1,
7013,
364,
1517,
7757,
9029,
1300,
434,
5983,
364,
783,
25803,
5783,
1160,
7631,
1160,
868,
9940,
569,
508,
358,
17505,
2110,
963,
316,
8181,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3639,
364,
261,
11890,
2313,
277,
273,
374,
31,
277,
411,
389,
2232,
2173,
10193,
18,
2469,
31,
277,
27245,
288,
203,
5411,
612,
10505,
2173,
10193,
273,
374,
31,
203,
5411,
364,
261,
11890,
2313,
525,
273,
374,
31,
525,
411,
389,
2232,
2173,
10193,
63,
77,
15533,
525,
27245,
288,
203,
7734,
18412,
3402,
1782,
273,
2254,
28,
24899,
2232,
63,
350,
1016,
397,
612,
10505,
2173,
10193,
6362,
20,
19226,
203,
7734,
612,
1782,
273,
203,
10792,
2254,
2313,
24899,
2232,
63,
350,
1016,
397,
612,
10505,
2173,
10193,
397,
261,
321,
3402,
1782,
397,
404,
13,
342,
3847,
6362,
12,
321,
3402,
1782,
397,
404,
13,
738,
3847,
5717,
380,
576,
2826,
1725,
571,
203,
10792,
2254,
28,
24899,
2232,
63,
350,
1016,
397,
612,
10505,
2173,
10193,
397,
261,
321,
3402,
1782,
397,
576,
13,
342,
3847,
6362,
12,
321,
3402,
1782,
397,
576,
13,
738,
3847,
19226,
203,
203,
7734,
612,
10505,
2173,
10193,
1011,
261,
350,
1782,
397,
18412,
3402,
1782,
397,
890,
13,
342,
3847,
31,
203,
7734,
309,
14015,
350,
1782,
397,
18412,
3402,
1782,
397,
890,
13,
738,
3847,
480,
374,
13,
288,
203,
10792,
612,
10505,
2173,
10193,
9904,
31,
203,
7734,
289,
203,
5411,
289,
203,
203,
5411,
364,
261,
78,
273,
374,
31,
525,
411,
612,
10505,
2173,
10193,
31,
525,
27245,
288,
203,
7734,
3258,
63,
78,
65,
273,
389,
2232,
63,
350,
1016,
9904,
15533,
203,
5411,
289,
203,
203,
5411,
1731,
1578,
8526,
3778,
501,
273,
394,
1731,
2
] |
pragma solidity ^0.4.13;
contract ZCHMath {
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);
}
function min(uint x, uint y) internal pure returns (uint z) {
return x <= y ? x : y;
}
function max(uint x, uint y) internal pure returns (uint z) {
return x >= y ? x : y;
}
function imin(int x, int y) internal pure returns (int z) {
return x <= y ? x : y;
}
function imax(int x, int y) internal pure returns (int z) {
return x >= y ? x : y;
}
uint constant WAD = 10 ** 18;
uint constant RAY = 10 ** 27;
function wmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
function rmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
function wdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, WAD), y / 2) / y;
}
function rdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, RAY), y / 2) / y;
}
function rpow(uint x, uint n) internal pure returns (uint z) {
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rmul(x, x);
if (n % 2 != 0) {
z = rmul(z, x);
}
}
}
}
contract ZCHAuthority {
function canCall(
address src, address ZCH, bytes4 sig
) public view returns (bool);
}
contract ZCHAuthEvents {
event LogSetAuthority (address indexed authority);
event LogSetOwner (address indexed owner);
}
contract ZCHAuth is ZCHAuthEvents {
ZCHAuthority public authority;
address public owner;
function ZCHAuth() public {
owner = msg.sender;
LogSetOwner(msg.sender);
}
function setOwner(address owner_)
public
auth
{
owner = owner_;
LogSetOwner(owner);
}
function setAuthority(ZCHAuthority 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 == ZCHAuthority(0)) {
return false;
} else {
return authority.canCall(src, this, sig);
}
}
}
contract ZCHNote {
event LogNote(
bytes4 indexed sig,
address indexed guy,
bytes32 indexed foo,
bytes32 indexed bar,
uint wad,
bytes fax
) anonymous;
modifier note {
bytes32 foo;
bytes32 bar;
assembly {
foo := calldataload(4)
bar := calldataload(36)
}
LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data);
_;
}
}
contract ZCHStop is ZCHNote, ZCHAuth {
bool public stopped;
modifier stoppable {
require(!stopped);
_;
}
function stop() public auth note {
stopped = true;
}
function start() public auth note {
stopped = false;
}
}
contract ERC20Events {
event Approval(address indexed src, address indexed guy, uint wad);
event Transfer(address indexed src, address indexed ZCH, uint wad);
}
contract ERC20 is ERC20Events {
function totalSupply() public view returns (uint);
function balanceOf(address guy) public view returns (uint);
function allowance(address src, address guy) public view returns (uint);
function approve(address guy, uint wad) public returns (bool);
function transfer(address ZCH, uint wad) public returns (bool);
function transferFrom(
address src, address ZCH, uint wad
) public returns (bool);
}
contract ZCHTokenBase is ERC20, ZCHMath {
uint256 _supply;
mapping (address => uint256) _balances;
mapping (address => mapping (address => uint256)) _approvals;
function ZCHTokenBase(uint supply) public {
_balances[msg.sender] = supply;
_supply = supply;
}
function totalSupply() public view returns (uint) {
return _supply;
}
function balanceOf(address src) public view returns (uint) {
return _balances[src];
}
function allowance(address src, address guy) public view returns (uint) {
return _approvals[src][guy];
}
function transfer(address ZCH, uint wad) public returns (bool) {
return transferFrom(msg.sender, ZCH, wad);
}
function transferFrom(address src, address ZCH, uint wad)
public
returns (bool)
{
if (src != msg.sender) {
_approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad);
}
_balances[src] = sub(_balances[src], wad);
_balances[ZCH] = add(_balances[ZCH], wad);
Transfer(src, ZCH, wad);
return true;
}
function approve(address guy, uint wad) public returns (bool) {
_approvals[msg.sender][guy] = wad;
Approval(msg.sender, guy, wad);
return true;
}
}
contract ZCHToken is ZCHTokenBase(0), ZCHStop {
bytes32 public symbol;
uint256 public decimals = 2; // standard token precision. override to customize
function ZCHToken(bytes32 symbol_) public {
symbol = symbol_;
}
event Mint(address indexed guy, uint wad);
event Burn(address indexed guy, uint wad);
function approve(address guy) public stoppable returns (bool) {
return super.approve(guy, uint(-1));
}
function approve(address guy, uint wad) public stoppable returns (bool) {
return super.approve(guy, wad);
}
function transferFrom(address src, address ZCH, uint wad)
public
stoppable
returns (bool)
{
if (src != msg.sender && _approvals[src][msg.sender] != uint(-1)) {
_approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad);
}
_balances[src] = sub(_balances[src], wad);
_balances[ZCH] = add(_balances[ZCH], wad);
Transfer(src, ZCH, wad);
return true;
}
function push(address ZCH, uint wad) public {
transferFrom(msg.sender, ZCH, wad);
}
function pull(address src, uint wad) public {
transferFrom(src, msg.sender, wad);
}
function move(address src, address ZCH, uint wad) public {
transferFrom(src, ZCH, wad);
}
function mint(uint wad) public {
mint(msg.sender, wad);
}
function burn(uint wad) public {
burn(msg.sender, wad);
}
function mint(address guy, uint wad) public auth stoppable {
_balances[guy] = add(_balances[guy], wad);
_supply = add(_supply, wad);
Mint(guy, wad);
}
function burn(address guy, uint wad) public auth stoppable {
if (guy != msg.sender && _approvals[guy][msg.sender] != uint(-1)) {
_approvals[guy][msg.sender] = sub(_approvals[guy][msg.sender], wad);
}
_balances[guy] = sub(_balances[guy], wad);
_supply = sub(_supply, wad);
Burn(guy, wad);
}
// Optional token name
bytes32 public name = "";
function setName(bytes32 name_) public auth {
name = name_;
}
}
|
standard token precision. override to customize
|
uint256 public decimals = 2;
| 1,085,032 |
[
1,
10005,
1147,
6039,
18,
3849,
358,
20236,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
225,
1071,
225,
15105,
273,
576,
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
] |
pragma solidity ^0.6.12;
// SPDX-License-Identifier: MIT
/*
* @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 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 Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @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");
}
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// Honeyjar with Governance.
contract Honeyjar is ERC20("Honey", "BHNY"), Ownable {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
}
}
contract BHNYChef is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of BHNYs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accBHNYPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accBHNYPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. BHNYs to distribute per block.
uint256 lastRewardBlock; // Last block number that BHNYs distribution occurs.
uint256 accBHNYPerShare; // Accumulated BHNYs per share, times 1e12. See below.
}
// The BHNY TOKEN!
Honeyjar public BHNY;
// Dev address.
address public devaddr;
// Block number when bonus BHNY period ends.
uint256 public bonusEndBlock;
// BHNY tokens created per block.
uint256 public BHNYPerBlock;
// Bonus muliplier for early BHNY makers.
uint256 public constant BONUS_MULTIPLIER = 1; // no bonus
// No of blocks in a day - 7000
uint256 public constant perDayBlocks = 7000; // no bonus
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when BHNY mining starts.
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
Honeyjar _BHNY,
address _devaddr,
uint256 _BHNYPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
) public {
BHNY = _BHNY;
devaddr = _devaddr;
BHNYPerBlock = _BHNYPerBlock;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accBHNYPerShare: 0
}));
}
// Update the given pool's BHNY allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(
_to.sub(bonusEndBlock)
);
}
}
// reward prediction at specific block
function getRewardPerBlock(uint blockNumber) public view returns (uint256) {
if (blockNumber >= startBlock){
uint256 blockDaysPassed = (blockNumber.sub(startBlock)).div(perDayBlocks);
if(blockDaysPassed <= 0){
return BHNYPerBlock;
}
else if(blockDaysPassed > 0 && blockDaysPassed <= 7){
return BHNYPerBlock.div(2);
}
else if(blockDaysPassed > 7 && blockDaysPassed <= 30){
return BHNYPerBlock.div(4);
}
else if(blockDaysPassed > 30 && blockDaysPassed <= 90){
return BHNYPerBlock.div(8);
}
else {
return BHNYPerBlock.div(10);
}
} else {
return 0;
}
}
// View function to see pending BHNYs on frontend.
function pendingBHNY(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accBHNYPerShare = pool.accBHNYPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 rewardThisBlock = getRewardPerBlock(block.number);
uint256 BHNYReward = multiplier.mul(rewardThisBlock).mul(pool.allocPoint).div(totalAllocPoint);
accBHNYPerShare = accBHNYPerShare.add(BHNYReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accBHNYPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 rewardThisBlock = getRewardPerBlock(block.number);
uint256 BHNYReward = multiplier.mul(rewardThisBlock).mul(pool.allocPoint).div(totalAllocPoint);
BHNY.mint(devaddr, BHNYReward.div(25)); // 4%
BHNY.mint(address(this), BHNYReward);
pool.accBHNYPerShare = pool.accBHNYPerShare.add(BHNYReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for BHNY allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accBHNYPerShare).div(1e12).sub(user.rewardDebt);
safeBHNYTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accBHNYPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accBHNYPerShare).div(1e12).sub(user.rewardDebt);
safeBHNYTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accBHNYPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe BHNY transfer function, just in case if rounding error causes pool to not have enough BHNYs.
function safeBHNYTransfer(address _to, uint256 _amount) internal {
uint256 BHNYBal = BHNY.balanceOf(address(this));
if (_amount > BHNYBal) {
BHNY.transfer(_to, BHNYBal);
} else {
BHNY.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
}
|
Safe BHNY transfer function, just in case if rounding error causes pool to not have enough BHNYs.
|
function safeBHNYTransfer(address _to, uint256 _amount) internal {
uint256 BHNYBal = BHNY.balanceOf(address(this));
if (_amount > BHNYBal) {
BHNY.transfer(_to, BHNYBal);
BHNY.transfer(_to, _amount);
}
}
| 10,042,109 |
[
1,
9890,
605,
44,
50,
61,
7412,
445,
16,
2537,
316,
648,
309,
13885,
555,
14119,
2845,
358,
486,
1240,
7304,
605,
44,
50,
61,
87,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
4183,
38,
44,
50,
61,
5912,
12,
2867,
389,
869,
16,
2254,
5034,
389,
8949,
13,
2713,
288,
203,
3639,
2254,
5034,
605,
44,
50,
61,
38,
287,
273,
605,
44,
50,
61,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
309,
261,
67,
8949,
405,
605,
44,
50,
61,
38,
287,
13,
288,
203,
5411,
605,
44,
50,
61,
18,
13866,
24899,
869,
16,
605,
44,
50,
61,
38,
287,
1769,
203,
5411,
605,
44,
50,
61,
18,
13866,
24899,
869,
16,
389,
8949,
1769,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x0A7a3f0696c36E5c3452915dbB1b3115c3A37680/sources/browser/3_Ballot.sol
|
* Whitelist any user address - only Owner can do this It will add user address in whitelisted mapping/
|
function whitelistUser(address userAddress) onlyOwner public{
require(whitelistingStatus == true);
require(userAddress != address(0));
whitelisted[userAddress] = true;
}
| 671,092 |
[
1,
18927,
1281,
729,
1758,
300,
1338,
16837,
848,
741,
333,
2597,
903,
527,
729,
1758,
316,
26944,
2874,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
10734,
1299,
12,
2867,
729,
1887,
13,
1338,
5541,
1071,
95,
203,
3639,
2583,
12,
20409,
310,
1482,
422,
638,
1769,
203,
3639,
2583,
12,
1355,
1887,
480,
1758,
12,
20,
10019,
203,
3639,
26944,
63,
1355,
1887,
65,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
require(token.transfer(to, value));
}
function safeTransferFrom(
ERC20 token,
address from,
address to,
uint256 value
)
internal
{
require(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
require(token.approve(spender, value));
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* See https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/issues/20
* Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_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,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of 'user permissions'.
*/
/// @title Ownable
/// @author Applicature
/// @notice helper mixed to other contracts to link contract on an owner
/// @dev Base class
contract Ownable {
//Variables
address public owner;
address public newOwner;
// Modifiers
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @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));
newOwner = _newOwner;
}
function acceptOwnership() public {
if (msg.sender == newOwner) {
owner = newOwner;
}
}
}
/**
* @title TokenVesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the
* owner.
*/
contract TokenVesting is Ownable {
using SafeMath for uint256;
using SafeERC20 for ERC20Basic;
event Released(uint256 amount);
event Revoked();
// beneficiary of tokens after they are released
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
bool public revocable;
mapping (address => uint256) public released;
mapping (address => bool) public revoked;
/**
* @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* _beneficiary, gradually in a linear fashion until _start + _duration. By then all
* of the balance will have vested.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _start the time (as Unix time) at which point vesting starts
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
*/
constructor(
address _beneficiary,
uint256 _start,
uint256 _cliff,
uint256 _duration,
bool _revocable
)
public
{
require(_beneficiary != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
cliff = _start.add(_cliff);
start = _start;
}
/**
* @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(ERC20Basic token) public {
uint256 unreleased = releasableAmount(token);
require(unreleased > 0);
released[token] = released[token].add(unreleased);
token.safeTransfer(beneficiary, unreleased);
emit Released(unreleased);
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(ERC20Basic token) public onlyOwner {
require(revocable);
require(!revoked[token]);
uint256 balance = token.balanceOf(this);
uint256 unreleased = releasableAmount(token);
uint256 refund = balance.sub(unreleased);
revoked[token] = true;
token.safeTransfer(owner, refund);
emit Revoked();
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
function releasableAmount(ERC20Basic token) public view returns (uint256) {
return vestedAmount(token).sub(released[token]);
}
/**
* @dev Calculates the amount that has already vested.
* @param token ERC20 token which is being vested
*/
function vestedAmount(ERC20Basic token) public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[token]);
if (block.timestamp < cliff) {
return 0;
} else if (block.timestamp >= start.add(duration) || revoked[token]) {
return totalBalance;
} else {
return totalBalance.mul(block.timestamp.sub(start)).div(duration);
}
}
}
/// @title OpenZeppelinERC20
/// @author Applicature
/// @notice Open Zeppelin implementation of standart ERC20
/// @dev Base class
contract OpenZeppelinERC20 is StandardToken, Ownable {
using SafeMath for uint256;
uint8 public decimals;
string public name;
string public symbol;
string public standard;
constructor(
uint256 _totalSupply,
string _tokenName,
uint8 _decimals,
string _tokenSymbol,
bool _transferAllSupplyToOwner
) public {
standard = 'ERC20 0.1';
totalSupply_ = _totalSupply;
if (_transferAllSupplyToOwner) {
balances[msg.sender] = _totalSupply;
} else {
balances[this] = _totalSupply;
}
name = _tokenName;
// Set the name for display purposes
symbol = _tokenSymbol;
// Set the symbol for display purposes
decimals = _decimals;
}
}
/// @title MintableToken
/// @author Applicature
/// @notice allow to mint tokens
/// @dev Base class
contract MintableToken is BasicToken, Ownable {
using SafeMath for uint256;
uint256 public maxSupply;
bool public allowedMinting;
mapping(address => bool) public mintingAgents;
mapping(address => bool) public stateChangeAgents;
event Mint(address indexed holder, uint256 tokens);
modifier onlyMintingAgents () {
require(mintingAgents[msg.sender]);
_;
}
modifier onlyStateChangeAgents () {
require(stateChangeAgents[msg.sender]);
_;
}
constructor(uint256 _maxSupply, uint256 _mintedSupply, bool _allowedMinting) public {
maxSupply = _maxSupply;
totalSupply_ = totalSupply_.add(_mintedSupply);
allowedMinting = _allowedMinting;
mintingAgents[msg.sender] = true;
}
/// @notice allow to mint tokens
function mint(address _holder, uint256 _tokens) public onlyMintingAgents() {
require(allowedMinting == true && totalSupply_.add(_tokens) <= maxSupply);
totalSupply_ = totalSupply_.add(_tokens);
balances[_holder] = balances[_holder].add(_tokens);
if (totalSupply_ == maxSupply) {
allowedMinting = false;
}
emit Transfer(address(0), _holder, _tokens);
emit Mint(_holder, _tokens);
}
/// @notice update allowedMinting flat
function disableMinting() public onlyStateChangeAgents() {
allowedMinting = false;
}
/// @notice update minting agent
function updateMintingAgent(address _agent, bool _status) public onlyOwner {
mintingAgents[_agent] = _status;
}
/// @notice update state change agent
function updateStateChangeAgent(address _agent, bool _status) public onlyOwner {
stateChangeAgents[_agent] = _status;
}
/// @return available tokens
function availableTokens() public view returns (uint256 tokens) {
return maxSupply.sub(totalSupply_);
}
}
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
/// @title MintableBurnableToken
/// @author Applicature
/// @notice helper mixed to other contracts to burn tokens
/// @dev implementation
contract MintableBurnableToken is MintableToken, BurnableToken {
mapping (address => bool) public burnAgents;
modifier onlyBurnAgents () {
require(burnAgents[msg.sender]);
_;
}
constructor(
uint256 _maxSupply,
uint256 _mintedSupply,
bool _allowedMinting
) public MintableToken(
_maxSupply,
_mintedSupply,
_allowedMinting
) {
}
/// @notice update burn agent
function updateBurnAgent(address _agent, bool _status) public onlyOwner {
burnAgents[_agent] = _status;
}
function burnByAgent(address _holder, uint256 _tokensToBurn) public onlyBurnAgents() returns (uint256) {
if (_tokensToBurn == 0) {
_tokensToBurn = balances[_holder];
}
_burn(_holder, _tokensToBurn);
return _tokensToBurn;
}
function _burn(address _who, uint256 _value) internal {
super._burn(_who, _value);
maxSupply = maxSupply.sub(_value);
}
}
/// @title TimeLocked
/// @author Applicature
/// @notice helper mixed to other contracts to lock contract on a timestamp
/// @dev Base class
contract TimeLocked {
uint256 public time;
mapping(address => bool) public excludedAddresses;
modifier isTimeLocked(address _holder, bool _timeLocked) {
bool locked = (block.timestamp < time);
require(excludedAddresses[_holder] == true || locked == _timeLocked);
_;
}
constructor(uint256 _time) public {
time = _time;
}
function updateExcludedAddress(address _address, bool _status) public;
}
/// @title TimeLockedToken
/// @author Applicature
/// @notice helper mixed to other contracts to lock contract on a timestamp
/// @dev Base class
contract TimeLockedToken is TimeLocked, StandardToken {
constructor(uint256 _time) public TimeLocked(_time) {}
function transfer(address _to, uint256 _tokens) public isTimeLocked(msg.sender, false) returns (bool) {
return super.transfer(_to, _tokens);
}
function transferFrom(address _holder, address _to, uint256 _tokens)
public
isTimeLocked(_holder, false)
returns (bool)
{
return super.transferFrom(_holder, _to, _tokens);
}
}
contract ICUToken is OpenZeppelinERC20, MintableBurnableToken, TimeLockedToken {
ICUCrowdsale public crowdsale;
bool public isSoftCapAchieved;
constructor(uint256 _unlockTokensTime)
public
OpenZeppelinERC20(0, 'iCumulate', 18, 'ICU', false)
MintableBurnableToken(4700000000e18, 0, true)
TimeLockedToken(_unlockTokensTime)
{}
function setUnlockTime(uint256 _unlockTokensTime) public onlyStateChangeAgents {
time = _unlockTokensTime;
}
function setIsSoftCapAchieved() public onlyStateChangeAgents {
isSoftCapAchieved = true;
}
function setCrowdSale(address _crowdsale) public onlyOwner {
require(_crowdsale != address(0));
crowdsale = ICUCrowdsale(_crowdsale);
}
function updateExcludedAddress(address _address, bool _status) public onlyOwner {
excludedAddresses[_address] = _status;
}
function transfer(address _to, uint256 _tokens) public returns (bool) {
require(true == isTransferAllowed(msg.sender));
return super.transfer(_to, _tokens);
}
function transferFrom(address _holder, address _to, uint256 _tokens) public returns (bool) {
require(true == isTransferAllowed(_holder));
return super.transferFrom(_holder, _to, _tokens);
}
function isTransferAllowed(address _address) public view returns (bool) {
if (excludedAddresses[_address] == true) {
return true;
}
if (!isSoftCapAchieved && (address(crowdsale) == address(0) || false == crowdsale.isSoftCapAchieved(0))) {
return false;
}
return true;
}
function burnUnsoldTokens(uint256 _tokensToBurn) public onlyBurnAgents() returns (uint256) {
require(maxSupply.sub(_tokensToBurn) >= totalSupply_);
maxSupply = maxSupply.sub(_tokensToBurn);
emit Burn(address(0), _tokensToBurn);
return _tokensToBurn;
}
}
/// @title Agent
/// @author Applicature
/// @notice Contract which takes actions on state change and contribution
/// @dev Base class
contract Agent {
using SafeMath for uint256;
function isInitialized() public view returns (bool) {
return false;
}
}
/// @title CrowdsaleAgent
/// @author Applicature
/// @notice Contract which takes actions on state change and contribution
/// @dev Base class
contract CrowdsaleAgent is Agent {
Crowdsale public crowdsale;
bool public _isInitialized;
modifier onlyCrowdsale() {
require(msg.sender == address(crowdsale));
_;
}
constructor(Crowdsale _crowdsale) public {
crowdsale = _crowdsale;
if (address(0) != address(_crowdsale)) {
_isInitialized = true;
} else {
_isInitialized = false;
}
}
function isInitialized() public view returns (bool) {
return _isInitialized;
}
function onContribution(address _contributor, uint256 _weiAmount, uint256 _tokens, uint256 _bonus)
public onlyCrowdsale();
function onStateChange(Crowdsale.State _state) public onlyCrowdsale();
function onRefund(address _contributor, uint256 _tokens) public onlyCrowdsale() returns (uint256 burned);
}
/// @title MintableCrowdsaleOnSuccessAgent
/// @author Applicature
/// @notice Contract which takes actions on state change and contribution
/// un-pause tokens and disable minting on Crowdsale success
/// @dev implementation
contract MintableCrowdsaleOnSuccessAgent is CrowdsaleAgent {
MintableToken public token;
bool public _isInitialized;
constructor(Crowdsale _crowdsale, MintableToken _token) public CrowdsaleAgent(_crowdsale) {
token = _token;
if (address(0) != address(_token) && address(0) != address(_crowdsale)) {
_isInitialized = true;
} else {
_isInitialized = false;
}
}
/// @notice Check whether contract is initialised
/// @return true if initialized
function isInitialized() public view returns (bool) {
return _isInitialized;
}
/// @notice Takes actions on contribution
function onContribution(address _contributor, uint256 _weiAmount, uint256 _tokens, uint256 _bonus) public onlyCrowdsale;
/// @notice Takes actions on state change,
/// un-pause tokens and disable minting on Crowdsale success
/// @param _state Crowdsale.State
function onStateChange(Crowdsale.State _state) public onlyCrowdsale;
}
contract ICUAgent is MintableCrowdsaleOnSuccessAgent {
ICUStrategy public strategy;
ICUCrowdsale public crowdsale;
bool public burnStatus;
constructor(
ICUCrowdsale _crowdsale,
ICUToken _token,
ICUStrategy _strategy
) public MintableCrowdsaleOnSuccessAgent(_crowdsale, _token) {
require(address(_strategy) != address(0) && address(_crowdsale) != address(0));
strategy = _strategy;
crowdsale = _crowdsale;
}
/// @notice Takes actions on contribution
function onContribution(
address,
uint256 _tierIndex,
uint256 _tokens,
uint256 _bonus
) public onlyCrowdsale() {
strategy.updateTierState(_tierIndex, _tokens, _bonus);
}
function onStateChange(Crowdsale.State _state) public onlyCrowdsale() {
ICUToken icuToken = ICUToken(token);
if (
icuToken.isSoftCapAchieved() == false
&& (_state == Crowdsale.State.Success || _state == Crowdsale.State.Finalized)
&& crowdsale.isSoftCapAchieved(0)
) {
icuToken.setIsSoftCapAchieved();
}
if (_state > Crowdsale.State.InCrowdsale && burnStatus == false) {
uint256 unsoldTokensAmount = strategy.getUnsoldTokens();
burnStatus = true;
icuToken.burnUnsoldTokens(unsoldTokensAmount);
}
}
function onRefund(address _contributor, uint256 _tokens) public onlyCrowdsale() returns (uint256 burned) {
burned = ICUToken(token).burnByAgent(_contributor, _tokens);
}
function updateLockPeriod(uint256 _time) public {
require(msg.sender == address(strategy));
ICUToken(token).setUnlockTime(_time);
}
}
/// @title TokenAllocator
/// @author Applicature
/// @notice Contract responsible for defining distribution logic of tokens.
/// @dev Base class
contract TokenAllocator is Ownable {
mapping(address => bool) public crowdsales;
modifier onlyCrowdsale() {
require(crowdsales[msg.sender]);
_;
}
function addCrowdsales(address _address) public onlyOwner {
crowdsales[_address] = true;
}
function removeCrowdsales(address _address) public onlyOwner {
crowdsales[_address] = false;
}
function isInitialized() public view returns (bool) {
return false;
}
function allocate(address _holder, uint256 _tokens) public onlyCrowdsale() {
internalAllocate(_holder, _tokens);
}
function tokensAvailable() public view returns (uint256);
function internalAllocate(address _holder, uint256 _tokens) internal onlyCrowdsale();
}
/// @title MintableTokenAllocator
/// @author Applicature
/// @notice Contract responsible for defining distribution logic of tokens.
/// @dev implementation
contract MintableTokenAllocator is TokenAllocator {
using SafeMath for uint256;
MintableToken public token;
constructor(MintableToken _token) public {
require(address(0) != address(_token));
token = _token;
}
/// @notice update instance of MintableToken
function setToken(MintableToken _token) public onlyOwner {
token = _token;
}
function internalAllocate(address _holder, uint256 _tokens) internal {
token.mint(_holder, _tokens);
}
/// @notice Check whether contract is initialised
/// @return true if initialized
function isInitialized() public view returns (bool) {
return token.mintingAgents(this);
}
/// @return available tokens
function tokensAvailable() public view returns (uint256) {
return token.availableTokens();
}
}
/// @title ContributionForwarder
/// @author Applicature
/// @notice Contract is responsible for distributing collected ethers, that are received from CrowdSale.
/// @dev Base class
contract ContributionForwarder {
using SafeMath for uint256;
uint256 public weiCollected;
uint256 public weiForwarded;
event ContributionForwarded(address receiver, uint256 weiAmount);
function isInitialized() public view returns (bool) {
return false;
}
/// @notice transfer wei to receiver
function forward() public payable {
require(msg.value > 0);
weiCollected += msg.value;
internalForward();
}
function internalForward() internal;
}
/// @title DistributedDirectContributionForwarder
/// @author Applicature
/// @notice Contract is responsible for distributing collected ethers, that are received from CrowdSale.
/// @dev implementation
contract DistributedDirectContributionForwarder is ContributionForwarder {
Receiver[] public receivers;
uint256 public proportionAbsMax;
bool public isInitialized_;
struct Receiver {
address receiver;
uint256 proportion; // abslolute value in range of 0 - proportionAbsMax
uint256 forwardedWei;
}
constructor(uint256 _proportionAbsMax, address[] _receivers, uint256[] _proportions) public {
proportionAbsMax = _proportionAbsMax;
require(_receivers.length == _proportions.length);
require(_receivers.length > 0);
uint256 totalProportion;
for (uint256 i = 0; i < _receivers.length; i++) {
uint256 proportion = _proportions[i];
totalProportion = totalProportion.add(proportion);
receivers.push(Receiver(_receivers[i], proportion, 0));
}
require(totalProportion == proportionAbsMax);
isInitialized_ = true;
}
/// @notice Check whether contract is initialised
/// @return true if initialized
function isInitialized() public view returns (bool) {
return isInitialized_;
}
function internalForward() internal {
uint256 transferred;
for (uint256 i = 0; i < receivers.length; i++) {
Receiver storage receiver = receivers[i];
uint256 value = msg.value.mul(receiver.proportion).div(proportionAbsMax);
if (i == receivers.length - 1) {
value = msg.value.sub(transferred);
}
transferred = transferred.add(value);
receiver.receiver.transfer(value);
emit ContributionForwarded(receiver.receiver, value);
}
weiForwarded = weiForwarded.add(transferred);
}
}
contract Crowdsale {
uint256 public tokensSold;
enum State {Unknown, Initializing, BeforeCrowdsale, InCrowdsale, Success, Finalized, Refunding}
function externalContribution(address _contributor, uint256 _wei) public payable;
function contribute(uint8 _v, bytes32 _r, bytes32 _s) public payable;
function getState() public view returns (State);
function updateState() public;
function internalContribution(address _contributor, uint256 _wei) internal;
}
/// @title Crowdsale
/// @author Applicature
/// @notice Contract is responsible for collecting, refunding, allocating tokens during different stages of Crowdsale.
contract CrowdsaleImpl is Crowdsale, Ownable {
using SafeMath for uint256;
State public currentState;
TokenAllocator public allocator;
ContributionForwarder public contributionForwarder;
PricingStrategy public pricingStrategy;
CrowdsaleAgent public crowdsaleAgent;
bool public finalized;
uint256 public startDate;
uint256 public endDate;
bool public allowWhitelisted;
bool public allowSigned;
bool public allowAnonymous;
mapping(address => bool) public whitelisted;
mapping(address => bool) public signers;
mapping(address => bool) public externalContributionAgents;
event Contribution(address _contributor, uint256 _wei, uint256 _tokensExcludingBonus, uint256 _bonus);
constructor(
TokenAllocator _allocator,
ContributionForwarder _contributionForwarder,
PricingStrategy _pricingStrategy,
uint256 _startDate,
uint256 _endDate,
bool _allowWhitelisted,
bool _allowSigned,
bool _allowAnonymous
) public {
allocator = _allocator;
contributionForwarder = _contributionForwarder;
pricingStrategy = _pricingStrategy;
startDate = _startDate;
endDate = _endDate;
allowWhitelisted = _allowWhitelisted;
allowSigned = _allowSigned;
allowAnonymous = _allowAnonymous;
currentState = State.Unknown;
}
/// @notice default payable function
function() public payable {
require(allowWhitelisted || allowAnonymous);
if (!allowAnonymous) {
if (allowWhitelisted) {
require(whitelisted[msg.sender]);
}
}
internalContribution(msg.sender, msg.value);
}
/// @notice update crowdsale agent
function setCrowdsaleAgent(CrowdsaleAgent _crowdsaleAgent) public onlyOwner {
require(address(_crowdsaleAgent) != address(0));
crowdsaleAgent = _crowdsaleAgent;
}
/// @notice allows external user to do contribution
function externalContribution(address _contributor, uint256 _wei) public payable {
require(externalContributionAgents[msg.sender]);
internalContribution(_contributor, _wei);
}
/// @notice update external contributor
function addExternalContributor(address _contributor) public onlyOwner {
externalContributionAgents[_contributor] = true;
}
/// @notice update external contributor
function removeExternalContributor(address _contributor) public onlyOwner {
externalContributionAgents[_contributor] = false;
}
/// @notice update whitelisting address
function updateWhitelist(address _address, bool _status) public onlyOwner {
whitelisted[_address] = _status;
}
/// @notice update signer
function addSigner(address _signer) public onlyOwner {
signers[_signer] = true;
}
/// @notice update signer
function removeSigner(address _signer) public onlyOwner {
signers[_signer] = false;
}
/// @notice allows to do signed contributions
function contribute(uint8 _v, bytes32 _r, bytes32 _s) public payable {
address recoveredAddress = verify(msg.sender, _v, _r, _s);
require(signers[recoveredAddress]);
internalContribution(msg.sender, msg.value);
}
/// @notice check sign
function verify(address _sender, uint8 _v, bytes32 _r, bytes32 _s) public view returns (address) {
bytes32 hash = keccak256(abi.encodePacked(this, _sender));
bytes memory prefix = '\x19Ethereum Signed Message:\n32';
return ecrecover(keccak256(abi.encodePacked(prefix, hash)), _v, _r, _s);
}
/// @return Crowdsale state
function getState() public view returns (State) {
if (finalized) {
return State.Finalized;
} else if (allocator.isInitialized() == false) {
return State.Initializing;
} else if (contributionForwarder.isInitialized() == false) {
return State.Initializing;
} else if (pricingStrategy.isInitialized() == false) {
return State.Initializing;
} else if (block.timestamp < startDate) {
return State.BeforeCrowdsale;
} else if (block.timestamp >= startDate && block.timestamp <= endDate) {
return State.InCrowdsale;
} else if (block.timestamp > endDate) {
return State.Success;
}
return State.Unknown;
}
/// @notice Crowdsale state
function updateState() public {
State state = getState();
if (currentState != state) {
if (crowdsaleAgent != address(0)) {
crowdsaleAgent.onStateChange(state);
}
currentState = state;
}
}
function internalContribution(address _contributor, uint256 _wei) internal {
require(getState() == State.InCrowdsale);
uint256 tokensAvailable = allocator.tokensAvailable();
uint256 collectedWei = contributionForwarder.weiCollected();
uint256 tokens;
uint256 tokensExcludingBonus;
uint256 bonus;
(tokens, tokensExcludingBonus, bonus) = pricingStrategy.getTokens(
_contributor, tokensAvailable, tokensSold, _wei, collectedWei);
require(tokens > 0 && tokens <= tokensAvailable);
tokensSold = tokensSold.add(tokens);
allocator.allocate(_contributor, tokens);
if (msg.value > 0) {
contributionForwarder.forward.value(msg.value)();
}
emit Contribution(_contributor, _wei, tokensExcludingBonus, bonus);
}
}
/// @title HardCappedCrowdsale
/// @author Applicature
/// @notice Contract is responsible for collecting, refunding, allocating tokens during different stages of Crowdsale.
/// with hard limit
contract HardCappedCrowdsale is CrowdsaleImpl {
using SafeMath for uint256;
uint256 public hardCap;
constructor(
TokenAllocator _allocator,
ContributionForwarder _contributionForwarder,
PricingStrategy _pricingStrategy,
uint256 _startDate,
uint256 _endDate,
bool _allowWhitelisted,
bool _allowSigned,
bool _allowAnonymous,
uint256 _hardCap
) public CrowdsaleImpl(
_allocator,
_contributionForwarder,
_pricingStrategy,
_startDate,
_endDate,
_allowWhitelisted,
_allowSigned,
_allowAnonymous
) {
hardCap = _hardCap;
}
/// @return Crowdsale state
function getState() public view returns (State) {
State state = super.getState();
if (state == State.InCrowdsale) {
if (isHardCapAchieved(0)) {
return State.Success;
}
}
return state;
}
function isHardCapAchieved(uint256 _value) public view returns (bool) {
if (hardCap <= tokensSold.add(_value)) {
return true;
}
return false;
}
function internalContribution(address _contributor, uint256 _wei) internal {
require(getState() == State.InCrowdsale);
uint256 tokensAvailable = allocator.tokensAvailable();
uint256 collectedWei = contributionForwarder.weiCollected();
uint256 tokens;
uint256 tokensExcludingBonus;
uint256 bonus;
(tokens, tokensExcludingBonus, bonus) = pricingStrategy.getTokens(
_contributor, tokensAvailable, tokensSold, _wei, collectedWei);
require(tokens <= tokensAvailable && tokens > 0 && false == isHardCapAchieved(tokens.sub(1)));
tokensSold = tokensSold.add(tokens);
allocator.allocate(_contributor, tokens);
if (msg.value > 0) {
contributionForwarder.forward.value(msg.value)();
}
crowdsaleAgent.onContribution(_contributor, _wei, tokensExcludingBonus, bonus);
emit Contribution(_contributor, _wei, tokensExcludingBonus, bonus);
}
}
/// @title RefundableCrowdsale
/// @author Applicature
/// @notice Contract is responsible for collecting, refunding, allocating tokens during different stages of Crowdsale.
/// with hard and soft limits
contract RefundableCrowdsale is HardCappedCrowdsale {
using SafeMath for uint256;
uint256 public softCap;
mapping(address => uint256) public contributorsWei;
address[] public contributors;
event Refund(address _holder, uint256 _wei, uint256 _tokens);
constructor(
TokenAllocator _allocator,
ContributionForwarder _contributionForwarder,
PricingStrategy _pricingStrategy,
uint256 _startDate,
uint256 _endDate,
bool _allowWhitelisted,
bool _allowSigned,
bool _allowAnonymous,
uint256 _softCap,
uint256 _hardCap
) public HardCappedCrowdsale(
_allocator, _contributionForwarder, _pricingStrategy,
_startDate, _endDate,
_allowWhitelisted, _allowSigned, _allowAnonymous, _hardCap
) {
softCap = _softCap;
}
/// @return Crowdsale state
function getState() public view returns (State) {
State state = super.getState();
if (state == State.Success) {
if (!isSoftCapAchieved(0)) {
return State.Refunding;
}
}
return state;
}
function isSoftCapAchieved(uint256 _value) public view returns (bool) {
if (softCap <= tokensSold.add(_value)) {
return true;
}
return false;
}
/// @notice refund ethers to contributor
function refund() public {
internalRefund(msg.sender);
}
/// @notice refund ethers to delegate
function delegatedRefund(address _address) public {
internalRefund(_address);
}
function internalContribution(address _contributor, uint256 _wei) internal {
require(block.timestamp >= startDate && block.timestamp <= endDate);
uint256 tokensAvailable = allocator.tokensAvailable();
uint256 collectedWei = contributionForwarder.weiCollected();
uint256 tokens;
uint256 tokensExcludingBonus;
uint256 bonus;
(tokens, tokensExcludingBonus, bonus) = pricingStrategy.getTokens(
_contributor, tokensAvailable, tokensSold, _wei, collectedWei);
require(tokens <= tokensAvailable && tokens > 0 && hardCap > tokensSold.add(tokens));
tokensSold = tokensSold.add(tokens);
allocator.allocate(_contributor, tokens);
// transfer only if softcap is reached
if (isSoftCapAchieved(0)) {
if (msg.value > 0) {
contributionForwarder.forward.value(address(this).balance)();
}
} else {
// store contributor if it is not stored before
if (contributorsWei[_contributor] == 0) {
contributors.push(_contributor);
}
contributorsWei[_contributor] = contributorsWei[_contributor].add(msg.value);
}
crowdsaleAgent.onContribution(_contributor, _wei, tokensExcludingBonus, bonus);
emit Contribution(_contributor, _wei, tokensExcludingBonus, bonus);
}
function internalRefund(address _holder) internal {
updateState();
require(block.timestamp > endDate);
require(!isSoftCapAchieved(0));
require(crowdsaleAgent != address(0));
uint256 value = contributorsWei[_holder];
require(value > 0);
contributorsWei[_holder] = 0;
uint256 burnedTokens = crowdsaleAgent.onRefund(_holder, 0);
_holder.transfer(value);
emit Refund(_holder, value, burnedTokens);
}
}
contract ICUCrowdsale is RefundableCrowdsale {
uint256 public maxSaleSupply = 2350000000e18;
uint256 public availableBonusAmount = 447500000e18;
uint256 public usdCollected;
mapping(address => uint256) public contributorBonuses;
constructor(
MintableTokenAllocator _allocator,
DistributedDirectContributionForwarder _contributionForwarder,
ICUStrategy _pricingStrategy,
uint256 _startTime,
uint256 _endTime
) public RefundableCrowdsale(
_allocator,
_contributionForwarder,
_pricingStrategy,
_startTime,
_endTime,
true,
true,
false,
2500000e5, //softCap
23500000e5//hardCap
) {}
function updateState() public {
(startDate, endDate) = ICUStrategy(pricingStrategy).getActualDates();
super.updateState();
}
function claimBonuses() public {
require(isSoftCapAchieved(0) && contributorBonuses[msg.sender] > 0);
uint256 bonus = contributorBonuses[msg.sender];
contributorBonuses[msg.sender] = 0;
allocator.allocate(msg.sender, bonus);
}
function addExternalContributor(address) public onlyOwner {
require(false);
}
function isHardCapAchieved(uint256 _value) public view returns (bool) {
if (hardCap <= usdCollected.add(_value)) {
return true;
}
return false;
}
function isSoftCapAchieved(uint256 _value) public view returns (bool) {
if (softCap <= usdCollected.add(_value)) {
return true;
}
return false;
}
function internalContribution(address _contributor, uint256 _wei) internal {
updateState();
require(currentState == State.InCrowdsale);
ICUStrategy pricing = ICUStrategy(pricingStrategy);
uint256 usdAmount = pricing.getUSDAmount(_wei);
require(!isHardCapAchieved(usdAmount.sub(1)));
uint256 tokensAvailable = allocator.tokensAvailable();
uint256 collectedWei = contributionForwarder.weiCollected();
uint256 tierIndex = pricing.getTierIndex();
uint256 tokens;
uint256 tokensExcludingBonus;
uint256 bonus;
(tokens, tokensExcludingBonus, bonus) = pricing.getTokens(
_contributor, tokensAvailable, tokensSold, _wei, collectedWei
);
require(tokens > 0);
tokensSold = tokensSold.add(tokens);
allocator.allocate(_contributor, tokensExcludingBonus);
if (isSoftCapAchieved(usdAmount)) {
if (msg.value > 0) {
contributionForwarder.forward.value(address(this).balance)();
}
} else {
// store contributor if it is not stored before
if (contributorsWei[_contributor] == 0) {
contributors.push(_contributor);
}
contributorsWei[_contributor] = contributorsWei[_contributor].add(msg.value);
}
usdCollected = usdCollected.add(usdAmount);
if (availableBonusAmount > 0) {
if (availableBonusAmount >= bonus) {
availableBonusAmount -= bonus;
} else {
bonus = availableBonusAmount;
availableBonusAmount = 0;
}
contributorBonuses[_contributor] = contributorBonuses[_contributor].add(bonus);
} else {
bonus = 0;
}
crowdsaleAgent.onContribution(pricing, tierIndex, tokensExcludingBonus, bonus);
emit Contribution(_contributor, _wei, tokensExcludingBonus, bonus);
}
}
/// @title PricingStrategy
/// @author Applicature
/// @notice Contract is responsible for calculating tokens amount depending on different criterias
/// @dev Base class
contract PricingStrategy {
function isInitialized() public view returns (bool);
function getTokens(
address _contributor,
uint256 _tokensAvailable,
uint256 _tokensSold,
uint256 _weiAmount,
uint256 _collectedWei
)
public
view
returns (uint256 tokens, uint256 tokensExludingBonus, uint256 bonus);
function getWeis(
uint256 _collectedWei,
uint256 _tokensSold,
uint256 _tokens
)
public
view
returns (uint256 weiAmount, uint256 tokensBonus);
}
/// @title TokenDateCappedTiersPricingStrategy
/// @author Applicature
/// @notice Contract is responsible for calculating tokens amount depending on price in USD
/// @dev implementation
contract TokenDateCappedTiersPricingStrategy is PricingStrategy, Ownable {
using SafeMath for uint256;
uint256 public etherPriceInUSD;
uint256 public capsAmount;
struct Tier {
uint256 tokenInUSD;
uint256 maxTokensCollected;
uint256 soldTierTokens;
uint256 bonusTierTokens;
uint256 discountPercents;
uint256 minInvestInUSD;
uint256 startDate;
uint256 endDate;
bool unsoldProcessed;
uint256[] capsData;
}
Tier[] public tiers;
uint256 public decimals;
constructor(
uint256[] _tiers,
uint256[] _capsData,
uint256 _decimals,
uint256 _etherPriceInUSD
)
public
{
decimals = _decimals;
require(_etherPriceInUSD > 0);
etherPriceInUSD = _etherPriceInUSD;
require(_tiers.length % 6 == 0);
uint256 length = _tiers.length / 6;
require(_capsData.length % 2 == 0);
uint256 lengthCaps = _capsData.length / 2;
uint256[] memory emptyArray;
for (uint256 i = 0; i < length; i++) {
tiers.push(
Tier(
_tiers[i * 6],//tokenInUSD
_tiers[i * 6 + 1],//maxTokensCollected
0,//soldTierTokens
0,//bonusTierTokens
_tiers[i * 6 + 2],//discountPercents
_tiers[i * 6 + 3],//minInvestInUSD
_tiers[i * 6 + 4],//startDate
_tiers[i * 6 + 5],//endDate
false,
emptyArray//capsData
)
);
for (uint256 j = 0; j < lengthCaps; j++) {
tiers[i].capsData.push(_capsData[i * lengthCaps + j]);
}
}
}
/// @return tier index
function getTierIndex() public view returns (uint256) {
for (uint256 i = 0; i < tiers.length; i++) {
if (
block.timestamp >= tiers[i].startDate &&
block.timestamp < tiers[i].endDate &&
tiers[i].maxTokensCollected > tiers[i].soldTierTokens
) {
return i;
}
}
return tiers.length;
}
function getActualTierIndex() public view returns (uint256) {
for (uint256 i = 0; i < tiers.length; i++) {
if (
block.timestamp >= tiers[i].startDate
&& block.timestamp < tiers[i].endDate
&& tiers[i].maxTokensCollected > tiers[i].soldTierTokens
|| block.timestamp < tiers[i].startDate
) {
return i;
}
}
return tiers.length.sub(1);
}
/// @return actual dates
function getActualDates() public view returns (uint256 startDate, uint256 endDate) {
uint256 tierIndex = getActualTierIndex();
startDate = tiers[tierIndex].startDate;
endDate = tiers[tierIndex].endDate;
}
function getTokensWithoutRestrictions(uint256 _weiAmount) public view returns (
uint256 tokens,
uint256 tokensExcludingBonus,
uint256 bonus
) {
if (_weiAmount == 0) {
return (0, 0, 0);
}
uint256 tierIndex = getActualTierIndex();
tokensExcludingBonus = _weiAmount.mul(etherPriceInUSD).div(getTokensInUSD(tierIndex));
bonus = calculateBonusAmount(tierIndex, tokensExcludingBonus);
tokens = tokensExcludingBonus.add(bonus);
}
/// @return tokens based on sold tokens and wei amount
function getTokens(
address,
uint256 _tokensAvailable,
uint256,
uint256 _weiAmount,
uint256
) public view returns (uint256 tokens, uint256 tokensExcludingBonus, uint256 bonus) {
if (_weiAmount == 0) {
return (0, 0, 0);
}
uint256 tierIndex = getTierIndex();
if (tierIndex == tiers.length || _weiAmount.mul(etherPriceInUSD).div(1e18) < tiers[tierIndex].minInvestInUSD) {
return (0, 0, 0);
}
tokensExcludingBonus = _weiAmount.mul(etherPriceInUSD).div(getTokensInUSD(tierIndex));
if (tiers[tierIndex].maxTokensCollected < tiers[tierIndex].soldTierTokens.add(tokensExcludingBonus)) {
return (0, 0, 0);
}
bonus = calculateBonusAmount(tierIndex, tokensExcludingBonus);
tokens = tokensExcludingBonus.add(bonus);
if (tokens > _tokensAvailable) {
return (0, 0, 0);
}
}
/// @return weis based on sold and required tokens
function getWeis(
uint256,
uint256,
uint256 _tokens
) public view returns (uint256 totalWeiAmount, uint256 tokensBonus) {
if (_tokens == 0) {
return (0, 0);
}
uint256 tierIndex = getTierIndex();
if (tierIndex == tiers.length) {
return (0, 0);
}
if (tiers[tierIndex].maxTokensCollected < tiers[tierIndex].soldTierTokens.add(_tokens)) {
return (0, 0);
}
uint256 usdAmount = _tokens.mul(getTokensInUSD(tierIndex)).div(1e18);
totalWeiAmount = usdAmount.mul(1e18).div(etherPriceInUSD);
if (totalWeiAmount < uint256(1 ether).mul(tiers[tierIndex].minInvestInUSD).div(etherPriceInUSD)) {
return (0, 0);
}
tokensBonus = calculateBonusAmount(tierIndex, _tokens);
}
function calculateBonusAmount(uint256 _tierIndex, uint256 _tokens) public view returns (uint256 bonus) {
uint256 length = tiers[_tierIndex].capsData.length.div(2);
uint256 remainingTokens = _tokens;
uint256 newSoldTokens = tiers[_tierIndex].soldTierTokens;
for (uint256 i = 0; i < length; i++) {
if (tiers[_tierIndex].capsData[i.mul(2)] == 0) {
break;
}
if (newSoldTokens.add(remainingTokens) <= tiers[_tierIndex].capsData[i.mul(2)]) {
bonus += remainingTokens.mul(tiers[_tierIndex].capsData[i.mul(2).add(1)]).div(100);
break;
} else {
uint256 diff = tiers[_tierIndex].capsData[i.mul(2)].sub(newSoldTokens);
remainingTokens -= diff;
newSoldTokens += diff;
bonus += diff.mul(tiers[_tierIndex].capsData[i.mul(2).add(1)]).div(100);
}
}
}
function getTokensInUSD(uint256 _tierIndex) public view returns (uint256) {
if (_tierIndex < uint256(tiers.length)) {
return tiers[_tierIndex].tokenInUSD;
}
}
function getDiscount(uint256 _tierIndex) public view returns (uint256) {
if (_tierIndex < uint256(tiers.length)) {
return tiers[_tierIndex].discountPercents;
}
}
function getMinEtherInvest(uint256 _tierIndex) public view returns (uint256) {
if (_tierIndex < uint256(tiers.length)) {
return tiers[_tierIndex].minInvestInUSD.mul(1 ether).div(etherPriceInUSD);
}
}
function getUSDAmount(uint256 _weiAmount) public view returns (uint256) {
return _weiAmount.mul(etherPriceInUSD).div(1 ether);
}
/// @notice Check whether contract is initialised
/// @return true if initialized
function isInitialized() public view returns (bool) {
return true;
}
/// @notice updates tier start/end dates by id
function updateDates(uint8 _tierId, uint256 _start, uint256 _end) public onlyOwner() {
if (_start != 0 && _start < _end && _tierId < tiers.length) {
Tier storage tier = tiers[_tierId];
tier.startDate = _start;
tier.endDate = _end;
}
}
}
contract ICUStrategy is TokenDateCappedTiersPricingStrategy {
ICUAgent public agent;
event UnsoldTokensProcessed(uint256 fromTier, uint256 toTier, uint256 tokensAmount);
constructor(
uint256[] _emptyArray,
uint256 _etherPriceInUSD
) public TokenDateCappedTiersPricingStrategy(
_emptyArray,
_emptyArray,
18,
_etherPriceInUSD
) {
//Pre-ICO
tiers.push(
Tier(
0.01e5,//tokenInUSD
1000000000e18,//maxTokensCollected
0,//soldTierTokens
0,//bonusTierTokens
0,//discountPercents
uint256(20).mul(_etherPriceInUSD),//minInvestInUSD | 20 ethers
1543579200,//startDate | 2018/11/30 12:00:00 PM UTC
1544184000,//endDate | 2018/12/07 12:00:00 PM UTC
false,
_emptyArray
)
);
//ICO
tiers.push(
Tier(
0.01e5,//tokenInUSD
1350000000e18,//maxTokensCollected
0,//soldTierTokens
0,//bonusTierTokens
0,//discountPercents
uint256(_etherPriceInUSD).div(10),//minInvestInUSD | 0.1 ether
1544443200,//startDate | 2018/12/10 12:00:00 PM UTC
1546257600,//endDate | 2018/12/31 12:00:00 PM UTC
false,
_emptyArray
)
);
//Pre-ICO caps data
tiers[0].capsData.push(1000000000e18);//cap $10,000,000 in tokens
tiers[0].capsData.push(30);//bonus percents
//ICO caps data
tiers[1].capsData.push(400000000e18);//cap $4,000,000 in tokens
tiers[1].capsData.push(20);//bonus percents
tiers[1].capsData.push(800000000e18);//cap $4,000,000 in tokens
tiers[1].capsData.push(10);//bonus percents
tiers[1].capsData.push(1350000000e18);//cap $5,500,000 in tokens
tiers[1].capsData.push(5);//bonus percents
}
function getArrayOfTiers() public view returns (uint256[14] tiersData) {
uint256 j = 0;
for (uint256 i = 0; i < tiers.length; i++) {
tiersData[j++] = uint256(tiers[i].tokenInUSD);
tiersData[j++] = uint256(tiers[i].maxTokensCollected);
tiersData[j++] = uint256(tiers[i].soldTierTokens);
tiersData[j++] = uint256(tiers[i].discountPercents);
tiersData[j++] = uint256(tiers[i].minInvestInUSD);
tiersData[j++] = uint256(tiers[i].startDate);
tiersData[j++] = uint256(tiers[i].endDate);
}
}
function updateTier(
uint256 _tierId,
uint256 _start,
uint256 _end,
uint256 _minInvest,
uint256 _price,
uint256 _discount,
uint256[] _capsData,
bool updateLockNeeded
) public onlyOwner() {
require(
_start != 0 &&
_price != 0 &&
_start < _end &&
_tierId < tiers.length &&
_capsData.length > 0 &&
_capsData.length % 2 == 0
);
if (updateLockNeeded) {
agent.updateLockPeriod(_end);
}
Tier storage tier = tiers[_tierId];
tier.tokenInUSD = _price;
tier.discountPercents = _discount;
tier.minInvestInUSD = _minInvest;
tier.startDate = _start;
tier.endDate = _end;
tier.capsData = _capsData;
}
function setCrowdsaleAgent(ICUAgent _crowdsaleAgent) public onlyOwner {
agent = _crowdsaleAgent;
}
function updateTierState(uint256 _tierId, uint256 _soldTokens, uint256 _bonusTokens) public {
require(
msg.sender == address(agent) &&
_tierId < tiers.length &&
_soldTokens > 0
);
Tier storage tier = tiers[_tierId];
if (_tierId > 0 && !tiers[_tierId.sub(1)].unsoldProcessed) {
Tier storage prevTier = tiers[_tierId.sub(1)];
prevTier.unsoldProcessed = true;
uint256 unsold = prevTier.maxTokensCollected.sub(prevTier.soldTierTokens);
tier.maxTokensCollected = tier.maxTokensCollected.add(unsold);
tier.capsData[0] = tier.capsData[0].add(unsold);
emit UnsoldTokensProcessed(_tierId.sub(1), _tierId, unsold);
}
tier.soldTierTokens = tier.soldTierTokens.add(_soldTokens);
tier.bonusTierTokens = tier.bonusTierTokens.add(_bonusTokens);
}
function getTierUnsoldTokens(uint256 _tierId) public view returns (uint256) {
if (_tierId >= tiers.length || tiers[_tierId].unsoldProcessed) {
return 0;
}
return tiers[_tierId].maxTokensCollected.sub(tiers[_tierId].soldTierTokens);
}
function getUnsoldTokens() public view returns (uint256 unsoldTokens) {
for (uint256 i = 0; i < tiers.length; i++) {
unsoldTokens += getTierUnsoldTokens(i);
}
}
function getCapsData(uint256 _tierId) public view returns (uint256[]) {
if (_tierId < tiers.length) {
return tiers[_tierId].capsData;
}
}
}
contract Referral is Ownable {
using SafeMath for uint256;
MintableTokenAllocator public allocator;
CrowdsaleImpl public crowdsale;
uint256 public constant DECIMALS = 18;
uint256 public totalSupply;
bool public unLimited;
bool public sentOnce;
mapping(address => bool) public claimed;
mapping(address => uint256) public claimedBalances;
constructor(
uint256 _totalSupply,
address _allocator,
address _crowdsale,
bool _sentOnce
) public {
require(_allocator != address(0) && _crowdsale != address(0));
totalSupply = _totalSupply;
if (totalSupply == 0) {
unLimited = true;
}
allocator = MintableTokenAllocator(_allocator);
crowdsale = CrowdsaleImpl(_crowdsale);
sentOnce = _sentOnce;
}
function setAllocator(address _allocator) public onlyOwner {
require(_allocator != address(0));
allocator = MintableTokenAllocator(_allocator);
}
function setCrowdsale(address _crowdsale) public onlyOwner {
require(_crowdsale != address(0));
crowdsale = CrowdsaleImpl(_crowdsale);
}
function multivestMint(
address _address,
uint256 _amount,
uint8 _v,
bytes32 _r,
bytes32 _s
) public {
require(true == crowdsale.signers(verify(msg.sender, _amount, _v, _r, _s)));
if (true == sentOnce) {
require(claimed[_address] == false);
claimed[_address] = true;
}
require(
_address == msg.sender &&
_amount > 0 &&
(true == unLimited || _amount <= totalSupply)
);
claimedBalances[_address] = claimedBalances[_address].add(_amount);
if (false == unLimited) {
totalSupply = totalSupply.sub(_amount);
}
allocator.allocate(_address, _amount);
}
/// @notice check sign
function verify(address _sender, uint256 _amount, uint8 _v, bytes32 _r, bytes32 _s) public pure returns (address) {
bytes32 hash = keccak256(abi.encodePacked(_sender, _amount));
bytes memory prefix = '\x19Ethereum Signed Message:\n32';
return ecrecover(keccak256(abi.encodePacked(prefix, hash)), _v, _r, _s);
}
}
contract ICUReferral is Referral {
constructor(
address _allocator,
address _crowdsale
) public Referral(35000000e18, _allocator, _crowdsale, true) {}
function multivestMint(
address _address,
uint256 _amount,
uint8 _v,
bytes32 _r,
bytes32 _s
) public {
ICUCrowdsale icuCrowdsale = ICUCrowdsale(crowdsale);
icuCrowdsale.updateState();
require(icuCrowdsale.isSoftCapAchieved(0) && block.timestamp > icuCrowdsale.endDate());
super.multivestMint(_address, _amount, _v, _r, _s);
}
}
contract Stats {
using SafeMath for uint256;
MintableToken public token;
MintableTokenAllocator public allocator;
ICUCrowdsale public crowdsale;
ICUStrategy public pricing;
constructor(
MintableToken _token,
MintableTokenAllocator _allocator,
ICUCrowdsale _crowdsale,
ICUStrategy _pricing
) public {
token = _token;
allocator = _allocator;
crowdsale = _crowdsale;
pricing = _pricing;
}
function getTokens(
uint256,
uint256 _weiAmount
) public view returns (uint256 tokens, uint256 tokensExcludingBonus, uint256 bonus) {
return pricing.getTokensWithoutRestrictions(_weiAmount);
}
function getWeis(
uint256,
uint256 _tokenAmount
) public view returns (uint256 totalWeiAmount, uint256 tokensBonus) {
return pricing.getWeis(0, 0, _tokenAmount);
}
function getStats(uint256 _userType, uint256[7] _ethPerCurrency) public view returns (
uint256[8] stats,
uint256[26] tiersData,
uint256[21] currencyContr //tokensPerEachCurrency,
) {
stats = getStatsData(_userType);
tiersData = getTiersData(_userType);
currencyContr = getCurrencyContrData(_userType, _ethPerCurrency);
}
function getTiersData(uint256) public view returns (
uint256[26] tiersData
) {
uint256[14] memory tiers = pricing.getArrayOfTiers();
uint256 tierElements = tiers.length.div(2);
uint256 j = 0;
for (uint256 i = 0; i <= tierElements; i += tierElements) {
tiersData[j++] = uint256(1e23).div(tiers[i]);// tokenInUSD;
tiersData[j++] = 0;// tokenInWei;
tiersData[j++] = uint256(tiers[i.add(1)]);// maxTokensCollected;
tiersData[j++] = uint256(tiers[i.add(2)]);// soldTierTokens;
tiersData[j++] = 0;// discountPercents;
tiersData[j++] = 0;// bonusPercents;
tiersData[j++] = uint256(tiers[i.add(4)]);// minInvestInUSD;
tiersData[j++] = 0;// minInvestInWei;
tiersData[j++] = 0;// maxInvestInUSD;
tiersData[j++] = 0;// maxInvestInWei;
tiersData[j++] = uint256(tiers[i.add(5)]);// startDate;
tiersData[j++] = uint256(tiers[i.add(6)]);// endDate;
tiersData[j++] = 1;
}
tiersData[25] = 2;
}
function getStatsData(uint256 _type) public view returns (
uint256[8] stats
) {
_type = _type;
stats[0] = token.maxSupply();
stats[1] = token.totalSupply();
stats[2] = crowdsale.maxSaleSupply();
stats[3] = crowdsale.tokensSold();
stats[4] = uint256(crowdsale.currentState());
stats[5] = pricing.getActualTierIndex();
stats[6] = pricing.getTierUnsoldTokens(stats[5]);
stats[7] = pricing.getMinEtherInvest(stats[5]);
}
function getCurrencyContrData(uint256 _type, uint256[7] _ethPerCurrency) public view returns (
uint256[21] currencyContr
) {
_type = _type;
uint256 j = 0;
for (uint256 i = 0; i < _ethPerCurrency.length; i++) {
(currencyContr[j++], currencyContr[j++], currencyContr[j++]) = pricing.getTokensWithoutRestrictions(
_ethPerCurrency[i]
);
}
}
}
contract PeriodicTokenVesting is TokenVesting {
address public unreleasedHolder;
uint256 public periods;
constructor(
address _beneficiary,
uint256 _start,
uint256 _cliff,
uint256 _duration,
uint256 _periods,
bool _revocable,
address _unreleasedHolder
)
public TokenVesting(_beneficiary, _start, _cliff, _duration, _revocable)
{
require(_revocable == false || _unreleasedHolder != address(0));
periods = _periods;
unreleasedHolder = _unreleasedHolder;
}
/**
* @dev Calculates the amount that has already vested.
* @param token ERC20 token which is being vested
*/
function vestedAmount(ERC20Basic token) public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[token]);
if (now < cliff) {
return 0;
} else if (now >= start.add(duration * periods) || revoked[token]) {
return totalBalance;
} else {
uint256 periodTokens = totalBalance.div(periods);
uint256 periodsOver = now.sub(start).div(duration);
if (periodsOver >= periods) {
return totalBalance;
}
return periodTokens.mul(periodsOver);
}
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(ERC20Basic token) public onlyOwner {
require(revocable);
require(!revoked[token]);
uint256 balance = token.balanceOf(this);
uint256 unreleased = releasableAmount(token);
uint256 refund = balance.sub(unreleased);
revoked[token] = true;
token.safeTransfer(unreleasedHolder, refund);
emit Revoked();
}
}
contract ICUAllocation is Ownable {
using SafeERC20 for ERC20Basic;
using SafeMath for uint256;
uint256 public constant BOUNTY_TOKENS = 47000000e18;
uint256 public constant MAX_TREASURY_TOKENS = 2350000000e18;
uint256 public icoEndTime;
address[] public vestings;
address public bountyAddress;
address public treasuryAddress;
bool public isBountySent;
bool public isTeamSent;
event VestingCreated(
address _vesting,
address _beneficiary,
uint256 _start,
uint256 _cliff,
uint256 _duration,
uint256 _periods,
bool _revocable
);
event VestingRevoked(address _vesting);
constructor(address _bountyAddress, address _treasuryAddress) public {
require(_bountyAddress != address(0) && _treasuryAddress != address(0));
bountyAddress = _bountyAddress;
treasuryAddress = _treasuryAddress;
}
function setICOEndTime(uint256 _icoEndTime) public onlyOwner {
icoEndTime = _icoEndTime;
}
function allocateBounty(MintableTokenAllocator _allocator, ICUCrowdsale _crowdsale) public onlyOwner {
require(!isBountySent && icoEndTime < block.timestamp && _crowdsale.isSoftCapAchieved(0));
isBountySent = true;
_allocator.allocate(bountyAddress, BOUNTY_TOKENS);
}
function allocateTreasury(MintableTokenAllocator _allocator) public onlyOwner {
require(icoEndTime < block.timestamp, 'ICO is not ended');
require(isBountySent, 'Bounty is not sent');
require(isTeamSent, 'Team vesting is not created');
require(MAX_TREASURY_TOKENS >= _allocator.tokensAvailable(), 'Unsold tokens are not burned');
_allocator.allocate(treasuryAddress, _allocator.tokensAvailable());
}
function createVesting(
address _beneficiary,
uint256 _start,
uint256 _cliff,
uint256 _duration,
uint256 _periods,
bool _revocable,
address _unreleasedHolder,
MintableTokenAllocator _allocator,
uint256 _amount
) public onlyOwner returns (PeriodicTokenVesting) {
require(icoEndTime > 0 && _amount > 0);
isTeamSent = true;
PeriodicTokenVesting vesting = new PeriodicTokenVesting(
_beneficiary, _start, _cliff, _duration, _periods, _revocable, _unreleasedHolder
);
vestings.push(vesting);
emit VestingCreated(vesting, _beneficiary, _start, _cliff, _duration, _periods, _revocable);
_allocator.allocate(address(vesting), _amount);
return vesting;
}
function revokeVesting(PeriodicTokenVesting _vesting, ERC20Basic token) public onlyOwner() {
_vesting.revoke(token);
emit VestingRevoked(_vesting);
}
}
|
@title Crowdsale @author Applicature @notice Contract is responsible for collecting, refunding, allocating tokens during different stages of Crowdsale.
|
contract CrowdsaleImpl is Crowdsale, Ownable {
using SafeMath for uint256;
State public currentState;
TokenAllocator public allocator;
ContributionForwarder public contributionForwarder;
PricingStrategy public pricingStrategy;
CrowdsaleAgent public crowdsaleAgent;
bool public finalized;
uint256 public startDate;
uint256 public endDate;
bool public allowWhitelisted;
bool public allowSigned;
bool public allowAnonymous;
mapping(address => bool) public whitelisted;
mapping(address => bool) public signers;
mapping(address => bool) public externalContributionAgents;
event Contribution(address _contributor, uint256 _wei, uint256 _tokensExcludingBonus, uint256 _bonus);
constructor(
TokenAllocator _allocator,
ContributionForwarder _contributionForwarder,
PricingStrategy _pricingStrategy,
uint256 _startDate,
uint256 _endDate,
bool _allowWhitelisted,
bool _allowSigned,
bool _allowAnonymous
) public {
allocator = _allocator;
contributionForwarder = _contributionForwarder;
pricingStrategy = _pricingStrategy;
startDate = _startDate;
endDate = _endDate;
allowWhitelisted = _allowWhitelisted;
allowSigned = _allowSigned;
allowAnonymous = _allowAnonymous;
currentState = State.Unknown;
}
function() public payable {
require(allowWhitelisted || allowAnonymous);
if (!allowAnonymous) {
if (allowWhitelisted) {
require(whitelisted[msg.sender]);
}
}
internalContribution(msg.sender, msg.value);
}
function() public payable {
require(allowWhitelisted || allowAnonymous);
if (!allowAnonymous) {
if (allowWhitelisted) {
require(whitelisted[msg.sender]);
}
}
internalContribution(msg.sender, msg.value);
}
function() public payable {
require(allowWhitelisted || allowAnonymous);
if (!allowAnonymous) {
if (allowWhitelisted) {
require(whitelisted[msg.sender]);
}
}
internalContribution(msg.sender, msg.value);
}
function setCrowdsaleAgent(CrowdsaleAgent _crowdsaleAgent) public onlyOwner {
require(address(_crowdsaleAgent) != address(0));
crowdsaleAgent = _crowdsaleAgent;
}
function externalContribution(address _contributor, uint256 _wei) public payable {
require(externalContributionAgents[msg.sender]);
internalContribution(_contributor, _wei);
}
function addExternalContributor(address _contributor) public onlyOwner {
externalContributionAgents[_contributor] = true;
}
function removeExternalContributor(address _contributor) public onlyOwner {
externalContributionAgents[_contributor] = false;
}
function updateWhitelist(address _address, bool _status) public onlyOwner {
whitelisted[_address] = _status;
}
function addSigner(address _signer) public onlyOwner {
signers[_signer] = true;
}
function removeSigner(address _signer) public onlyOwner {
signers[_signer] = false;
}
function contribute(uint8 _v, bytes32 _r, bytes32 _s) public payable {
address recoveredAddress = verify(msg.sender, _v, _r, _s);
require(signers[recoveredAddress]);
internalContribution(msg.sender, msg.value);
}
function verify(address _sender, uint8 _v, bytes32 _r, bytes32 _s) public view returns (address) {
bytes32 hash = keccak256(abi.encodePacked(this, _sender));
bytes memory prefix = '\x19Ethereum Signed Message:\n32';
return ecrecover(keccak256(abi.encodePacked(prefix, hash)), _v, _r, _s);
}
function getState() public view returns (State) {
if (finalized) {
return State.Finalized;
return State.Initializing;
return State.Initializing;
return State.Initializing;
return State.BeforeCrowdsale;
return State.InCrowdsale;
return State.Success;
}
return State.Unknown;
}
function getState() public view returns (State) {
if (finalized) {
return State.Finalized;
return State.Initializing;
return State.Initializing;
return State.Initializing;
return State.BeforeCrowdsale;
return State.InCrowdsale;
return State.Success;
}
return State.Unknown;
}
} else if (allocator.isInitialized() == false) {
} else if (contributionForwarder.isInitialized() == false) {
} else if (pricingStrategy.isInitialized() == false) {
} else if (block.timestamp < startDate) {
} else if (block.timestamp >= startDate && block.timestamp <= endDate) {
} else if (block.timestamp > endDate) {
function updateState() public {
State state = getState();
if (currentState != state) {
if (crowdsaleAgent != address(0)) {
crowdsaleAgent.onStateChange(state);
}
currentState = state;
}
}
function updateState() public {
State state = getState();
if (currentState != state) {
if (crowdsaleAgent != address(0)) {
crowdsaleAgent.onStateChange(state);
}
currentState = state;
}
}
function updateState() public {
State state = getState();
if (currentState != state) {
if (crowdsaleAgent != address(0)) {
crowdsaleAgent.onStateChange(state);
}
currentState = state;
}
}
function internalContribution(address _contributor, uint256 _wei) internal {
require(getState() == State.InCrowdsale);
uint256 tokensAvailable = allocator.tokensAvailable();
uint256 collectedWei = contributionForwarder.weiCollected();
uint256 tokens;
uint256 tokensExcludingBonus;
uint256 bonus;
(tokens, tokensExcludingBonus, bonus) = pricingStrategy.getTokens(
_contributor, tokensAvailable, tokensSold, _wei, collectedWei);
require(tokens > 0 && tokens <= tokensAvailable);
tokensSold = tokensSold.add(tokens);
allocator.allocate(_contributor, tokens);
if (msg.value > 0) {
contributionForwarder.forward.value(msg.value)();
}
emit Contribution(_contributor, _wei, tokensExcludingBonus, bonus);
}
function internalContribution(address _contributor, uint256 _wei) internal {
require(getState() == State.InCrowdsale);
uint256 tokensAvailable = allocator.tokensAvailable();
uint256 collectedWei = contributionForwarder.weiCollected();
uint256 tokens;
uint256 tokensExcludingBonus;
uint256 bonus;
(tokens, tokensExcludingBonus, bonus) = pricingStrategy.getTokens(
_contributor, tokensAvailable, tokensSold, _wei, collectedWei);
require(tokens > 0 && tokens <= tokensAvailable);
tokensSold = tokensSold.add(tokens);
allocator.allocate(_contributor, tokens);
if (msg.value > 0) {
contributionForwarder.forward.value(msg.value)();
}
emit Contribution(_contributor, _wei, tokensExcludingBonus, bonus);
}
}
| 13,111,383 |
[
1,
39,
492,
2377,
5349,
225,
1716,
1780,
1231,
225,
13456,
353,
14549,
364,
30160,
16,
1278,
14351,
16,
4767,
1776,
2430,
4982,
3775,
20298,
434,
385,
492,
2377,
5349,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
385,
492,
2377,
5349,
2828,
353,
385,
492,
2377,
5349,
16,
14223,
6914,
288,
203,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
3287,
1071,
17773,
31,
203,
565,
3155,
21156,
1071,
26673,
31,
203,
565,
735,
4027,
30839,
1071,
24880,
30839,
31,
203,
565,
453,
1512,
25866,
1071,
31765,
4525,
31,
203,
565,
385,
492,
2377,
5349,
3630,
1071,
276,
492,
2377,
5349,
3630,
31,
203,
565,
1426,
1071,
727,
1235,
31,
203,
565,
2254,
5034,
1071,
12572,
31,
203,
565,
2254,
5034,
1071,
13202,
31,
203,
565,
1426,
1071,
1699,
18927,
329,
31,
203,
565,
1426,
1071,
1699,
12294,
31,
203,
565,
1426,
1071,
1699,
18792,
31,
203,
565,
2874,
12,
2867,
516,
1426,
13,
1071,
26944,
31,
203,
565,
2874,
12,
2867,
516,
1426,
13,
1071,
1573,
414,
31,
203,
565,
2874,
12,
2867,
516,
1426,
13,
1071,
3903,
442,
4027,
23400,
31,
203,
203,
565,
871,
735,
4027,
12,
2867,
389,
591,
19293,
16,
2254,
5034,
389,
1814,
77,
16,
2254,
5034,
389,
7860,
424,
18596,
38,
22889,
16,
2254,
5034,
389,
18688,
407,
1769,
203,
203,
565,
3885,
12,
203,
3639,
3155,
21156,
389,
9853,
639,
16,
203,
3639,
735,
4027,
30839,
389,
591,
4027,
30839,
16,
203,
3639,
453,
1512,
25866,
389,
683,
14774,
4525,
16,
203,
3639,
2254,
5034,
389,
1937,
1626,
16,
203,
3639,
2254,
5034,
389,
409,
1626,
16,
203,
3639,
1426,
389,
5965,
18927,
329,
16,
203,
3639,
1426,
389,
5965,
12294,
16,
203,
3639,
1426,
389,
5965,
18792,
2
] |
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./interfaces/IRewardDistributionRecipient.sol";
import "./token/TokenWrapper.sol";
import "./internal/SponsorWhitelistControl.sol";
import "@openzeppelin/contracts/token/ERC777/IERC777.sol";
import "@openzeppelin/contracts/token/ERC777/IERC777Recipient.sol";
import "@openzeppelin/contracts/introspection/IERC1820Registry.sol";
contract MainArtPool is
TokenWrapper,
IRewardDistributionRecipient,
IERC777Recipient
{
IERC777 public artCoin;
uint256 public constant DURATION = 30 days;
uint256 public initreward = 200000 * 10**18; // total:500w
uint256 public starttime;
uint256 public periodFinish = 0;
uint256 public rewardRate = 0;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards;
event RewardAdded(uint256 reward);
event Staked(address indexed user, uint256 amount);
event Withdrawn(address indexed user, uint256 amount);
event RewardPaid(address indexed user, uint256 reward);
mapping(address => bool) public miners;
modifier onlyMiner() {
require(miners[msg.sender], "Not miner");
_;
}
IERC1820Registry private _erc1820 =
IERC1820Registry(0x88887eD889e776bCBe2f0f9932EcFaBcDfCd1820);
// keccak256("ERC777TokensRecipient")
bytes32 private constant TOKENS_RECIPIENT_INTERFACE_HASH =
0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b;
SponsorWhitelistControl public constant SPONSOR =
SponsorWhitelistControl(
address(0x0888000000000000000000000000000000000001)
);
constructor(address artCoin_, uint256 starttime_) public {
_erc1820.setInterfaceImplementer(
address(this),
TOKENS_RECIPIENT_INTERFACE_HASH,
address(this)
);
artCoin = IERC777(artCoin_);
starttime = starttime_;
// register all users as sponsees
address[] memory users = new address[](1);
users[0] = address(0);
SPONSOR.addPrivilege(users);
}
modifier updateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
function addMiner(address _miner) public onlyOwner() {
miners[_miner] = true;
}
function removeMiner(address _miner) public onlyOwner() {
miners[_miner] = false;
}
function lastTimeRewardApplicable() public view returns (uint256) {
return Math.min(block.timestamp, periodFinish);
}
function rewardPerToken() public view returns (uint256) {
if (totalSupply() == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored.add(
lastTimeRewardApplicable()
.sub(lastUpdateTime)
.mul(rewardRate)
.mul(1e18)
.div(totalSupply())
);
}
//获取收益结果
function earned(address account) public view returns (uint256) {
return
balanceOf(account)
.mul(rewardPerToken().sub(userRewardPerTokenPaid[account]))
.div(1e18)
.add(rewards[account]);
}
//抵押
function stake()
public
payable
override
updateReward(msg.sender)
checkhalve()
checkStart()
{
uint256 amount = msg.value;
require(amount > 0, "stake amount error,must > 0");
super.stake();
emit Staked(msg.sender, amount);
}
//铸造用的方法,增加铸造的balance2
function stake2(address _sender, uint256 _amount)
public
override
updateReward(_sender)
checkhalve()
checkStart()
onlyMiner()
{
uint256 amount = _amount;
require(amount > 0, "stake amount error,must > 0");
super.stake2(_sender, _amount);
emit Staked(_sender, amount);
}
//扣除一定量的铸造时的抵押币,不需要转移,直接扣除就行
function withdraw2(address _sender, uint256 amount)
public
override
updateReward(_sender)
checkhalve()
checkStart()
onlyMiner()
{
require(amount > 0, "Cannot withdraw 0");
super.withdraw2(_sender, amount);
emit Withdrawn(_sender, amount);
}
//取出一定量的抵押币
function withdraw(uint256 amount)
public
override
updateReward(msg.sender)
checkhalve
checkStart
{
require(amount > 0, "Cannot withdraw 0");
super.withdraw(amount);
emit Withdrawn(msg.sender, amount);
}
//取出收益+抵押的所有币,只能取出balance1的币!!
function exit() external {
withdraw(balance1Of(msg.sender));
getReward();
}
//领取收益
function getReward() public updateReward(msg.sender) checkhalve checkStart {
uint256 reward = earned(msg.sender);
if (reward > 0) {
rewards[msg.sender] = 0;
artCoin.send(msg.sender, reward, "");
emit RewardPaid(msg.sender, reward);
}
}
modifier checkhalve() {
if (block.timestamp >= periodFinish) {
initreward = initreward.mul(96).div(100);
rewardRate = initreward.div(DURATION);
periodFinish = block.timestamp.add(DURATION);
emit RewardAdded(initreward);
}
_;
}
modifier checkStart() {
require(block.timestamp >= starttime, "not start");
_;
}
function notifyRewardAmount(uint256 reward)
external
override
onlyRewardDistribution
updateReward(address(0))
{
if (block.timestamp > starttime) {
if (block.timestamp >= periodFinish) {
rewardRate = reward.div(DURATION);
} else {
uint256 remaining = periodFinish.sub(block.timestamp);
uint256 leftover = remaining.mul(rewardRate);
rewardRate = reward.add(leftover).div(DURATION);
}
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp.add(DURATION);
emit RewardAdded(reward);
} else {
rewardRate = initreward.div(DURATION);
lastUpdateTime = starttime;
periodFinish = starttime.add(DURATION);
emit RewardAdded(reward);
}
}
function tokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
) external override {
//require(operator == address(artCoin), "Not artCoin");
}
}
|
register all users as sponsees
|
constructor(address artCoin_, uint256 starttime_) public {
_erc1820.setInterfaceImplementer(
address(this),
TOKENS_RECIPIENT_INTERFACE_HASH,
address(this)
);
artCoin = IERC777(artCoin_);
starttime = starttime_;
address[] memory users = new address[](1);
users[0] = address(0);
SPONSOR.addPrivilege(users);
}
| 1,032,829 |
[
1,
4861,
777,
3677,
487,
272,
575,
281,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3885,
12,
2867,
3688,
27055,
67,
16,
2254,
5034,
23437,
67,
13,
1071,
288,
203,
3639,
389,
12610,
2643,
3462,
18,
542,
1358,
5726,
264,
12,
203,
5411,
1758,
12,
2211,
3631,
203,
5411,
14275,
55,
67,
862,
7266,
1102,
2222,
67,
18865,
67,
15920,
16,
203,
5411,
1758,
12,
2211,
13,
203,
3639,
11272,
203,
3639,
3688,
27055,
273,
467,
654,
39,
14509,
12,
485,
27055,
67,
1769,
203,
3639,
23437,
273,
23437,
67,
31,
203,
203,
3639,
1758,
8526,
3778,
3677,
273,
394,
1758,
8526,
12,
21,
1769,
203,
3639,
3677,
63,
20,
65,
273,
1758,
12,
20,
1769,
203,
3639,
11405,
673,
55,
916,
18,
1289,
24308,
12,
5577,
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
] |
./full_match/1/0xe3C90b7e2BE74C4aEDb1F3511BC42F185a855b25/sources/DataStorage.sol
|
200k - 50k giveaway, 150k staking bonus
|
constructor(address m) {
masterContract = m;
_balances[address(0x7FB4eCD5b8E234fA5863bFa2799EA25D8819F42d)] = 200000.mul(10.pow(18));
_totalSupply = 200000.mul(10.pow(18));
}
| 4,886,772 |
[
1,
6976,
79,
300,
6437,
79,
8492,
26718,
16,
18478,
79,
384,
6159,
324,
22889,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3885,
12,
2867,
312,
13,
288,
203,
3639,
4171,
8924,
273,
312,
31,
203,
3639,
389,
70,
26488,
63,
2867,
12,
20,
92,
27,
22201,
24,
73,
10160,
25,
70,
28,
41,
17959,
29534,
8204,
4449,
70,
29634,
5324,
2733,
41,
37,
2947,
40,
5482,
3657,
42,
9452,
72,
25887,
273,
576,
11706,
18,
16411,
12,
2163,
18,
23509,
12,
2643,
10019,
203,
3639,
389,
4963,
3088,
1283,
273,
576,
11706,
18,
16411,
12,
2163,
18,
23509,
12,
2643,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/lib/math/SafeMath.sol
pragma solidity 0.5.12;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
// File: contracts/lib/ownership/Ownable.sol
pragma solidity 0.5.12;
/**
* @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 aplied to your functions to restrict their use to
* the owner.
*/
contract Ownable {
address public owner;
address public pendingOwner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
owner = msg.sender;
emit OwnershipTransferred(address(0), owner);
}
/**
* @dev Modifier throws if called by any account other than the pendingOwner.
*/
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner);
_;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return msg.sender == owner;
}
/**
* @dev Allows the current owner to set the pendingOwner address.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
pendingOwner = newOwner;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() public onlyPendingOwner {
emit OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
// File: contracts/lib/utils/ReentrancyGuard.sol
pragma solidity ^0.5.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the `nonReentrant` modifier
* available, which can be aplied 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 {
/// @dev counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
constructor () internal {
// 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");
}
}
// File: contracts/Utils.sol
pragma solidity 0.5.12;
interface ERC20 {
function balanceOf(address account) external view returns (uint256);
}
interface MarketDapp {
// Returns the address to approve tokens for
function tokenReceiver(address[] calldata assetIds, uint256[] calldata dataValues, address[] calldata addresses) external view returns(address);
function trade(address[] calldata assetIds, uint256[] calldata dataValues, address[] calldata addresses, address payable recipient) external payable;
}
/// @title Util functions for the BrokerV2 contract for Switcheo Exchange
/// @author Switcheo Network
/// @notice Functions were moved from the BrokerV2 contract into this contract
/// so that the BrokerV2 contract would not exceed the maximum contract size of
/// 24 KB.
library Utils {
using SafeMath for uint256;
// The constants for EIP-712 are precompiled to reduce contract size,
// the original values are left here for reference and verification.
//
// bytes32 public constant EIP712_DOMAIN_TYPEHASH = keccak256(abi.encodePacked(
// "EIP712Domain(",
// "string name,",
// "string version,",
// "uint256 chainId,",
// "address verifyingContract,",
// "bytes32 salt",
// ")"
// ));
// bytes32 public constant EIP712_DOMAIN_TYPEHASH = 0xd87cd6ef79d4e2b95e15ce8abf732db51ec771f1ca2edccf22a46c729ac56472;
//
// bytes32 public constant CONTRACT_NAME = keccak256("Switcheo Exchange");
// bytes32 public constant CONTRACT_VERSION = keccak256("2");
// uint256 public constant CHAIN_ID = 1;
// address public constant VERIFYING_CONTRACT = 0x7ee7Ca6E75dE79e618e88bDf80d0B1DB136b22D0;
// bytes32 public constant SALT = keccak256("switcheo-eth-salt");
// bytes32 public constant DOMAIN_SEPARATOR = keccak256(abi.encode(
// EIP712_DOMAIN_TYPEHASH,
// CONTRACT_NAME,
// CONTRACT_VERSION,
// CHAIN_ID,
// VERIFYING_CONTRACT,
// SALT
// ));
bytes32 public constant DOMAIN_SEPARATOR = 0x256c0713d13c6a01bd319a2f7edabde771b6c167d37c01778290d60b362ccc7d;
// bytes32 public constant OFFER_TYPEHASH = keccak256(abi.encodePacked(
// "Offer(",
// "address maker,",
// "address offerAssetId,",
// "uint256 offerAmount,",
// "address wantAssetId,",
// "uint256 wantAmount,",
// "address feeAssetId,",
// "uint256 feeAmount,",
// "uint256 nonce",
// ")"
// ));
bytes32 public constant OFFER_TYPEHASH = 0xf845c83a8f7964bc8dd1a092d28b83573b35be97630a5b8a3b8ae2ae79cd9260;
// bytes32 public constant CANCEL_TYPEHASH = keccak256(abi.encodePacked(
// "Cancel(",
// "bytes32 offerHash,",
// "address feeAssetId,",
// "uint256 feeAmount,",
// ")"
// ));
bytes32 public constant CANCEL_TYPEHASH = 0x46f6d088b1f0ff5a05c3f232c4567f2df96958e05457e6c0e1221dcee7d69c18;
// bytes32 public constant FILL_TYPEHASH = keccak256(abi.encodePacked(
// "Fill(",
// "address filler,",
// "address offerAssetId,",
// "uint256 offerAmount,",
// "address wantAssetId,",
// "uint256 wantAmount,",
// "address feeAssetId,",
// "uint256 feeAmount,",
// "uint256 nonce",
// ")"
// ));
bytes32 public constant FILL_TYPEHASH = 0x5f59dbc3412a4575afed909d028055a91a4250ce92235f6790c155a4b2669e99;
// The Ether token address is set as the constant 0x00 for backwards
// compatibility
address private constant ETHER_ADDR = address(0);
uint256 private constant mask8 = ~(~uint256(0) << 8);
uint256 private constant mask16 = ~(~uint256(0) << 16);
uint256 private constant mask24 = ~(~uint256(0) << 24);
uint256 private constant mask32 = ~(~uint256(0) << 32);
uint256 private constant mask40 = ~(~uint256(0) << 40);
uint256 private constant mask48 = ~(~uint256(0) << 48);
uint256 private constant mask56 = ~(~uint256(0) << 56);
uint256 private constant mask120 = ~(~uint256(0) << 120);
uint256 private constant mask128 = ~(~uint256(0) << 128);
uint256 private constant mask136 = ~(~uint256(0) << 136);
uint256 private constant mask144 = ~(~uint256(0) << 144);
event Trade(
address maker,
address taker,
address makerGiveAsset,
uint256 makerGiveAmount,
address fillerGiveAsset,
uint256 fillerGiveAmount
);
/// @dev Calculates the balance increments for a set of trades
/// @param _values The _values param from the trade method
/// @param _incrementsLength Should match the value of _addresses.length / 2
/// from the trade method
/// @return An array of increments
function calculateTradeIncrements(
uint256[] memory _values,
uint256 _incrementsLength
)
public
pure
returns (uint256[] memory)
{
uint256[] memory increments = new uint256[](_incrementsLength);
_creditFillBalances(increments, _values);
_creditMakerBalances(increments, _values);
_creditMakerFeeBalances(increments, _values);
return increments;
}
/// @dev Calculates the balance decrements for a set of trades
/// @param _values The _values param from the trade method
/// @param _decrementsLength Should match the value of _addresses.length / 2
/// from the trade method
/// @return An array of decrements
function calculateTradeDecrements(
uint256[] memory _values,
uint256 _decrementsLength
)
public
pure
returns (uint256[] memory)
{
uint256[] memory decrements = new uint256[](_decrementsLength);
_deductFillBalances(decrements, _values);
_deductMakerBalances(decrements, _values);
return decrements;
}
/// @dev Calculates the balance increments for a set of network trades
/// @param _values The _values param from the networkTrade method
/// @param _incrementsLength Should match the value of _addresses.length / 2
/// from the networkTrade method
/// @return An array of increments
function calculateNetworkTradeIncrements(
uint256[] memory _values,
uint256 _incrementsLength
)
public
pure
returns (uint256[] memory)
{
uint256[] memory increments = new uint256[](_incrementsLength);
_creditMakerBalances(increments, _values);
_creditMakerFeeBalances(increments, _values);
return increments;
}
/// @dev Calculates the balance decrements for a set of network trades
/// @param _values The _values param from the trade method
/// @param _decrementsLength Should match the value of _addresses.length / 2
/// from the networkTrade method
/// @return An array of decrements
function calculateNetworkTradeDecrements(
uint256[] memory _values,
uint256 _decrementsLength
)
public
pure
returns (uint256[] memory)
{
uint256[] memory decrements = new uint256[](_decrementsLength);
_deductMakerBalances(decrements, _values);
return decrements;
}
/// @dev Validates `BrokerV2.trade` parameters to ensure trade fairness,
/// see `BrokerV2.trade` for param details.
/// @param _values Values from `trade`
/// @param _hashes Hashes from `trade`
/// @param _addresses Addresses from `trade`
function validateTrades(
uint256[] memory _values,
bytes32[] memory _hashes,
address[] memory _addresses,
address _operator
)
public
returns (bytes32[] memory)
{
_validateTradeInputLengths(_values, _hashes);
_validateUniqueOffers(_values);
_validateMatches(_values, _addresses);
_validateFillAmounts(_values);
_validateTradeData(_values, _addresses, _operator);
// validate signatures of all offers
_validateTradeSignatures(
_values,
_hashes,
_addresses,
OFFER_TYPEHASH,
0,
_values[0] & mask8 // numOffers
);
// validate signatures of all fills
_validateTradeSignatures(
_values,
_hashes,
_addresses,
FILL_TYPEHASH,
_values[0] & mask8, // numOffers
(_values[0] & mask8) + ((_values[0] & mask16) >> 8) // numOffers + numFills
);
_emitTradeEvents(_values, _addresses, new address[](0), false);
return _hashes;
}
/// @dev Validates `BrokerV2.networkTrade` parameters to ensure trade fairness,
/// see `BrokerV2.networkTrade` for param details.
/// @param _values Values from `networkTrade`
/// @param _hashes Hashes from `networkTrade`
/// @param _addresses Addresses from `networkTrade`
/// @param _operator Address of the `BrokerV2.operator`
function validateNetworkTrades(
uint256[] memory _values,
bytes32[] memory _hashes,
address[] memory _addresses,
address _operator
)
public
pure
returns (bytes32[] memory)
{
_validateNetworkTradeInputLengths(_values, _hashes);
_validateUniqueOffers(_values);
_validateNetworkMatches(_values, _addresses, _operator);
_validateTradeData(_values, _addresses, _operator);
// validate signatures of all offers
_validateTradeSignatures(
_values,
_hashes,
_addresses,
OFFER_TYPEHASH,
0,
_values[0] & mask8 // numOffers
);
return _hashes;
}
/// @dev Executes trades against external markets,
/// see `BrokerV2.networkTrade` for param details.
/// @param _values Values from `networkTrade`
/// @param _addresses Addresses from `networkTrade`
/// @param _marketDapps See `BrokerV2.marketDapps`
function performNetworkTrades(
uint256[] memory _values,
address[] memory _addresses,
address[] memory _marketDapps
)
public
returns (uint256[] memory)
{
uint256[] memory increments = new uint256[](_addresses.length / 2);
// i = 1 + numOffers * 2
uint256 i = 1 + (_values[0] & mask8) * 2;
uint256 end = _values.length;
// loop matches
for(i; i < end; i++) {
uint256[] memory data = new uint256[](9);
data[0] = _values[i]; // match data
data[1] = data[0] & mask8; // offerIndex
data[2] = (data[0] & mask24) >> 16; // operator.surplusAssetIndex
data[3] = _values[data[1] * 2 + 1]; // offer.dataA
data[4] = _values[data[1] * 2 + 2]; // offer.dataB
data[5] = ((data[3] & mask16) >> 8); // maker.offerAssetIndex
data[6] = ((data[3] & mask24) >> 16); // maker.wantAssetIndex
// amount of offerAssetId to take from the offer is equal to the match.takeAmount
data[7] = data[0] >> 128;
// expected amount to receive is: matchData.takeAmount * offer.wantAmount / offer.offerAmount
data[8] = data[7].mul(data[4] >> 128).div(data[4] & mask128);
address[] memory assetIds = new address[](3);
assetIds[0] = _addresses[data[5] * 2 + 1]; // offer.offerAssetId
assetIds[1] = _addresses[data[6] * 2 + 1]; // offer.wantAssetId
assetIds[2] = _addresses[data[2] * 2 + 1]; // surplusAssetId
uint256[] memory dataValues = new uint256[](3);
dataValues[0] = data[7]; // the proportion of offerAmount to offer
dataValues[1] = data[8]; // the proportion of wantAmount to receive for the offer
dataValues[2] = data[0]; // match data
increments[data[2]] = _performNetworkTrade(
assetIds,
dataValues,
_marketDapps,
_addresses
);
}
_emitTradeEvents(_values, _addresses, _marketDapps, true);
return increments;
}
/// @dev Validates the signature of a cancel invocation
/// @param _values The _values param from the cancel method
/// @param _hashes The _hashes param from the cancel method
/// @param _addresses The _addresses param from the cancel method
function validateCancel(
uint256[] memory _values,
bytes32[] memory _hashes,
address[] memory _addresses
)
public
pure
{
bytes32 offerHash = hashOffer(_values, _addresses);
bytes32 cancelHash = keccak256(abi.encode(
CANCEL_TYPEHASH,
offerHash,
_addresses[4],
_values[1] >> 128
));
validateSignature(
cancelHash,
_addresses[0], // maker
uint8((_values[2] & mask144) >> 136), // v
_hashes[0], // r
_hashes[1], // s
((_values[2] & mask136) >> 128) != 0 // prefixedSignature
);
}
/// @dev Hashes an offer for the cancel method
/// @param _values The _values param from the cancel method
/// @param _addresses THe _addresses param from the cancel method
/// @return The hash of the offer
function hashOffer(
uint256[] memory _values,
address[] memory _addresses
)
public
pure
returns (bytes32)
{
return keccak256(abi.encode(
OFFER_TYPEHASH,
_addresses[0], // maker
_addresses[1], // offerAssetId
_values[0] & mask128, // offerAmount
_addresses[2], // wantAssetId
_values[0] >> 128, // wantAmount
_addresses[3], // feeAssetId
_values[1] & mask128, // feeAmount
_values[2] >> 144 // offerNonce
));
}
/// @notice Approves a token transfer
/// @param _assetId The address of the token to approve
/// @param _spender The address of the spender to approve
/// @param _amount The number of tokens to approve
function approveTokenTransfer(
address _assetId,
address _spender,
uint256 _amount
)
public
{
_validateContractAddress(_assetId);
// Some tokens have an `approve` which returns a boolean and some do not.
// The ERC20 interface cannot be used here because it requires specifying
// an explicit return value, and an EVM exception would be raised when calling
// a token with the mismatched return value.
bytes memory payload = abi.encodeWithSignature(
"approve(address,uint256)",
_spender,
_amount
);
bytes memory returnData = _callContract(_assetId, payload);
// Ensure that the asset transfer succeeded
_validateContractCallResult(returnData);
}
/// @notice Transfers tokens into the contract
/// @param _user The address to transfer the tokens from
/// @param _assetId The address of the token to transfer
/// @param _amount The number of tokens to transfer
/// @param _expectedAmount The number of tokens expected to be received,
/// this may not match `_amount`, for example, tokens which have a
/// proportion burnt on transfer will have a different amount received.
function transferTokensIn(
address _user,
address _assetId,
uint256 _amount,
uint256 _expectedAmount
)
public
{
_validateContractAddress(_assetId);
uint256 initialBalance = tokenBalance(_assetId);
// Some tokens have a `transferFrom` which returns a boolean and some do not.
// The ERC20 interface cannot be used here because it requires specifying
// an explicit return value, and an EVM exception would be raised when calling
// a token with the mismatched return value.
bytes memory payload = abi.encodeWithSignature(
"transferFrom(address,address,uint256)",
_user,
address(this),
_amount
);
bytes memory returnData = _callContract(_assetId, payload);
// Ensure that the asset transfer succeeded
_validateContractCallResult(returnData);
uint256 finalBalance = tokenBalance(_assetId);
uint256 transferredAmount = finalBalance.sub(initialBalance);
require(transferredAmount == _expectedAmount, "Invalid transfer");
}
/// @notice Transfers tokens from the contract to a user
/// @param _receivingAddress The address to transfer the tokens to
/// @param _assetId The address of the token to transfer
/// @param _amount The number of tokens to transfer
function transferTokensOut(
address _receivingAddress,
address _assetId,
uint256 _amount
)
public
{
_validateContractAddress(_assetId);
// Some tokens have a `transfer` which returns a boolean and some do not.
// The ERC20 interface cannot be used here because it requires specifying
// an explicit return value, and an EVM exception would be raised when calling
// a token with the mismatched return value.
bytes memory payload = abi.encodeWithSignature(
"transfer(address,uint256)",
_receivingAddress,
_amount
);
bytes memory returnData = _callContract(_assetId, payload);
// Ensure that the asset transfer succeeded
_validateContractCallResult(returnData);
}
/// @notice Returns the number of tokens owned by this contract
/// @param _assetId The address of the token to query
function externalBalance(address _assetId) public view returns (uint256) {
if (_assetId == ETHER_ADDR) {
return address(this).balance;
}
return tokenBalance(_assetId);
}
/// @notice Returns the number of tokens owned by this contract.
/// @dev This will not work for Ether tokens, use `externalBalance` for
/// Ether tokens.
/// @param _assetId The address of the token to query
function tokenBalance(address _assetId) public view returns (uint256) {
return ERC20(_assetId).balanceOf(address(this));
}
/// @dev Validates that the specified `_hash` was signed by the specified `_user`.
/// This method supports the EIP712 specification, the older Ethereum
/// signed message specification is also supported for backwards compatibility.
/// @param _hash The original hash that was signed by the user
/// @param _user The user who signed the hash
/// @param _v The `v` component of the `_user`'s signature
/// @param _r The `r` component of the `_user`'s signature
/// @param _s The `s` component of the `_user`'s signature
/// @param _prefixed If true, the signature will be verified
/// against the Ethereum signed message specification instead of the
/// EIP712 specification
function validateSignature(
bytes32 _hash,
address _user,
uint8 _v,
bytes32 _r,
bytes32 _s,
bool _prefixed
)
public
pure
{
bytes32 eip712Hash = keccak256(abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
_hash
));
if (_prefixed) {
bytes32 prefixedHash = keccak256(abi.encodePacked(
"\x19Ethereum Signed Message:\n32",
eip712Hash
));
require(_user == ecrecover(prefixedHash, _v, _r, _s), "Invalid signature");
} else {
require(_user == ecrecover(eip712Hash, _v, _r, _s), "Invalid signature");
}
}
/// @dev Ensures that `_address` is not the zero address
/// @param _address The address to check
function validateAddress(address _address) public pure {
require(_address != address(0), "Invalid address");
}
/// @dev Credit fillers for each fill.wantAmount,and credit the operator
/// for each fill.feeAmount. See the `trade` method for param details.
/// @param _values Values from `trade`
function _creditFillBalances(
uint256[] memory _increments,
uint256[] memory _values
)
private
pure
{
// 1 + numOffers * 2
uint256 i = 1 + (_values[0] & mask8) * 2;
// i + numFills * 2
uint256 end = i + ((_values[0] & mask16) >> 8) * 2;
// loop fills
for(i; i < end; i += 2) {
uint256 fillerWantAssetIndex = (_values[i] & mask24) >> 16;
uint256 wantAmount = _values[i + 1] >> 128;
// credit fill.wantAmount to filler
_increments[fillerWantAssetIndex] = _increments[fillerWantAssetIndex].add(wantAmount);
uint256 feeAmount = _values[i] >> 128;
if (feeAmount == 0) { continue; }
uint256 operatorFeeAssetIndex = ((_values[i] & mask40) >> 32);
// credit fill.feeAmount to operator
_increments[operatorFeeAssetIndex] = _increments[operatorFeeAssetIndex].add(feeAmount);
}
}
/// @dev Credit makers for each amount received through a matched fill.
/// See the `trade` method for param details.
/// @param _values Values from `trade`
function _creditMakerBalances(
uint256[] memory _increments,
uint256[] memory _values
)
private
pure
{
uint256 i = 1;
// i += numOffers * 2
i += (_values[0] & mask8) * 2;
// i += numFills * 2
i += ((_values[0] & mask16) >> 8) * 2;
uint256 end = _values.length;
// loop matches
for(i; i < end; i++) {
// match.offerIndex
uint256 offerIndex = _values[i] & mask8;
// maker.wantAssetIndex
uint256 makerWantAssetIndex = (_values[1 + offerIndex * 2] & mask24) >> 16;
// match.takeAmount
uint256 amount = _values[i] >> 128;
// receiveAmount = match.takeAmount * offer.wantAmount / offer.offerAmount
amount = amount.mul(_values[2 + offerIndex * 2] >> 128)
.div(_values[2 + offerIndex * 2] & mask128);
// credit maker for the amount received from the match
_increments[makerWantAssetIndex] = _increments[makerWantAssetIndex].add(amount);
}
}
/// @dev Credit the operator for each offer.feeAmount if the offer has not
/// been recorded through a previous `trade` call.
/// See the `trade` method for param details.
/// @param _values Values from `trade`
function _creditMakerFeeBalances(
uint256[] memory _increments,
uint256[] memory _values
)
private
pure
{
uint256 i = 1;
// i + numOffers * 2
uint256 end = i + (_values[0] & mask8) * 2;
// loop offers
for(i; i < end; i += 2) {
bool nonceTaken = ((_values[i] & mask128) >> 120) == 1;
if (nonceTaken) { continue; }
uint256 feeAmount = _values[i] >> 128;
if (feeAmount == 0) { continue; }
uint256 operatorFeeAssetIndex = (_values[i] & mask40) >> 32;
// credit make.feeAmount to operator
_increments[operatorFeeAssetIndex] = _increments[operatorFeeAssetIndex].add(feeAmount);
}
}
/// @dev Deduct tokens from fillers for each fill.offerAmount
/// and each fill.feeAmount.
/// See the `trade` method for param details.
/// @param _values Values from `trade`
function _deductFillBalances(
uint256[] memory _decrements,
uint256[] memory _values
)
private
pure
{
// 1 + numOffers * 2
uint256 i = 1 + (_values[0] & mask8) * 2;
// i + numFills * 2
uint256 end = i + ((_values[0] & mask16) >> 8) * 2;
// loop fills
for(i; i < end; i += 2) {
uint256 fillerOfferAssetIndex = (_values[i] & mask16) >> 8;
uint256 offerAmount = _values[i + 1] & mask128;
// deduct fill.offerAmount from filler
_decrements[fillerOfferAssetIndex] = _decrements[fillerOfferAssetIndex].add(offerAmount);
uint256 feeAmount = _values[i] >> 128;
if (feeAmount == 0) { continue; }
// deduct fill.feeAmount from filler
uint256 fillerFeeAssetIndex = (_values[i] & mask32) >> 24;
_decrements[fillerFeeAssetIndex] = _decrements[fillerFeeAssetIndex].add(feeAmount);
}
}
/// @dev Deduct tokens from makers for each offer.offerAmount
/// and each offer.feeAmount if the offer has not been recorded
/// through a previous `trade` call.
/// See the `trade` method for param details.
/// @param _values Values from `trade`
function _deductMakerBalances(
uint256[] memory _decrements,
uint256[] memory _values
)
private
pure
{
uint256 i = 1;
// i + numOffers * 2
uint256 end = i + (_values[0] & mask8) * 2;
// loop offers
for(i; i < end; i += 2) {
bool nonceTaken = ((_values[i] & mask128) >> 120) == 1;
if (nonceTaken) { continue; }
uint256 makerOfferAssetIndex = (_values[i] & mask16) >> 8;
uint256 offerAmount = _values[i + 1] & mask128;
// deduct make.offerAmount from maker
_decrements[makerOfferAssetIndex] = _decrements[makerOfferAssetIndex].add(offerAmount);
uint256 feeAmount = _values[i] >> 128;
if (feeAmount == 0) { continue; }
// deduct make.feeAmount from maker
uint256 makerFeeAssetIndex = (_values[i] & mask32) >> 24;
_decrements[makerFeeAssetIndex] = _decrements[makerFeeAssetIndex].add(feeAmount);
}
}
/// @dev Emits trade events for easier tracking
/// @param _values The _values param from the trade / networkTrade method
/// @param _addresses The _addresses param from the trade / networkTrade method
/// @param _marketDapps The _marketDapps from BrokerV2
/// @param _forNetworkTrade Whether this is called from the networkTrade method
function _emitTradeEvents(
uint256[] memory _values,
address[] memory _addresses,
address[] memory _marketDapps,
bool _forNetworkTrade
)
private
{
uint256 i = 1;
// i += numOffers * 2
i += (_values[0] & mask8) * 2;
// i += numFills * 2
i += ((_values[0] & mask16) >> 8) * 2;
uint256 end = _values.length;
// loop matches
for(i; i < end; i++) {
uint256[] memory data = new uint256[](7);
data[0] = _values[i] & mask8; // match.offerIndex
data[1] = _values[1 + data[0] * 2] & mask8; // makerIndex
data[2] = (_values[1 + data[0] * 2] & mask16) >> 8; // makerOfferAssetIndex
data[3] = (_values[1 + data[0] * 2] & mask24) >> 16; // makerWantAssetIndex
data[4] = _values[i] >> 128; // match.takeAmount
// receiveAmount = match.takeAmount * offer.wantAmount / offer.offerAmount
data[5] = data[4].mul(_values[2 + data[0] * 2] >> 128)
.div(_values[2 + data[0] * 2] & mask128);
// match.fillIndex for `trade`, marketDappIndex for `networkTrade`
data[6] = (_values[i] & mask16) >> 8;
address filler;
if (_forNetworkTrade) {
filler = _marketDapps[data[6]];
} else {
uint256 fillerIndex = (_values[1 + data[6] * 2] & mask8);
filler = _addresses[fillerIndex * 2];
}
emit Trade(
_addresses[data[1] * 2], // maker
filler,
_addresses[data[2] * 2 + 1], // makerGiveAsset
data[4], // makerGiveAmount
_addresses[data[3] * 2 + 1], // fillerGiveAsset
data[5] // fillerGiveAmount
);
}
}
/// @notice Executes a trade against an external market.
/// @dev The initial Ether or token balance is compared with the
/// balance after the trade to ensure that the appropriate amounts of
/// tokens were taken and an appropriate amount received.
/// The trade will fail if the number of tokens received is less than
/// expected. If the number of tokens received is more than expected than
/// the excess tokens are transferred to the `BrokerV2.operator`.
/// @param _assetIds[0] The offerAssetId of the offer
/// @param _assetIds[1] The wantAssetId of the offer
/// @param _assetIds[2] The surplusAssetId
/// @param _dataValues[0] The number of tokens offerred
/// @param _dataValues[1] The number of tokens expected to be received
/// @param _dataValues[2] Match data
/// @param _marketDapps See `BrokerV2.marketDapps`
/// @param _addresses Addresses from `networkTrade`
function _performNetworkTrade(
address[] memory _assetIds,
uint256[] memory _dataValues,
address[] memory _marketDapps,
address[] memory _addresses
)
private
returns (uint256)
{
uint256 dappIndex = (_dataValues[2] & mask16) >> 8;
validateAddress(_marketDapps[dappIndex]);
MarketDapp marketDapp = MarketDapp(_marketDapps[dappIndex]);
uint256[] memory funds = new uint256[](6);
funds[0] = externalBalance(_assetIds[0]); // initialOfferTokenBalance
funds[1] = externalBalance(_assetIds[1]); // initialWantTokenBalance
if (_assetIds[2] != _assetIds[0] && _assetIds[2] != _assetIds[1]) {
funds[2] = externalBalance(_assetIds[2]); // initialSurplusTokenBalance
}
uint256 ethValue = 0;
address tokenReceiver;
if (_assetIds[0] == ETHER_ADDR) {
ethValue = _dataValues[0]; // offerAmount
} else {
tokenReceiver = marketDapp.tokenReceiver(_assetIds, _dataValues, _addresses);
approveTokenTransfer(
_assetIds[0], // offerAssetId
tokenReceiver,
_dataValues[0] // offerAmount
);
}
marketDapp.trade.value(ethValue)(
_assetIds,
_dataValues,
_addresses,
// use uint160 to cast `address` to `address payable`
address(uint160(address(this))) // destAddress
);
funds[3] = externalBalance(_assetIds[0]); // finalOfferTokenBalance
funds[4] = externalBalance(_assetIds[1]); // finalWantTokenBalance
if (_assetIds[2] != _assetIds[0] && _assetIds[2] != _assetIds[1]) {
funds[5] = externalBalance(_assetIds[2]); // finalSurplusTokenBalance
}
uint256 surplusAmount = 0;
// validate that the appropriate offerAmount was deducted
// surplusAssetId == offerAssetId
if (_assetIds[2] == _assetIds[0]) {
// surplusAmount = finalOfferTokenBalance - (initialOfferTokenBalance - offerAmount)
surplusAmount = funds[3].sub(funds[0].sub(_dataValues[0]));
} else {
// finalOfferTokenBalance == initialOfferTokenBalance - offerAmount
require(funds[3] == funds[0].sub(_dataValues[0]), "Invalid offer asset balance");
}
// validate that the appropriate wantAmount was credited
// surplusAssetId == wantAssetId
if (_assetIds[2] == _assetIds[1]) {
// surplusAmount = finalWantTokenBalance - (initialWantTokenBalance + wantAmount)
surplusAmount = funds[4].sub(funds[1].add(_dataValues[1]));
} else {
// finalWantTokenBalance == initialWantTokenBalance + wantAmount
require(funds[4] == funds[1].add(_dataValues[1]), "Invalid want asset balance");
}
// surplusAssetId != offerAssetId && surplusAssetId != wantAssetId
if (_assetIds[2] != _assetIds[0] && _assetIds[2] != _assetIds[1]) {
// surplusAmount = finalSurplusTokenBalance - initialSurplusTokenBalance
surplusAmount = funds[5].sub(funds[2]);
}
// set the approved token amount back to zero
if (_assetIds[0] != ETHER_ADDR) {
approveTokenTransfer(
_assetIds[0],
tokenReceiver,
0
);
}
return surplusAmount;
}
/// @dev Validates input lengths based on the expected format
/// detailed in the `trade` method.
/// @param _values Values from `trade`
/// @param _hashes Hashes from `trade`
function _validateTradeInputLengths(
uint256[] memory _values,
bytes32[] memory _hashes
)
private
pure
{
uint256 numOffers = _values[0] & mask8;
uint256 numFills = (_values[0] & mask16) >> 8;
uint256 numMatches = (_values[0] & mask24) >> 16;
// Validate that bits(24..256) are zero
require(_values[0] >> 24 == 0, "Invalid trade input");
// It is enforced by other checks that if a fill is present
// then it must be completely filled so there must be at least one offer
// and at least one match in this case.
// It is possible to have one offer with no matches and no fills
// but that is blocked by this check as there is no foreseeable use
// case for it.
require(
numOffers > 0 && numFills > 0 && numMatches > 0,
"Invalid trade input"
);
require(
_values.length == 1 + numOffers * 2 + numFills * 2 + numMatches,
"Invalid _values.length"
);
require(
_hashes.length == (numOffers + numFills) * 2,
"Invalid _hashes.length"
);
}
/// @dev Validates input lengths based on the expected format
/// detailed in the `networkTrade` method.
/// @param _values Values from `networkTrade`
/// @param _hashes Hashes from `networkTrade`
function _validateNetworkTradeInputLengths(
uint256[] memory _values,
bytes32[] memory _hashes
)
private
pure
{
uint256 numOffers = _values[0] & mask8;
uint256 numFills = (_values[0] & mask16) >> 8;
uint256 numMatches = (_values[0] & mask24) >> 16;
// Validate that bits(24..256) are zero
require(_values[0] >> 24 == 0, "Invalid networkTrade input");
// Validate that numFills is zero because the offers
// should be filled against external orders
require(
numOffers > 0 && numMatches > 0 && numFills == 0,
"Invalid networkTrade input"
);
require(
_values.length == 1 + numOffers * 2 + numMatches,
"Invalid _values.length"
);
require(
_hashes.length == numOffers * 2,
"Invalid _hashes.length"
);
}
/// @dev See the `BrokerV2.trade` method for an explanation of why offer
/// uniquness is required.
/// The set of offers in `_values` must be sorted such that offer nonces'
/// are arranged in a strictly ascending order.
/// This allows the validation of offer uniqueness to be done in O(N) time,
/// with N being the number of offers.
/// @param _values Values from `trade`
function _validateUniqueOffers(uint256[] memory _values) private pure {
uint256 numOffers = _values[0] & mask8;
uint256 prevNonce;
for(uint256 i = 0; i < numOffers; i++) {
uint256 nonce = (_values[i * 2 + 1] & mask120) >> 56;
if (i == 0) {
// Set the value of the first nonce
prevNonce = nonce;
continue;
}
require(nonce > prevNonce, "Invalid offer nonces");
prevNonce = nonce;
}
}
/// @dev Validate that for every match:
/// 1. offerIndexes fall within the range of offers
/// 2. fillIndexes falls within the range of fills
/// 3. offer.offerAssetId == fill.wantAssetId
/// 4. offer.wantAssetId == fill.offerAssetId
/// 5. takeAmount > 0
/// 6. (offer.wantAmount * takeAmount) % offer.offerAmount == 0
/// @param _values Values from `trade`
/// @param _addresses Addresses from `trade`
function _validateMatches(
uint256[] memory _values,
address[] memory _addresses
)
private
pure
{
uint256 numOffers = _values[0] & mask8;
uint256 numFills = (_values[0] & mask16) >> 8;
uint256 i = 1 + numOffers * 2 + numFills * 2;
uint256 end = _values.length;
// loop matches
for (i; i < end; i++) {
uint256 offerIndex = _values[i] & mask8;
uint256 fillIndex = (_values[i] & mask16) >> 8;
require(offerIndex < numOffers, "Invalid match.offerIndex");
require(fillIndex >= numOffers && fillIndex < numOffers + numFills, "Invalid match.fillIndex");
require(
_addresses[_values[1 + offerIndex * 2] & mask8] !=
_addresses[_values[1 + fillIndex * 2] & mask8],
"offer.maker cannot be the same as fill.filler"
);
uint256 makerOfferAssetIndex = (_values[1 + offerIndex * 2] & mask16) >> 8;
uint256 makerWantAssetIndex = (_values[1 + offerIndex * 2] & mask24) >> 16;
uint256 fillerOfferAssetIndex = (_values[1 + fillIndex * 2] & mask16) >> 8;
uint256 fillerWantAssetIndex = (_values[1 + fillIndex * 2] & mask24) >> 16;
require(
_addresses[makerOfferAssetIndex * 2 + 1] ==
_addresses[fillerWantAssetIndex * 2 + 1],
"offer.offerAssetId does not match fill.wantAssetId"
);
require(
_addresses[makerWantAssetIndex * 2 + 1] ==
_addresses[fillerOfferAssetIndex * 2 + 1],
"offer.wantAssetId does not match fill.offerAssetId"
);
// require that bits(16..128) are all zero for every match
require((_values[i] & mask128) >> 16 == uint256(0), "Invalid match data");
uint256 takeAmount = _values[i] >> 128;
require(takeAmount > 0, "Invalid match.takeAmount");
uint256 offerDataB = _values[2 + offerIndex * 2];
// (offer.wantAmount * takeAmount) % offer.offerAmount == 0
require(
(offerDataB >> 128).mul(takeAmount).mod(offerDataB & mask128) == 0,
"Invalid amounts"
);
}
}
/// @dev Validate that for every match:
/// 1. offerIndexes fall within the range of offers
/// 2. _addresses[surplusAssetIndexes * 2] matches the operator address
/// 3. takeAmount > 0
/// 4. (offer.wantAmount * takeAmount) % offer.offerAmount == 0
/// @param _values Values from `trade`
/// @param _addresses Addresses from `trade`
/// @param _operator Address of the `BrokerV2.operator`
function _validateNetworkMatches(
uint256[] memory _values,
address[] memory _addresses,
address _operator
)
private
pure
{
uint256 numOffers = _values[0] & mask8;
// 1 + numOffers * 2
uint256 i = 1 + (_values[0] & mask8) * 2;
uint256 end = _values.length;
// loop matches
for (i; i < end; i++) {
uint256 offerIndex = _values[i] & mask8;
uint256 surplusAssetIndex = (_values[i] & mask24) >> 16;
require(offerIndex < numOffers, "Invalid match.offerIndex");
require(_addresses[surplusAssetIndex * 2] == _operator, "Invalid operator address");
uint256 takeAmount = _values[i] >> 128;
require(takeAmount > 0, "Invalid match.takeAmount");
uint256 offerDataB = _values[2 + offerIndex * 2];
// (offer.wantAmount * takeAmount) % offer.offerAmount == 0
require(
(offerDataB >> 128).mul(takeAmount).mod(offerDataB & mask128) == 0,
"Invalid amounts"
);
}
}
/// @dev Validate that all fills will be completely filled by the specified
/// matches. See the `BrokerV2.trade` method for an explanation of why
/// fills must be completely filled.
/// @param _values Values from `trade`
function _validateFillAmounts(uint256[] memory _values) private pure {
// "filled" is used to store the sum of `takeAmount`s and `giveAmount`s.
// While a fill's `offerAmount` and `wantAmount` are combined to share
// a single uint256 value, each sum of `takeAmount`s and `giveAmount`s
// for a fill is tracked with an individual uint256 value.
// This is to prevent the verification from being vulnerable to overflow
// issues.
uint256[] memory filled = new uint256[](_values.length);
uint256 i = 1;
// i += numOffers * 2
i += (_values[0] & mask8) * 2;
// i += numFills * 2
i += ((_values[0] & mask16) >> 8) * 2;
uint256 end = _values.length;
// loop matches
for (i; i < end; i++) {
uint256 offerIndex = _values[i] & mask8;
uint256 fillIndex = (_values[i] & mask16) >> 8;
uint256 takeAmount = _values[i] >> 128;
uint256 wantAmount = _values[2 + offerIndex * 2] >> 128;
uint256 offerAmount = _values[2 + offerIndex * 2] & mask128;
// giveAmount = takeAmount * wantAmount / offerAmount
uint256 giveAmount = takeAmount.mul(wantAmount).div(offerAmount);
// (1 + fillIndex * 2) would give the index of the first part
// of the data for the fill at fillIndex within `_values`,
// and (2 + fillIndex * 2) would give the index of the second part
filled[1 + fillIndex * 2] = filled[1 + fillIndex * 2].add(giveAmount);
filled[2 + fillIndex * 2] = filled[2 + fillIndex * 2].add(takeAmount);
}
// numOffers
i = _values[0] & mask8;
// i + numFills
end = i + ((_values[0] & mask16) >> 8);
// loop fills
for(i; i < end; i++) {
require(
// fill.offerAmount == (sum of given amounts for fill)
_values[i * 2 + 2] & mask128 == filled[i * 2 + 1] &&
// fill.wantAmount == (sum of taken amounts for fill)
_values[i * 2 + 2] >> 128 == filled[i * 2 + 2],
"Invalid fills"
);
}
}
/// @dev Validates that for every offer / fill
/// 1. user address matches address referenced by user.offerAssetIndex
/// 2. user address matches address referenced by user.wantAssetIndex
/// 3. user address matches address referenced by user.feeAssetIndex
/// 4. offerAssetId != wantAssetId
/// 5. offerAmount > 0 && wantAmount > 0
/// 6. Specified `operator` address matches the expected `operator` address,
/// 7. Specified `operator.feeAssetId` matches the offer's feeAssetId
/// @param _values Values from `trade`
/// @param _addresses Addresses from `trade`
function _validateTradeData(
uint256[] memory _values,
address[] memory _addresses,
address _operator
)
private
pure
{
// numOffers + numFills
uint256 end = (_values[0] & mask8) +
((_values[0] & mask16) >> 8);
for (uint256 i = 0; i < end; i++) {
uint256 dataA = _values[i * 2 + 1];
uint256 dataB = _values[i * 2 + 2];
uint256 feeAssetIndex = ((dataA & mask40) >> 32) * 2;
require(
// user address == user in user.offerAssetIndex pair
_addresses[(dataA & mask8) * 2] ==
_addresses[((dataA & mask16) >> 8) * 2],
"Invalid user in user.offerAssetIndex"
);
require(
// user address == user in user.wantAssetIndex pair
_addresses[(dataA & mask8) * 2] ==
_addresses[((dataA & mask24) >> 16) * 2],
"Invalid user in user.wantAssetIndex"
);
require(
// user address == user in user.feeAssetIndex pair
_addresses[(dataA & mask8) * 2] ==
_addresses[((dataA & mask32) >> 24) * 2],
"Invalid user in user.feeAssetIndex"
);
require(
// offerAssetId != wantAssetId
_addresses[((dataA & mask16) >> 8) * 2 + 1] !=
_addresses[((dataA & mask24) >> 16) * 2 + 1],
"Invalid trade assets"
);
require(
// offerAmount > 0 && wantAmount > 0
(dataB & mask128) > 0 && (dataB >> 128) > 0,
"Invalid trade amounts"
);
require(
_addresses[feeAssetIndex] == _operator,
"Invalid operator address"
);
require(
_addresses[feeAssetIndex + 1] ==
_addresses[((dataA & mask32) >> 24) * 2 + 1],
"Invalid operator fee asset ID"
);
}
}
/// @dev Validates signatures for a set of offers or fills
/// Note that the r value of the offer / fill in _hashes will be
/// overwritten by the hash of that offer / fill
/// @param _values Values from `trade`
/// @param _hashes Hashes from `trade`
/// @param _addresses Addresses from `trade`
/// @param _typehash The typehash used to construct the signed hash
/// @param _i The starting index to verify
/// @param _end The ending index to verify
/// @return An array of hash keys if _i started as 0, because only
/// the hash keys of offers are needed
function _validateTradeSignatures(
uint256[] memory _values,
bytes32[] memory _hashes,
address[] memory _addresses,
bytes32 _typehash,
uint256 _i,
uint256 _end
)
private
pure
{
for (_i; _i < _end; _i++) {
uint256 dataA = _values[_i * 2 + 1];
uint256 dataB = _values[_i * 2 + 2];
bytes32 hashKey = keccak256(abi.encode(
_typehash,
_addresses[(dataA & mask8) * 2], // user
_addresses[((dataA & mask16) >> 8) * 2 + 1], // offerAssetId
dataB & mask128, // offerAmount
_addresses[((dataA & mask24) >> 16) * 2 + 1], // wantAssetId
dataB >> 128, // wantAmount
_addresses[((dataA & mask32) >> 24) * 2 + 1], // feeAssetId
dataA >> 128, // feeAmount
(dataA & mask120) >> 56 // nonce
));
bool prefixedSignature = ((dataA & mask56) >> 48) != 0;
validateSignature(
hashKey,
_addresses[(dataA & mask8) * 2], // user
uint8((dataA & mask48) >> 40), // The `v` component of the user's signature
_hashes[_i * 2], // The `r` component of the user's signature
_hashes[_i * 2 + 1], // The `s` component of the user's signature
prefixedSignature
);
_hashes[_i * 2] = hashKey;
}
}
/// @dev Ensure that the address is a deployed contract
/// @param _contract The address to check
function _validateContractAddress(address _contract) private view {
assembly {
if iszero(extcodesize(_contract)) { revert(0, 0) }
}
}
/// @dev A thin wrapper around the native `call` function, to
/// validate that the contract `call` must be successful.
/// See https://solidity.readthedocs.io/en/v0.5.1/050-breaking-changes.html
/// for details on constructing the `_payload`
/// @param _contract Address of the contract to call
/// @param _payload The data to call the contract with
/// @return The data returned from the contract call
function _callContract(
address _contract,
bytes memory _payload
)
private
returns (bytes memory)
{
bool success;
bytes memory returnData;
(success, returnData) = _contract.call(_payload);
require(success, "Contract call failed");
return returnData;
}
/// @dev Fix for ERC-20 tokens that do not have proper return type
/// See: https://github.com/ethereum/solidity/issues/4116
/// https://medium.com/loopring-protocol/an-incompatibility-in-smart-contract-threatening-dapp-ecosystem-72b8ca5db4da
/// https://github.com/sec-bit/badERC20Fix/blob/master/badERC20Fix.sol
/// @param _data The data returned from a transfer call
function _validateContractCallResult(bytes memory _data) private pure {
require(
_data.length == 0 ||
(_data.length == 32 && _getUint256FromBytes(_data) != 0),
"Invalid contract call result"
);
}
/// @dev Converts data of type `bytes` into its corresponding `uint256` value
/// @param _data The data in bytes
/// @return The corresponding `uint256` value
function _getUint256FromBytes(
bytes memory _data
)
private
pure
returns (uint256)
{
uint256 parsed;
assembly { parsed := mload(add(_data, 32)) }
return parsed;
}
}
// File: contracts/BrokerV2.sol
pragma solidity 0.5.12;
interface IERC1820Registry {
function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external;
}
interface TokenList {
function validateToken(address assetId) external view;
}
interface SpenderList {
function validateSpender(address spender) external view;
function validateSpenderAuthorization(address user, address spender) external view;
}
/// @title The BrokerV2 contract for Switcheo Exchange
/// @author Switcheo Network
/// @notice This contract faciliates Ethereum and Ethereum token trades
/// between users.
/// Users can trade with each other by making and taking offers without
/// giving up custody of their tokens.
/// Users should first deposit tokens, then communicate off-chain
/// with the exchange coordinator, in order to place orders.
/// This allows trades to be confirmed immediately by the coordinator,
/// and settled on-chain through this contract at a later time.
///
/// @dev Bit compacting is used in the contract to reduce gas costs, when
/// it is used, params are documented as bits(n..m).
/// This means that the documented value is represented by bits starting
/// from and including `n`, up to and excluding `m`.
/// For example, bits(8..16), indicates that the value is represented by bits:
/// [8, 9, 10, 11, 12, 13, 14, 15].
///
/// Bit manipulation of the form (data & ~(~uint(0) << m)) >> n is frequently
/// used to recover the value at the specified bits.
/// For example, to recover bits(2..7) from a uint8 value, we can use
/// (data & ~(~uint8(0) << 7)) >> 2.
/// Given a `data` value of `1101,0111`, bits(2..7) should give "10101".
/// ~uint8(0): "1111,1111" (8 ones)
/// (~uint8(0) << 7): "1000,0000" (1 followed by 7 zeros)
/// ~(~uint8(0) << 7): "0111,1111" (0 followed by 7 ones)
/// (data & ~(~uint8(0) << 7)): "0101,0111" (bits after the 7th bit is zeroed)
/// (data & ~(~uint8(0) << 7)) >> 2: "0001,0101" (matching the expected "10101")
///
/// Additionally, bit manipulation of the form data >> n is used to recover
/// bits(n..e), where e is equal to the number of bits in the data.
/// For example, to recover bits(4..8) from a uint8 value, we can use data >> 4.
/// Given a data value of "1111,1111", bits(4..8) should give "1111".
/// data >> 4: "0000,1111" (matching the expected "1111")
///
/// There is frequent reference and usage of asset IDs, this is a unique
/// identifier used within the contract to represent individual assets.
/// For all tokens, the asset ID is identical to the contract address
/// of the token, this is so that additional mappings are not needed to
/// identify tokens during deposits and withdrawals.
/// The only exception is the Ethereum token, which does not have a contract
/// address, for this reason, the zero address is used to represent the
/// Ethereum token's ID.
contract BrokerV2 is Ownable, ReentrancyGuard {
using SafeMath for uint256;
struct WithdrawalAnnouncement {
uint256 amount;
uint256 withdrawableAt;
}
// Exchange states
enum State { Active, Inactive }
// Exchange admin states
enum AdminState { Normal, Escalated }
// The constants for EIP-712 are precompiled to reduce contract size,
// the original values are left here for reference and verification.
//
// bytes32 public constant WITHDRAW_TYPEHASH = keccak256(abi.encodePacked(
// "Withdraw(",
// "address withdrawer,",
// "address receivingAddress,",
// "address assetId,",
// "uint256 amount,",
// "address feeAssetId,",
// "uint256 feeAmount,",
// "uint256 nonce",
// ")"
// ));
bytes32 public constant WITHDRAW_TYPEHASH = 0xbe2f4292252fbb88b129dc7717b2f3f74a9afb5b13a2283cac5c056117b002eb;
// bytes32 public constant OFFER_TYPEHASH = keccak256(abi.encodePacked(
// "Offer(",
// "address maker,",
// "address offerAssetId,",
// "uint256 offerAmount,",
// "address wantAssetId,",
// "uint256 wantAmount,",
// "address feeAssetId,",
// "uint256 feeAmount,",
// "uint256 nonce",
// ")"
// ));
bytes32 public constant OFFER_TYPEHASH = 0xf845c83a8f7964bc8dd1a092d28b83573b35be97630a5b8a3b8ae2ae79cd9260;
// bytes32 public constant SWAP_TYPEHASH = keccak256(abi.encodePacked(
// "Swap(",
// "address maker,",
// "address taker,",
// "address assetId,",
// "uint256 amount,",
// "bytes32 hashedSecret,",
// "uint256 expiryTime,",
// "address feeAssetId,",
// "uint256 feeAmount,",
// "uint256 nonce",
// ")"
// ));
bytes32 public constant SWAP_TYPEHASH = 0x6ba9001457a287c210b728198a424a4222098d7fac48f8c5fb5ab10ef907d3ef;
// The Ether token address is set as the constant 0x00 for backwards
// compatibility
address private constant ETHER_ADDR = address(0);
// The maximum length of swap secret values
uint256 private constant MAX_SWAP_SECRET_LENGTH = 64;
// Reason codes are used by the off-chain coordinator to track balance changes
uint256 private constant REASON_DEPOSIT = 0x01;
uint256 private constant REASON_WITHDRAW = 0x09;
uint256 private constant REASON_WITHDRAW_FEE_GIVE = 0x14;
uint256 private constant REASON_WITHDRAW_FEE_RECEIVE = 0x15;
uint256 private constant REASON_CANCEL = 0x08;
uint256 private constant REASON_CANCEL_FEE_GIVE = 0x12;
uint256 private constant REASON_CANCEL_FEE_RECEIVE = 0x13;
uint256 private constant REASON_SWAP_GIVE = 0x30;
uint256 private constant REASON_SWAP_FEE_GIVE = 0x32;
uint256 private constant REASON_SWAP_RECEIVE = 0x35;
uint256 private constant REASON_SWAP_FEE_RECEIVE = 0x37;
uint256 private constant REASON_SWAP_CANCEL_RECEIVE = 0x38;
uint256 private constant REASON_SWAP_CANCEL_FEE_RECEIVE = 0x3B;
uint256 private constant REASON_SWAP_CANCEL_FEE_REFUND = 0x3D;
// 7 days * 24 hours * 60 mins * 60 seconds: 604800
uint256 private constant MAX_SLOW_WITHDRAW_DELAY = 604800;
uint256 private constant MAX_SLOW_CANCEL_DELAY = 604800;
uint256 private constant mask8 = ~(~uint256(0) << 8);
uint256 private constant mask16 = ~(~uint256(0) << 16);
uint256 private constant mask24 = ~(~uint256(0) << 24);
uint256 private constant mask32 = ~(~uint256(0) << 32);
uint256 private constant mask40 = ~(~uint256(0) << 40);
uint256 private constant mask120 = ~(~uint256(0) << 120);
uint256 private constant mask128 = ~(~uint256(0) << 128);
uint256 private constant mask136 = ~(~uint256(0) << 136);
uint256 private constant mask144 = ~(~uint256(0) << 144);
State public state;
AdminState public adminState;
// All fees will be transferred to the operator address
address public operator;
TokenList public tokenList;
SpenderList public spenderList;
// The delay in seconds to complete the respective escape hatch (`slowCancel` / `slowWithdraw`).
// This gives the off-chain service time to update the off-chain state
// before the state is separately updated by the user.
uint256 public slowCancelDelay;
uint256 public slowWithdrawDelay;
// A mapping of remaining offer amounts: offerHash => availableAmount
mapping(bytes32 => uint256) public offers;
// A mapping of used nonces: nonceIndex => nonceData
// The storing of nonces is used to ensure that transactions signed by
// the user can only be used once.
// For space and gas cost efficiency, one nonceData is used to store the
// state of 256 nonces.
// This reduces the average cost of storing a new nonce from 20,000 gas
// to 5000 + 20,000 / 256 = 5078.125 gas
// See _markNonce and _nonceTaken for more details.
mapping(uint256 => uint256) public usedNonces;
// A mapping of user balances: userAddress => assetId => balance
mapping(address => mapping(address => uint256)) public balances;
// A mapping of atomic swap states: swapHash => isSwapActive
mapping(bytes32 => bool) public atomicSwaps;
// A record of admin addresses: userAddress => isAdmin
mapping(address => bool) public adminAddresses;
// A record of market DApp addresses
address[] public marketDapps;
// A mapping of cancellation announcements for the cancel escape hatch: offerHash => cancellableAt
mapping(bytes32 => uint256) public cancellationAnnouncements;
// A mapping of withdrawal announcements: userAddress => assetId => { amount, withdrawableAt }
mapping(address => mapping(address => WithdrawalAnnouncement)) public withdrawalAnnouncements;
// Emitted on positive balance state transitions
event BalanceIncrease(
address indexed user,
address indexed assetId,
uint256 amount,
uint256 reason,
uint256 nonce
);
// Emitted on negative balance state transitions
event BalanceDecrease(
address indexed user,
address indexed assetId,
uint256 amount,
uint256 reason,
uint256 nonce
);
// Compacted versions of the `BalanceIncrease` and `BalanceDecrease` events.
// These are used in the `trade` method, they are compacted to save gas costs.
event Increment(uint256 data);
event Decrement(uint256 data);
event TokenFallback(
address indexed user,
address indexed assetId,
uint256 amount
);
event TokensReceived(
address indexed user,
address indexed assetId,
uint256 amount
);
event AnnounceCancel(
bytes32 indexed offerHash,
uint256 cancellableAt
);
event SlowCancel(
bytes32 indexed offerHash,
uint256 amount
);
event AnnounceWithdraw(
address indexed withdrawer,
address indexed assetId,
uint256 amount,
uint256 withdrawableAt
);
event SlowWithdraw(
address indexed withdrawer,
address indexed assetId,
uint256 amount
);
/// @notice Initializes the Broker contract
/// @dev The coordinator, operator and owner (through Ownable) is initialized
/// to be the address of the sender.
/// The Broker is put into an active state, with maximum exit delays set.
/// The Broker is also registered as an implementer of ERC777TokensRecipient
/// through the ERC1820 registry.
constructor(address _tokenListAddress, address _spenderListAddress) public {
adminAddresses[msg.sender] = true;
operator = msg.sender;
tokenList = TokenList(_tokenListAddress);
spenderList = SpenderList(_spenderListAddress);
slowWithdrawDelay = MAX_SLOW_WITHDRAW_DELAY;
slowCancelDelay = MAX_SLOW_CANCEL_DELAY;
state = State.Active;
IERC1820Registry erc1820 = IERC1820Registry(
0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24
);
erc1820.setInterfaceImplementer(
address(this),
keccak256("ERC777TokensRecipient"),
address(this)
);
}
modifier onlyAdmin() {
// Error code 1: onlyAdmin, address is not an admin address
require(adminAddresses[msg.sender], "1");
_;
}
modifier onlyActiveState() {
// Error code 2: onlyActiveState, state is not 'Active'
require(state == State.Active, "2");
_;
}
modifier onlyEscalatedAdminState() {
// Error code 3: onlyEscalatedAdminState, adminState is not 'Escalated'
require(adminState == AdminState.Escalated, "3");
_;
}
/// @notice Checks whether an address is appointed as an admin user
/// @param _user The address to check
/// @return Whether the address is appointed as an admin user
function isAdmin(address _user) external view returns(bool) {
return adminAddresses[_user];
}
/// @notice Sets tbe Broker's state.
/// @dev The two available states are `Active` and `Inactive`.
/// The `Active` state allows for regular exchange activity,
/// while the `Inactive` state prevents the invocation of deposit
/// and trading functions.
/// The `Inactive` state is intended as a means to cease contract operation
/// in the case of an upgrade or in an emergency.
/// @param _state The state to transition the contract into
function setState(State _state) external onlyOwner nonReentrant { state = _state; }
/// @notice Sets the Broker's admin state.
/// @dev The two available states are `Normal` and `Escalated`.
/// In the `Normal` admin state, the admin methods `adminCancel` and `adminWithdraw`
/// are not invocable.
/// The admin state must be set to `Escalated` by the contract owner for these
/// methods to become usable.
/// In an `Escalated` admin state, admin addresses would be able to cancel offers
/// and withdraw balances to the respective user's wallet on behalf of users.
/// The escalated state is intended to be used in the case of a contract upgrade or
/// in an emergency.
/// It is set separately from the `Inactive` state so that it is possible
/// to use admin functions without affecting regular operations.
/// @param _state The admin state to transition the contract into
function setAdminState(AdminState _state) external onlyOwner nonReentrant { adminState = _state; }
/// @notice Sets the operator address.
/// @dev All fees will be transferred to the operator address.
/// @param _operator The address to set as the operator
function setOperator(address _operator) external onlyOwner nonReentrant {
_validateAddress(operator);
operator = _operator;
}
/// @notice Sets the minimum delay between an `announceCancel` call and
/// when the cancellation can actually be executed through `slowCancel`.
/// @dev This gives the off-chain service time to update the off-chain state
/// before the state is separately updated by the user.
/// This differs from the regular `cancel` operation, which does not involve a delay.
/// @param _delay The delay in seconds
function setSlowCancelDelay(uint256 _delay) external onlyOwner nonReentrant {
// Error code 4: setSlowCancelDelay, slow cancel delay exceeds max allowable delay
require(_delay <= MAX_SLOW_CANCEL_DELAY, "4");
slowCancelDelay = _delay;
}
/// @notice Sets the delay between an `announceWithdraw` call and
/// when the withdrawal can actually be executed through `slowWithdraw`.
/// @dev This gives the off-chain service time to update the off-chain state
/// before the state is separately updated by the user.
/// This differs from the regular `withdraw` operation, which does not involve a delay.
/// @param _delay The delay in seconds
function setSlowWithdrawDelay(uint256 _delay) external onlyOwner nonReentrant {
// Error code 5: setSlowWithdrawDelay, slow withdraw delay exceeds max allowable delay
require(_delay <= MAX_SLOW_WITHDRAW_DELAY, "5");
slowWithdrawDelay = _delay;
}
/// @notice Gives admin permissons to the specified address.
/// @dev Admin addresses are intended to coordinate the regular operation
/// of the Broker contract, and to perform special functions such as
/// `adminCancel` and `adminWithdraw`.
/// @param _admin The address to give admin permissions to
function addAdmin(address _admin) external onlyOwner nonReentrant {
_validateAddress(_admin);
// Error code 6: addAdmin, address is already an admin address
require(!adminAddresses[_admin], "6");
adminAddresses[_admin] = true;
}
/// @notice Removes admin permissons for the specified address.
/// @param _admin The admin address to remove admin permissions from
function removeAdmin(address _admin) external onlyOwner nonReentrant {
_validateAddress(_admin);
// Error code 7: removeAdmin, address is not an admin address
require(adminAddresses[_admin], "7");
delete adminAddresses[_admin];
}
/// @notice Adds a market DApp to be used in `networkTrade`
/// @param _dapp Address of the market DApp
function addMarketDapp(address _dapp) external onlyOwner nonReentrant {
_validateAddress(_dapp);
marketDapps.push(_dapp);
}
/// @notice Updates a market DApp to be used in `networkTrade`
/// @param _index Index of the market DApp to update
/// @param _dapp The new address of the market DApp
function updateMarketDapp(uint256 _index, address _dapp) external onlyOwner nonReentrant {
_validateAddress(_dapp);
// Error code 8: updateMarketDapp, _index does not refer to an existing non-zero address
require(marketDapps[_index] != address(0), "8");
marketDapps[_index] = _dapp;
}
/// @notice Removes a market DApp
/// @param _index Index of the market DApp to remove
function removeMarketDapp(uint256 _index) external onlyOwner nonReentrant {
// Error code 9: removeMarketDapp, _index does not refer to a DApp address
require(marketDapps[_index] != address(0), "9");
delete marketDapps[_index];
}
/// @notice Performs a balance transfer from one address to another
/// @dev This method is intended to be invoked by spender contracts.
/// To invoke this method, a spender contract must have been
/// previously whitelisted and also authorized by the address from which
/// funds will be deducted.
/// Balance events are not emitted by this method, they should be separately
/// emitted by the spender contract.
/// @param _from The address to deduct from
/// @param _to The address to credit
/// @param _assetId The asset to transfer
/// @param _amount The amount to transfer
function spendFrom(
address _from,
address _to,
address _assetId,
uint256 _amount
)
external
nonReentrant
{
spenderList.validateSpenderAuthorization(_from, msg.sender);
_validateAddress(_to);
balances[_from][_assetId] = balances[_from][_assetId].sub(_amount);
balances[_to][_assetId] = balances[_to][_assetId].add(_amount);
}
/// @notice Allows a whitelisted contract to mark nonces
/// @dev If the whitelisted contract is malicious or vulnerable then there is
/// a possibility of a DoS attack. However, since this attack requires cooperation
/// of the contract owner, the risk is similar to the contract owner withholding
/// transactions, so there is no violation of the contract's trust model.
/// In the case that nonces are misused, users will still be able to cancel their offers
/// and withdraw all their funds using the escape hatch methods.
/// @param _nonce The nonce to mark
function markNonce(uint256 _nonce) external nonReentrant {
spenderList.validateSpender(msg.sender);
_markNonce(_nonce);
}
/// @notice Returns whether a nonce has been taken
/// @param _nonce The nonce to check
/// @return Whether the nonce has been taken
function nonceTaken(uint256 _nonce) external view returns (bool) {
return _nonceTaken(_nonce);
}
/// @notice Deposits ETH into the sender's contract balance
/// @dev This operation is only usable in an `Active` state
/// to prevent this contract from receiving ETH in the case that its
/// operation has been terminated.
function deposit() external payable onlyActiveState nonReentrant {
// Error code 10: deposit, msg.value is 0
require(msg.value > 0, "10");
_increaseBalance(msg.sender, ETHER_ADDR, msg.value, REASON_DEPOSIT, 0);
}
/// @dev This function is needed as market DApps generally send ETH
/// using the `<address>.transfer` method.
/// It is left empty to avoid issues with the function call running out
/// of gas, as some callers set a small limit on how much gas can be
/// used by the ETH receiver.
function() payable external {}
/// @notice Deposits ERC20 tokens under the `_user`'s balance
/// @dev Transfers token into the Broker contract using the
/// token's `transferFrom` method.
/// The user must have previously authorized the token transfer
/// through the token's `approve` method.
/// This method has separate `_amount` and `_expectedAmount` values
/// to support unconventional token transfers, e.g. tokens which have a
/// proportion burnt on transfer.
/// @param _user The address of the user depositing the tokens
/// @param _assetId The address of the token contract
/// @param _amount The value to invoke the token's `transferFrom` with
/// @param _expectedAmount The final amount expected to be received by this contract
/// @param _nonce A nonce for balance tracking, emitted in the BalanceIncrease event
function depositToken(
address _user,
address _assetId,
uint256 _amount,
uint256 _expectedAmount,
uint256 _nonce
)
external
onlyAdmin
onlyActiveState
nonReentrant
{
_increaseBalance(
_user,
_assetId,
_expectedAmount,
REASON_DEPOSIT,
_nonce
);
Utils.transferTokensIn(
_user,
_assetId,
_amount,
_expectedAmount
);
}
/// @notice Deposits ERC223 tokens under the `_user`'s balance
/// @dev ERC223 tokens should invoke this method when tokens are
/// sent to the Broker contract.
/// The invocation will fail unless the token has been previously
/// whitelisted through the `whitelistToken` method.
/// @param _user The address of the user sending the tokens
/// @param _amount The amount of tokens transferred to the Broker
function tokenFallback(
address _user,
uint _amount,
bytes calldata /* _data */
)
external
onlyActiveState
nonReentrant
{
address assetId = msg.sender;
tokenList.validateToken(assetId);
_increaseBalance(_user, assetId, _amount, REASON_DEPOSIT, 0);
emit TokenFallback(_user, assetId, _amount);
}
/// @notice Deposits ERC777 tokens under the `_user`'s balance
/// @dev ERC777 tokens should invoke this method when tokens are
/// sent to the Broker contract.
/// The invocation will fail unless the token has been previously
/// whitelisted through the `whitelistToken` method.
/// @param _user The address of the user sending the tokens
/// @param _to The address receiving the tokens
/// @param _amount The amount of tokens transferred to the Broker
function tokensReceived(
address /* _operator */,
address _user,
address _to,
uint _amount,
bytes calldata /* _userData */,
bytes calldata /* _operatorData */
)
external
onlyActiveState
nonReentrant
{
if (_to != address(this)) { return; }
address assetId = msg.sender;
tokenList.validateToken(assetId);
_increaseBalance(_user, assetId, _amount, REASON_DEPOSIT, 0);
emit TokensReceived(_user, assetId, _amount);
}
/// @notice Executes an array of offers and fills
/// @dev This method accepts an array of "offers" and "fills" together with
/// an array of "matches" to specify the matching between the "offers" and "fills".
/// The data is bit compacted for ease of index referencing and to reduce gas costs,
/// i.e. data representing different types of information is stored within one 256 bit value.
///
/// For efficient balance updates, the `_addresses` array is meant to contain a
/// unique set of user asset pairs in the form of:
/// [
/// user_1_address,
/// asset_1_address,
/// user_1_address,
/// asset_2_address,
/// user_2_address,
/// asset_1_address,
/// ...
/// ]
/// This allows combining multiple balance updates for a user asset pair
/// into a single update by first calculating the total balance update for
/// a pair at a specified index, then looping through the sums to perform
/// the balance update.
///
/// The added benefit is further gas cost reduction because repeated
/// user asset pairs do not need to be duplicated for the calldata.
///
/// The operator address is enforced to be the contract's current operator
/// address, and the operator fee asset ID is enforced to be identical to
/// the maker's / filler's feeAssetId.
///
/// A tradeoff of compacting the bits is that there is a lower maximum value
/// for offer and fill data, however the limits remain generally practical.
///
/// For `offerAmount`, `wantAmount`, `feeAmount` values, the maximum value
/// is 2^128. For a token with 18 decimals, this allows support for tokens
/// with a maximum supply of 1000 million billion billion (33 zeros).
/// In the case where the maximum value needs to be exceeded, a single
/// offer / fill can be split into multiple offers / fills by the off-chain
/// service.
///
/// For nonces the maximum value is 2^64, or more than a billion billion (19 zeros).
///
/// Offers and fills both encompass information about how much (offerAmount)
/// of a specified token (offerAssetId) the user wants to offer and
/// how much (wantAmount) of another token (wantAssetId) they want
/// in return.
///
/// Each match specifies how much of the match's `offer.offerAmount` should
/// be transferred to the filler, in return, the offer's maker receives:
/// `offer.wantAmount * match.takeAmount / offer.offerAmount` of the
/// `offer.wantAssetId` from the filler.
///
/// A few restirctions are enforced to ensure fairness and security of trades:
/// 1. To prevent unfairness due to rounding issues, it is required that:
/// `offer.wantAmount * match.takeAmount % offer.offerAmount == 0`.
///
/// 2. Fills can be filled by offers which do not individually match
/// the `fill.offerAmount` and `fill.wantAmount` ratio. As such, it is
/// required that:
/// fill.offerAmount == total amount deducted from filler for the fill's
/// associated matches (excluding fees)
/// fill.wantAmount == total amount credited to filler for the fill's
/// associated matches (excluding fees)
///
/// 3. The offer array must not consist of repeated offers. For efficient
/// balance updates, a loop through each offer in the offer array is used
/// to deduct the offer.offerAmount from the respective maker
/// if the offer has not been recorded by a previos `trade` call.
/// If an offer is repeated in the offers array, then there would be
/// duplicate deductions from the maker.
/// To enforce uniqueness, it is required that offers for a trade transaction
/// are sorted such that their nonces are in a strictly ascending order.
///
/// 4. The fill array must not consist of repeated fills, for the same
/// reason why there cannot be repeated offers. Additionally, to prevent
/// replay attacks, all fill nonces are required to be unused.
///
/// @param _values[0] Number of offers, fills, matches
/// bits(0..8): number of offers (numOffers)
/// bits(8..16): number of fills (numFills)
/// bits(16..24): number of matches (numMatches)
/// bits(24..256): must be zero
///
/// @param _values[1 + i * 2] First part of offer data for the i'th offer
/// bits(0..8): Index of the maker's address in _addresses
/// bits(8..16): Index of the maker offerAssetId pair in _addresses
/// bits(16..24): Index of the maker wantAssetId pair in _addresses
/// bits(24..32): Index of the maker feeAssetId pair in _addresses
/// bits(32..40): Index of the operator feeAssetId pair in _addresses
/// bits(40..48): The `v` component of the maker's signature for this offer
/// bits(48..56): Indicates whether the Ethereum signed message
/// prefix should be prepended during signature verification
/// bits(56..120): The offer nonce to prevent replay attacks
/// bits(120..128): Space to indicate whether the offer nonce has been marked before
/// bits(128..256): The number of tokens to be paid to the operator as fees for this offer
///
/// @param _values[2 + i * 2] Second part of offer data for the i'th offer
/// bits(0..128): offer.offerAmount, i.e. the number of tokens to offer
/// bits(128..256): offer.wantAmount, i.e. the number of tokens to ask for in return
///
/// @param _values[1 + numOffers * 2 + i * 2] First part of fill data for the i'th fill
/// bits(0..8): Index of the filler's address in _addresses
/// bits(8..16): Index of the filler offerAssetId pair in _addresses
/// bits(16..24): Index of the filler wantAssetId pair in _addresses
/// bits(24..32): Index of the filler feeAssetId pair in _addresses
/// bits(32..40): Index of the operator feeAssetId pair in _addresses
/// bits(40..48): The `v` component of the filler's signature for this fill
/// bits(48..56): Indicates whether the Ethereum signed message
/// prefix should be prepended during signature verification
/// bits(56..120): The fill nonce to prevent replay attacks
/// bits(120..128): Left empty to match the offer values format
/// bits(128..256): The number of tokens to be paid to the operator as fees for this fill
///
/// @param _values[2 + numOffers * 2 + i * 2] Second part of fill data for the i'th fill
/// bits(0..128): fill.offerAmount, i.e. the number of tokens to offer
/// bits(128..256): fill.wantAmount, i.e. the number of tokens to ask for in return
///
/// @param _values[1 + numOffers * 2 + numFills * 2 + i] Data for the i'th match
/// bits(0..8): Index of the offerIndex for this match
/// bits(8..16): Index of the fillIndex for this match
/// bits(128..256): The number of tokens to take from the matched offer's offerAmount
///
/// @param _hashes[i * 2] The `r` component of the maker's / filler's signature
/// for the i'th offer / fill
///
/// @param _hashes[i * 2 + 1] The `s` component of the maker's / filler's signature
/// for the i'th offer / fill
///
/// @param _addresses An array of user asset pairs in the form of:
/// [
/// user_1_address,
/// asset_1_address,
/// user_1_address,
/// asset_2_address,
/// user_2_address,
/// asset_1_address,
/// ...
/// ]
function trade(
uint256[] memory _values,
bytes32[] memory _hashes,
address[] memory _addresses
)
public
onlyAdmin
onlyActiveState
nonReentrant
{
// Cache the operator address to reduce gas costs from storage reads
address operatorAddress = operator;
// An array variable to store balance increments / decrements
uint256[] memory statements;
// Cache whether offer nonces are taken in the offer's nonce space
_cacheOfferNonceStates(_values);
// `validateTrades` needs to calculate the hash keys of offers and fills
// to verify the signature of the offer / fill.
// The calculated hash keys are returned to reduce repeated computation.
_hashes = Utils.validateTrades(
_values,
_hashes,
_addresses,
operatorAddress
);
statements = Utils.calculateTradeIncrements(_values, _addresses.length / 2);
_incrementBalances(statements, _addresses, 1);
statements = Utils.calculateTradeDecrements(_values, _addresses.length / 2);
_decrementBalances(statements, _addresses);
// Reduce available offer amounts of offers and store the remaining
// offer amount in the `offers` mapping.
// Offer nonces will also be marked as taken.
_storeOfferData(_values, _hashes);
// Mark all fill nonces as taken in the `usedNonces` mapping.
_storeFillNonces(_values);
}
/// @notice Executes an array of offers against external orders.
/// @dev This method accepts an array of "offers" together with
/// an array of "matches" to specify the matching between the "offers" and
/// external orders.
/// The data is bit compacted and formatted in the same way as the `trade` function.
///
/// @param _values[0] Number of offers, fills, matches
/// bits(0..8): number of offers (numOffers)
/// bits(8..16): number of fills, must be zero
/// bits(16..24): number of matches (numMatches)
/// bits(24..256): must be zero
///
/// @param _values[1 + i * 2] First part of offer data for the i'th offer
/// bits(0..8): Index of the maker's address in _addresses
/// bits(8..16): Index of the maker offerAssetId pair in _addresses
/// bits(16..24): Index of the maker wantAssetId pair in _addresses
/// bits(24..32): Index of the maker feeAssetId pair in _addresses
/// bits(32..40): Index of the operator feeAssetId pair in _addresses
/// bits(40..48): The `v` component of the maker's signature for this offer
/// bits(48..56): Indicates whether the Ethereum signed message
/// prefix should be prepended during signature verification
/// bits(56..120): The offer nonce to prevent replay attacks
/// bits(120..128): Space to indicate whether the offer nonce has been marked before
/// bits(128..256): The number of tokens to be paid to the operator as fees for this offer
///
/// @param _values[2 + i * 2] Second part of offer data for the i'th offer
/// bits(0..128): offer.offerAmount, i.e. the number of tokens to offer
/// bits(128..256): offer.wantAmount, i.e. the number of tokens to ask for in return
///
/// @param _values[1 + numOffers * 2 + i] Data for the i'th match
/// bits(0..8): Index of the offerIndex for this match
/// bits(8..16): Index of the marketDapp for this match
/// bits(16..24): Index of the surplus receiver and surplus asset ID for this
/// match, for any excess tokens resulting from the trade
/// bits(24..128): Additional DApp specific data
/// bits(128..256): The number of tokens to take from the matched offer's offerAmount
///
/// @param _hashes[i * 2] The `r` component of the maker's / filler's signature
/// for the i'th offer / fill
///
/// @param _hashes[i * 2 + 1] The `s` component of the maker's / filler's signature
/// for the i'th offer / fill
///
/// @param _addresses An array of user asset pairs in the form of:
/// [
/// user_1_address,
/// asset_1_address,
/// user_1_address,
/// asset_2_address,
/// user_2_address,
/// asset_1_address,
/// ...
/// ]
function networkTrade(
uint256[] memory _values,
bytes32[] memory _hashes,
address[] memory _addresses
)
public
onlyAdmin
onlyActiveState
nonReentrant
{
// Cache the operator address to reduce gas costs from storage reads
address operatorAddress = operator;
// An array variable to store balance increments / decrements
uint256[] memory statements;
// Cache whether offer nonces are taken in the offer's nonce space
_cacheOfferNonceStates(_values);
// `validateNetworkTrades` needs to calculate the hash keys of offers
// to verify the signature of the offer.
// The calculated hash keys for each offer is return to reduce repeated
// computation.
_hashes = Utils.validateNetworkTrades(
_values,
_hashes,
_addresses,
operatorAddress
);
statements = Utils.calculateNetworkTradeIncrements(_values, _addresses.length / 2);
_incrementBalances(statements, _addresses, 1);
statements = Utils.calculateNetworkTradeDecrements(_values, _addresses.length / 2);
_decrementBalances(statements, _addresses);
// Reduce available offer amounts of offers and store the remaining
// offer amount in the `offers` mapping.
// Offer nonces will also be marked as taken.
_storeOfferData(_values, _hashes);
// There may be excess tokens resulting from a trade
// Any excess tokens are returned and recorded in `increments`
statements = Utils.performNetworkTrades(
_values,
_addresses,
marketDapps
);
_incrementBalances(statements, _addresses, 0);
}
/// @notice Cancels a perviously made offer and refunds the remaining offer
/// amount to the offer maker.
/// To reduce gas costs, the original parameters of the offer are not stored
/// in the contract's storage, only the hash of the parameters is stored for
/// verification, so the original parameters need to be re-specified here.
///
/// The `_expectedavailableamount` is required to help prevent accidental
/// cancellation of an offer ahead of time, for example, if there is
/// a pending fill in the off-chain state.
///
/// @param _values[0] The offerAmount and wantAmount of the offer
/// bits(0..128): offer.offerAmount
/// bits(128..256): offer.wantAmount
///
/// @param _values[1] The fee amounts
/// bits(0..128): offer.feeAmount
/// bits(128..256): cancelFeeAmount
///
/// @param _values[2] Additional offer and cancellation data
/// bits(0..128): expectedAvailableAmount
/// bits(128..136): prefixedSignature
/// bits(136..144): The `v` component of the maker's signature for the cancellation
/// bits(144..256): offer.nonce
///
/// @param _hashes[0] The `r` component of the maker's signature for the cancellation
/// @param _hashes[1] The `s` component of the maker's signature for the cancellation
///
/// @param _addresses[0] offer.maker
/// @param _addresses[1] offer.offerAssetId
/// @param _addresses[2] offer.wantAssetId
/// @param _addresses[3] offer.feeAssetId
/// @param _addresses[4] offer.cancelFeeAssetId
function cancel(
uint256[] calldata _values,
bytes32[] calldata _hashes,
address[] calldata _addresses
)
external
onlyAdmin
nonReentrant
{
Utils.validateCancel(_values, _hashes, _addresses);
bytes32 offerHash = Utils.hashOffer(_values, _addresses);
_cancel(
_addresses[0], // maker
offerHash,
_values[2] & mask128, // expectedAvailableAmount
_addresses[1], // offerAssetId
_values[2] >> 144, // offerNonce
_addresses[4], // cancelFeeAssetId
_values[1] >> 128 // cancelFeeAmount
);
}
/// @notice Cancels an offer without requiring the maker's signature
/// @dev This method is intended to be used in the case of a contract
/// upgrade or in an emergency. It can only be invoked by an admin and only
/// after the admin state has been set to `Escalated` by the contract owner.
///
/// To reduce gas costs, the original parameters of the offer are not stored
/// in the contract's storage, only the hash of the parameters is stored for
/// verification, so the original parameters need to be re-specified here.
///
/// The `_expectedavailableamount` is required to help prevent accidental
/// cancellation of an offer ahead of time, for example, if there is
/// a pending fill in the off-chain state.
/// @param _maker The address of the offer's maker
/// @param _offerAssetId The contract address of the offerred asset
/// @param _offerAmount The number of tokens offerred
/// @param _wantAssetId The contract address of the asset asked in return
/// @param _wantAmount The number of tokens asked for in return
/// @param _feeAssetId The contract address of the fee asset
/// @param _feeAmount The number of tokens to pay as fees to the operator
/// @param _offerNonce The nonce of the original offer
/// @param _expectedAvailableAmount The offer amount remaining
function adminCancel(
address _maker,
address _offerAssetId,
uint256 _offerAmount,
address _wantAssetId,
uint256 _wantAmount,
address _feeAssetId,
uint256 _feeAmount,
uint256 _offerNonce,
uint256 _expectedAvailableAmount
)
external
onlyAdmin
onlyEscalatedAdminState
nonReentrant
{
bytes32 offerHash = keccak256(abi.encode(
OFFER_TYPEHASH,
_maker,
_offerAssetId,
_offerAmount,
_wantAssetId,
_wantAmount,
_feeAssetId,
_feeAmount,
_offerNonce
));
_cancel(
_maker,
offerHash,
_expectedAvailableAmount,
_offerAssetId,
_offerNonce,
address(0),
0
);
}
/// @notice Announces a user's intention to cancel their offer
/// @dev This method allows a user to cancel their offer without requiring
/// admin permissions.
/// An announcement followed by a delay is needed so that the off-chain
/// service has time to update the off-chain state.
///
/// To reduce gas costs, the original parameters of the offer are not stored
/// in the contract's storage, only the hash of the parameters is stored for
/// verification, so the original parameters need to be re-specified here.
///
/// @param _maker The address of the offer's maker
/// @param _offerAssetId The contract address of the offerred asset
/// @param _offerAmount The number of tokens offerred
/// @param _wantAssetId The contract address of the asset asked in return
/// @param _wantAmount The number of tokens asked for in return
/// @param _feeAssetId The contract address of the fee asset
/// @param _feeAmount The number of tokens to pay as fees to the operator
/// @param _offerNonce The nonce of the original offer
function announceCancel(
address _maker,
address _offerAssetId,
uint256 _offerAmount,
address _wantAssetId,
uint256 _wantAmount,
address _feeAssetId,
uint256 _feeAmount,
uint256 _offerNonce
)
external
nonReentrant
{
// Error code 11: announceCancel, invalid msg.sender
require(_maker == msg.sender, "11");
bytes32 offerHash = keccak256(abi.encode(
OFFER_TYPEHASH,
_maker,
_offerAssetId,
_offerAmount,
_wantAssetId,
_wantAmount,
_feeAssetId,
_feeAmount,
_offerNonce
));
// Error code 12: announceCancel, nothing left to cancel
require(offers[offerHash] > 0, "12");
uint256 cancellableAt = now.add(slowCancelDelay);
cancellationAnnouncements[offerHash] = cancellableAt;
emit AnnounceCancel(offerHash, cancellableAt);
}
/// @notice Executes an offer cancellation previously announced in `announceCancel`
/// @dev This method allows a user to cancel their offer without requiring
/// admin permissions.
/// An announcement followed by a delay is needed so that the off-chain
/// service has time to update the off-chain state.
///
/// To reduce gas costs, the original parameters of the offer are not stored
/// in the contract's storage, only the hash of the parameters is stored for
/// verification, so the original parameters need to be re-specified here.
///
/// @param _maker The address of the offer's maker
/// @param _offerAssetId The contract address of the offerred asset
/// @param _offerAmount The number of tokens offerred
/// @param _wantAssetId The contract address of the asset asked in return
/// @param _wantAmount The number of tokens asked for in return
/// @param _feeAssetId The contract address of the fee asset
/// @param _feeAmount The number of tokens to pay as fees to the operator
/// @param _offerNonce The nonce of the original offer
function slowCancel(
address _maker,
address _offerAssetId,
uint256 _offerAmount,
address _wantAssetId,
uint256 _wantAmount,
address _feeAssetId,
uint256 _feeAmount,
uint256 _offerNonce
)
external
nonReentrant
{
bytes32 offerHash = keccak256(abi.encode(
OFFER_TYPEHASH,
_maker,
_offerAssetId,
_offerAmount,
_wantAssetId,
_wantAmount,
_feeAssetId,
_feeAmount,
_offerNonce
));
uint256 cancellableAt = cancellationAnnouncements[offerHash];
// Error code 13: slowCancel, cancellation was not announced
require(cancellableAt != 0, "13");
// Error code 14: slowCancel, cancellation delay not yet reached
require(now >= cancellableAt, "14");
uint256 availableAmount = offers[offerHash];
// Error code 15: slowCancel, nothing left to cancel
require(availableAmount > 0, "15");
delete cancellationAnnouncements[offerHash];
_cancel(
_maker,
offerHash,
availableAmount,
_offerAssetId,
_offerNonce,
address(0),
0
);
emit SlowCancel(offerHash, availableAmount);
}
/// @notice Withdraws tokens from the Broker contract to a user's wallet balance
/// @dev The user's internal balance is decreased, and the tokens are transferred
/// to the `_receivingAddress` signed by the user.
/// @param _withdrawer The user address whose balance will be reduced
/// @param _receivingAddress The address to tranfer the tokens to
/// @param _assetId The contract address of the token to withdraw
/// @param _amount The number of tokens to withdraw
/// @param _feeAssetId The contract address of the fee asset
/// @param _feeAmount The number of tokens to pay as fees to the operator
/// @param _nonce An unused nonce to prevent replay attacks
/// @param _v The `v` component of the `_user`'s signature
/// @param _r The `r` component of the `_user`'s signature
/// @param _s The `s` component of the `_user`'s signature
/// @param _prefixedSignature Indicates whether the Ethereum signed message
/// prefix should be prepended during signature verification
function withdraw(
address _withdrawer,
address payable _receivingAddress,
address _assetId,
uint256 _amount,
address _feeAssetId,
uint256 _feeAmount,
uint256 _nonce,
uint8 _v,
bytes32 _r,
bytes32 _s,
bool _prefixedSignature
)
external
onlyAdmin
nonReentrant
{
_markNonce(_nonce);
_validateSignature(
keccak256(abi.encode(
WITHDRAW_TYPEHASH,
_withdrawer,
_receivingAddress,
_assetId,
_amount,
_feeAssetId,
_feeAmount,
_nonce
)),
_withdrawer,
_v,
_r,
_s,
_prefixedSignature
);
_withdraw(
_withdrawer,
_receivingAddress,
_assetId,
_amount,
_feeAssetId,
_feeAmount,
_nonce
);
}
/// @notice Withdraws tokens without requiring the withdrawer's signature
/// @dev This method is intended to be used in the case of a contract
/// upgrade or in an emergency. It can only be invoked by an admin and only
/// after the admin state has been set to `Escalated` by the contract owner.
/// Unlike `withdraw`, tokens can only be withdrawn to the `_withdrawer`'s
/// address.
/// @param _withdrawer The user address whose balance will be reduced
/// @param _assetId The contract address of the token to withdraw
/// @param _amount The number of tokens to withdraw
/// @param _nonce An unused nonce for balance tracking
function adminWithdraw(
address payable _withdrawer,
address _assetId,
uint256 _amount,
uint256 _nonce
)
external
onlyAdmin
onlyEscalatedAdminState
nonReentrant
{
_markNonce(_nonce);
_withdraw(
_withdrawer,
_withdrawer,
_assetId,
_amount,
address(0),
0,
_nonce
);
}
/// @notice Announces a user's intention to withdraw their funds
/// @dev This method allows a user to withdraw their funds without requiring
/// admin permissions.
/// An announcement followed by a delay before execution is needed so that
/// the off-chain service has time to update the off-chain state.
/// @param _assetId The contract address of the token to withdraw
/// @param _amount The number of tokens to withdraw
function announceWithdraw(
address _assetId,
uint256 _amount
)
external
nonReentrant
{
// Error code 16: announceWithdraw, invalid withdrawal amount
require(_amount > 0 && _amount <= balances[msg.sender][_assetId], "16");
WithdrawalAnnouncement storage announcement = withdrawalAnnouncements[msg.sender][_assetId];
announcement.withdrawableAt = now.add(slowWithdrawDelay);
announcement.amount = _amount;
emit AnnounceWithdraw(msg.sender, _assetId, _amount, announcement.withdrawableAt);
}
/// @notice Executes a withdrawal previously announced in `announceWithdraw`
/// @dev This method allows a user to withdraw their funds without requiring
/// admin permissions.
/// An announcement followed by a delay before execution is needed so that
/// the off-chain service has time to update the off-chain state.
/// @param _withdrawer The user address whose balance will be reduced
/// @param _assetId The contract address of the token to withdraw
function slowWithdraw(
address payable _withdrawer,
address _assetId,
uint256 _amount
)
external
nonReentrant
{
WithdrawalAnnouncement memory announcement = withdrawalAnnouncements[_withdrawer][_assetId];
// Error code 17: slowWithdraw, withdrawal was not announced
require(announcement.withdrawableAt != 0, "17");
// Error code 18: slowWithdraw, withdrawal delay not yet reached
require(now >= announcement.withdrawableAt, "18");
// Error code 19: slowWithdraw, withdrawal amount does not match announced amount
require(announcement.amount == _amount, "19");
delete withdrawalAnnouncements[_withdrawer][_assetId];
_withdraw(
_withdrawer,
_withdrawer,
_assetId,
_amount,
address(0),
0,
0
);
emit SlowWithdraw(_withdrawer, _assetId, _amount);
}
/// @notice Locks a user's balances for the first part of an atomic swap
/// @param _addresses[0] maker: the address of the user to deduct the swap tokens from
/// @param _addresses[1] taker: the address of the swap taker who will receive the swap tokens
/// if the swap is completed through `executeSwap`
/// @param _addresses[2] assetId: the contract address of the token to swap
/// @param _addresses[3] feeAssetId: the contract address of the token to use as fees
/// @param _values[0] amount: the number of tokens to lock and to transfer if the swap
/// is completed through `executeSwap`
/// @param _values[1] expiryTime: the time in epoch seconds after which the swap will become cancellable
/// @param _values[2] feeAmount: the number of tokens to be paid to the operator as fees
/// @param _values[3] nonce: an unused nonce to prevent replay attacks
/// @param _hashes[0] hashedSecret: the hash of the secret decided by the maker
/// @param _hashes[1] The `r` component of the user's signature
/// @param _hashes[2] The `s` component of the user's signature
/// @param _v The `v` component of the user's signature
/// @param _prefixedSignature Indicates whether the Ethereum signed message
/// prefix should be prepended during signature verification
function createSwap(
address[4] calldata _addresses,
uint256[4] calldata _values,
bytes32[3] calldata _hashes,
uint8 _v,
bool _prefixedSignature
)
external
onlyAdmin
onlyActiveState
nonReentrant
{
// Error code 20: createSwap, invalid swap amount
require(_values[0] > 0, "20");
// Error code 21: createSwap, expiry time has already passed
require(_values[1] > now, "21");
_validateAddress(_addresses[1]);
// Error code 39: createSwap, swap maker cannot be the swap taker
require(_addresses[0] != _addresses[1], "39");
bytes32 swapHash = _hashSwap(_addresses, _values, _hashes[0]);
// Error code 22: createSwap, the swap is already active
require(!atomicSwaps[swapHash], "22");
_markNonce(_values[3]);
_validateSignature(
swapHash,
_addresses[0], // swap.maker
_v,
_hashes[1], // r
_hashes[2], // s
_prefixedSignature
);
if (_addresses[3] == _addresses[2]) { // feeAssetId == assetId
// Error code 23: createSwap, swap.feeAmount exceeds swap.amount
require(_values[2] < _values[0], "23"); // feeAmount < amount
} else {
_decreaseBalance(
_addresses[0], // maker
_addresses[3], // feeAssetId
_values[2], // feeAmount
REASON_SWAP_FEE_GIVE,
_values[3] // nonce
);
}
_decreaseBalance(
_addresses[0], // maker
_addresses[2], // assetId
_values[0], // amount
REASON_SWAP_GIVE,
_values[3] // nonce
);
atomicSwaps[swapHash] = true;
}
/// @notice Executes a swap by transferring the tokens previously locked through
/// a `createSwap` call to the swap taker.
///
/// @dev To reduce gas costs, the original parameters of the swap are not stored
/// in the contract's storage, only the hash of the parameters is stored for
/// verification, so the original parameters need to be re-specified here.
///
/// @param _addresses[0] maker: the address of the user to deduct the swap tokens from
/// @param _addresses[1] taker: the address of the swap taker who will receive the swap tokens
/// @param _addresses[2] assetId: the contract address of the token to swap
/// @param _addresses[3] feeAssetId: the contract address of the token to use as fees
/// @param _values[0] amount: the number of tokens previously locked
/// @param _values[1] expiryTime: the time in epoch seconds after which the swap will become cancellable
/// @param _values[2] feeAmount: the number of tokens to be paid to the operator as fees
/// @param _values[3] nonce: an unused nonce to prevent replay attacks
/// @param _hashedSecret The hash of the secret decided by the maker
/// @param _preimage The preimage of the `_hashedSecret`
function executeSwap(
address[4] calldata _addresses,
uint256[4] calldata _values,
bytes32 _hashedSecret,
bytes calldata _preimage
)
external
nonReentrant
{
// Error code 37: swap secret length exceeded
require(_preimage.length <= MAX_SWAP_SECRET_LENGTH, "37");
bytes32 swapHash = _hashSwap(_addresses, _values, _hashedSecret);
// Error code 24: executeSwap, swap is not active
require(atomicSwaps[swapHash], "24");
// Error code 25: executeSwap, hash of preimage does not match hashedSecret
require(sha256(abi.encodePacked(sha256(_preimage))) == _hashedSecret, "25");
uint256 takeAmount = _values[0];
if (_addresses[3] == _addresses[2]) { // feeAssetId == assetId
takeAmount = takeAmount.sub(_values[2]);
}
delete atomicSwaps[swapHash];
_increaseBalance(
_addresses[1], // taker
_addresses[2], // assetId
takeAmount,
REASON_SWAP_RECEIVE,
_values[3] // nonce
);
_increaseBalance(
operator,
_addresses[3], // feeAssetId
_values[2], // feeAmount
REASON_SWAP_FEE_RECEIVE,
_values[3] // nonce
);
}
/// @notice Cancels a swap and refunds the previously locked tokens to
/// the swap maker.
///
/// @dev To reduce gas costs, the original parameters of the swap are not stored
/// in the contract's storage, only the hash of the parameters is stored for
/// verification, so the original parameters need to be re-specified here.
///
/// @param _addresses[0] maker: the address of the user to deduct the swap tokens from
/// @param _addresses[1] taker: the address of the swap taker who will receive the swap tokens
/// @param _addresses[2] assetId: the contract address of the token to swap
/// @param _addresses[3] feeAssetId: the contract address of the token to use as fees
/// @param _values[0] amount: the number of tokens previously locked
/// @param _values[1] expiryTime: the time in epoch seconds after which the swap will become cancellable
/// @param _values[2] feeAmount: the number of tokens to be paid to the operator as fees
/// @param _values[3] nonce: an unused nonce to prevent replay attacks
/// @param _hashedSecret The hash of the secret decided by the maker
/// @param _cancelFeeAmount The number of tokens to be paid to the operator as the cancellation fee
function cancelSwap(
address[4] calldata _addresses,
uint256[4] calldata _values,
bytes32 _hashedSecret,
uint256 _cancelFeeAmount
)
external
nonReentrant
{
// Error code 26: cancelSwap, expiry time has not been reached
require(_values[1] <= now, "26");
bytes32 swapHash = _hashSwap(_addresses, _values, _hashedSecret);
// Error code 27: cancelSwap, swap is not active
require(atomicSwaps[swapHash], "27");
uint256 cancelFeeAmount = _cancelFeeAmount;
if (!adminAddresses[msg.sender]) { cancelFeeAmount = _values[2]; }
// cancelFeeAmount <= feeAmount
// Error code 28: cancelSwap, cancelFeeAmount exceeds swap.feeAmount
require(cancelFeeAmount <= _values[2], "28");
uint256 refundAmount = _values[0];
if (_addresses[3] == _addresses[2]) { // feeAssetId == assetId
refundAmount = refundAmount.sub(cancelFeeAmount);
}
delete atomicSwaps[swapHash];
_increaseBalance(
_addresses[0], // maker
_addresses[2], // assetId
refundAmount,
REASON_SWAP_CANCEL_RECEIVE,
_values[3] // nonce
);
_increaseBalance(
operator,
_addresses[3], // feeAssetId
cancelFeeAmount,
REASON_SWAP_CANCEL_FEE_RECEIVE,
_values[3] // nonce
);
if (_addresses[3] != _addresses[2]) { // feeAssetId != assetId
uint256 refundFeeAmount = _values[2].sub(cancelFeeAmount);
_increaseBalance(
_addresses[0], // maker
_addresses[3], // feeAssetId
refundFeeAmount,
REASON_SWAP_CANCEL_FEE_REFUND,
_values[3] // nonce
);
}
}
/// @dev Cache whether offer nonces are taken in the offer's nonce space
/// @param _values The _values param from the trade / networkTrade method
function _cacheOfferNonceStates(uint256[] memory _values) private view {
uint256 i = 1;
// i + numOffers * 2
uint256 end = i + (_values[0] & mask8) * 2;
// loop offers
for(i; i < end; i += 2) {
// Error code 38: Invalid nonce space
require(((_values[i] & mask128) >> 120) == 0, "38");
uint256 nonce = (_values[i] & mask120) >> 56;
if (_nonceTaken(nonce)) {
_values[i] = _values[i] | (uint256(1) << 120);
}
}
}
/// @dev Reduce available offer amounts of offers and store the remaining
/// offer amount in the `offers` mapping.
/// Offer nonces will also be marked as taken.
/// See the `trade` method for param details.
/// @param _values Values from `trade`
/// @param _hashes An array of offer hash keys
function _storeOfferData(
uint256[] memory _values,
bytes32[] memory _hashes
)
private
{
// takenAmounts with same size as numOffers
uint256[] memory takenAmounts = new uint256[](_values[0] & mask8);
uint256 i = 1;
// i += numOffers * 2
i += (_values[0] & mask8) * 2;
// i += numFills * 2
i += ((_values[0] & mask16) >> 8) * 2;
uint256 end = _values.length;
// loop matches
for (i; i < end; i++) {
uint256 offerIndex = _values[i] & mask8;
uint256 takeAmount = _values[i] >> 128;
takenAmounts[offerIndex] = takenAmounts[offerIndex].add(takeAmount);
}
i = 0;
end = _values[0] & mask8; // numOffers
// loop offers
for (i; i < end; i++) {
// we can use the cached nonce taken value here because offers have been
// validated to be unique
bool existingOffer = ((_values[i * 2 + 1] & mask128) >> 120) == 1;
bytes32 hashKey = _hashes[i * 2];
uint256 availableAmount = existingOffer ? offers[hashKey] : (_values[i * 2 + 2] & mask128);
// Error code 31: _storeOfferData, offer's available amount is zero
require(availableAmount > 0, "31");
uint256 remainingAmount = availableAmount.sub(takenAmounts[i]);
if (remainingAmount > 0) { offers[hashKey] = remainingAmount; }
if (existingOffer && remainingAmount == 0) { delete offers[hashKey]; }
if (!existingOffer) {
uint256 nonce = (_values[i * 2 + 1] & mask120) >> 56;
_markNonce(nonce);
}
}
}
/// @dev Mark all fill nonces as taken in the `usedNonces` mapping.
/// This also validates fill uniquness within the set of fills in `_values`,
/// since fill nonces are marked one at a time with validation that the
/// nonce to be marked has not been marked before.
/// See the `trade` method for param details.
/// @param _values Values from `trade`
function _storeFillNonces(uint256[] memory _values) private {
// 1 + numOffers * 2
uint256 i = 1 + (_values[0] & mask8) * 2;
// i + numFills * 2
uint256 end = i + ((_values[0] & mask16) >> 8) * 2;
// loop fills
for(i; i < end; i += 2) {
uint256 nonce = (_values[i] & mask120) >> 56;
_markNonce(nonce);
}
}
/// @dev The actual cancellation logic shared by `cancel`, `adminCancel`,
/// `slowCancel`.
/// The remaining offer amount is refunded back to the offer's maker, and
/// the specified cancellation fee will be deducted from the maker's balances.
function _cancel(
address _maker,
bytes32 _offerHash,
uint256 _expectedAvailableAmount,
address _offerAssetId,
uint256 _offerNonce,
address _cancelFeeAssetId,
uint256 _cancelFeeAmount
)
private
{
uint256 refundAmount = offers[_offerHash];
// Error code 32: _cancel, there is no offer amount left to cancel
require(refundAmount > 0, "32");
// Error code 33: _cancel, the remaining offer amount does not match
// the expectedAvailableAmount
require(refundAmount == _expectedAvailableAmount, "33");
delete offers[_offerHash];
if (_cancelFeeAssetId == _offerAssetId) {
refundAmount = refundAmount.sub(_cancelFeeAmount);
} else {
_decreaseBalance(
_maker,
_cancelFeeAssetId,
_cancelFeeAmount,
REASON_CANCEL_FEE_GIVE,
_offerNonce
);
}
_increaseBalance(
_maker,
_offerAssetId,
refundAmount,
REASON_CANCEL,
_offerNonce
);
_increaseBalance(
operator,
_cancelFeeAssetId,
_cancelFeeAmount,
REASON_CANCEL_FEE_RECEIVE,
_offerNonce // offer nonce
);
}
/// @dev The actual withdrawal logic shared by `withdraw`, `adminWithdraw`,
/// `slowWithdraw`. The specified amount is deducted from the `_withdrawer`'s
/// contract balance and transferred to the external `_receivingAddress`,
/// and the specified withdrawal fee will be deducted from the `_withdrawer`'s
/// balance.
function _withdraw(
address _withdrawer,
address payable _receivingAddress,
address _assetId,
uint256 _amount,
address _feeAssetId,
uint256 _feeAmount,
uint256 _nonce
)
private
{
// Error code 34: _withdraw, invalid withdrawal amount
require(_amount > 0, "34");
_validateAddress(_receivingAddress);
_decreaseBalance(
_withdrawer,
_assetId,
_amount,
REASON_WITHDRAW,
_nonce
);
_increaseBalance(
operator,
_feeAssetId,
_feeAmount,
REASON_WITHDRAW_FEE_RECEIVE,
_nonce
);
uint256 withdrawAmount;
if (_feeAssetId == _assetId) {
withdrawAmount = _amount.sub(_feeAmount);
} else {
_decreaseBalance(
_withdrawer,
_feeAssetId,
_feeAmount,
REASON_WITHDRAW_FEE_GIVE,
_nonce
);
withdrawAmount = _amount;
}
if (_assetId == ETHER_ADDR) {
_receivingAddress.transfer(withdrawAmount);
return;
}
Utils.transferTokensOut(
_receivingAddress,
_assetId,
withdrawAmount
);
}
/// @dev Creates a hash key for a swap using the swap's parameters
/// @param _addresses[0] Address of the user making the swap
/// @param _addresses[1] Address of the user taking the swap
/// @param _addresses[2] Contract address of the asset to swap
/// @param _addresses[3] Contract address of the fee asset
/// @param _values[0] The number of tokens to be transferred
/// @param _values[1] The time in epoch seconds after which the swap will become cancellable
/// @param _values[2] The number of tokens to pay as fees to the operator
/// @param _values[3] The swap nonce to prevent replay attacks
/// @param _hashedSecret The hash of the secret decided by the maker
/// @return The hash key of the swap
function _hashSwap(
address[4] memory _addresses,
uint256[4] memory _values,
bytes32 _hashedSecret
)
private
pure
returns (bytes32)
{
return keccak256(abi.encode(
SWAP_TYPEHASH,
_addresses[0], // maker
_addresses[1], // taker
_addresses[2], // assetId
_values[0], // amount
_hashedSecret, // hashedSecret
_values[1], // expiryTime
_addresses[3], // feeAssetId
_values[2], // feeAmount
_values[3] // nonce
));
}
/// @dev Checks if the `_nonce` had been previously taken.
/// To reduce gas costs, a single `usedNonces` value is used to
/// store the state of 256 nonces, using the formula:
/// nonceTaken = "usedNonces[_nonce / 256] bit (_nonce % 256)" != 0
/// For example:
/// nonce 0 taken: "usedNonces[0] bit 0" != 0 (0 / 256 = 0, 0 % 256 = 0)
/// nonce 1 taken: "usedNonces[0] bit 1" != 0 (1 / 256 = 0, 1 % 256 = 1)
/// nonce 2 taken: "usedNonces[0] bit 2" != 0 (2 / 256 = 0, 2 % 256 = 2)
/// nonce 255 taken: "usedNonces[0] bit 255" != 0 (255 / 256 = 0, 255 % 256 = 255)
/// nonce 256 taken: "usedNonces[1] bit 0" != 0 (256 / 256 = 1, 256 % 256 = 0)
/// nonce 257 taken: "usedNonces[1] bit 1" != 0 (257 / 256 = 1, 257 % 256 = 1)
/// @param _nonce The nonce to check
/// @return Whether the nonce has been taken
function _nonceTaken(uint256 _nonce) private view returns (bool) {
uint256 slotData = _nonce.div(256);
uint256 shiftedBit = uint256(1) << _nonce.mod(256);
uint256 bits = usedNonces[slotData];
// The check is for "!= 0" instead of "== 1" because the shiftedBit is
// not at the zero'th position, so it would require an additional
// shift to compare it with "== 1"
return bits & shiftedBit != 0;
}
/// @dev Sets the corresponding `_nonce` bit to 1.
/// An error will be raised if the corresponding `_nonce` bit was
/// previously set to 1.
/// See `_nonceTaken` for details on calculating the corresponding `_nonce` bit.
/// @param _nonce The nonce to mark
function _markNonce(uint256 _nonce) private {
// Error code 35: _markNonce, nonce cannot be zero
require(_nonce != 0, "35");
uint256 slotData = _nonce.div(256);
uint256 shiftedBit = 1 << _nonce.mod(256);
uint256 bits = usedNonces[slotData];
// Error code 36: _markNonce, nonce has already been marked
require(bits & shiftedBit == 0, "36");
usedNonces[slotData] = bits | shiftedBit;
}
/// @dev Validates that the specified `_hash` was signed by the specified `_user`.
/// This method supports the EIP712 specification, the older Ethereum
/// signed message specification is also supported for backwards compatibility.
/// @param _hash The original hash that was signed by the user
/// @param _user The user who signed the hash
/// @param _v The `v` component of the `_user`'s signature
/// @param _r The `r` component of the `_user`'s signature
/// @param _s The `s` component of the `_user`'s signature
/// @param _prefixed If true, the signature will be verified
/// against the Ethereum signed message specification instead of the
/// EIP712 specification
function _validateSignature(
bytes32 _hash,
address _user,
uint8 _v,
bytes32 _r,
bytes32 _s,
bool _prefixed
)
private
pure
{
Utils.validateSignature(
_hash,
_user,
_v,
_r,
_s,
_prefixed
);
}
/// @dev A utility method to increase the balance of a user.
/// A corressponding `BalanceIncrease` event will also be emitted.
/// @param _user The address to increase balance for
/// @param _assetId The asset's contract address
/// @param _amount The number of tokens to increase the balance by
/// @param _reasonCode The reason code for the `BalanceIncrease` event
/// @param _nonce The nonce for the `BalanceIncrease` event
function _increaseBalance(
address _user,
address _assetId,
uint256 _amount,
uint256 _reasonCode,
uint256 _nonce
)
private
{
if (_amount == 0) { return; }
balances[_user][_assetId] = balances[_user][_assetId].add(_amount);
emit BalanceIncrease(
_user,
_assetId,
_amount,
_reasonCode,
_nonce
);
}
/// @dev A utility method to decrease the balance of a user.
/// A corressponding `BalanceDecrease` event will also be emitted.
/// @param _user The address to decrease balance for
/// @param _assetId The asset's contract address
/// @param _amount The number of tokens to decrease the balance by
/// @param _reasonCode The reason code for the `BalanceDecrease` event
/// @param _nonce The nonce for the `BalanceDecrease` event
function _decreaseBalance(
address _user,
address _assetId,
uint256 _amount,
uint256 _reasonCode,
uint256 _nonce
)
private
{
if (_amount == 0) { return; }
balances[_user][_assetId] = balances[_user][_assetId].sub(_amount);
emit BalanceDecrease(
_user,
_assetId,
_amount,
_reasonCode,
_nonce
);
}
/// @dev Ensures that `_address` is not the zero address
/// @param _address The address to check
function _validateAddress(address _address) private pure {
Utils.validateAddress(_address);
}
/// @dev A utility method to increase balances of multiple addresses.
/// A corressponding `Increment` event will also be emitted.
/// @param _increments An array of amounts to increase a user's balance by,
/// the corresponding user and assetId is referenced by
/// _addresses[index * 2] and _addresses[index * 2 + 1] respectively
/// @param _addresses An array of user asset pairs in the form of:
/// [
/// user_1_address,
/// asset_1_address,
/// user_1_address,
/// asset_2_address,
/// user_2_address,
/// asset_1_address,
/// ...
/// ]
/// @param _static Indicates if the amount was pre-calculated or only known
/// at the time the transaction was executed
function _incrementBalances(
uint256[] memory _increments,
address[] memory _addresses,
uint256 _static
)
private
{
uint256 end = _increments.length;
for(uint256 i = 0; i < end; i++) {
uint256 increment = _increments[i];
if (increment == 0) { continue; }
balances[_addresses[i * 2]][_addresses[i * 2 + 1]] =
balances[_addresses[i * 2]][_addresses[i * 2 + 1]].add(increment);
emit Increment((i << 248) | (_static << 240) | increment);
}
}
/// @dev A utility method to decrease balances of multiple addresses.
/// A corressponding `Decrement` event will also be emitted.
/// @param _decrements An array of amounts to decrease a user's balance by,
/// the corresponding user and assetId is referenced by
/// _addresses[index * 2] and _addresses[index * 2 + 1] respectively
/// @param _addresses An array of user asset pairs in the form of:
/// [
/// user_1_address,
/// asset_1_address,
/// user_1_address,
/// asset_2_address,
/// user_2_address,
/// asset_1_address,
/// ...
/// ]
function _decrementBalances(
uint256[] memory _decrements,
address[] memory _addresses
)
private
{
uint256 end = _decrements.length;
for(uint256 i = 0; i < end; i++) {
uint256 decrement = _decrements[i];
if (decrement == 0) { continue; }
balances[_addresses[i * 2]][_addresses[i * 2 + 1]] =
balances[_addresses[i * 2]][_addresses[i * 2 + 1]].sub(decrement);
emit Decrement(i << 248 | decrement);
}
}
}
|
@dev Checks if the `_nonce` had been previously taken. To reduce gas costs, a single `usedNonces` value is used to store the state of 256 nonces, using the formula: nonceTaken = "usedNonces[_nonce / 256] bit (_nonce % 256)" != 0 For example: nonce 0 taken: "usedNonces[0] bit 0" != 0 (0 / 256 = 0, 0 % 256 = 0) nonce 1 taken: "usedNonces[0] bit 1" != 0 (1 / 256 = 0, 1 % 256 = 1) nonce 2 taken: "usedNonces[0] bit 2" != 0 (2 / 256 = 0, 2 % 256 = 2) nonce 255 taken: "usedNonces[0] bit 255" != 0 (255 / 256 = 0, 255 % 256 = 255) nonce 256 taken: "usedNonces[1] bit 0" != 0 (256 / 256 = 1, 256 % 256 = 0) nonce 257 taken: "usedNonces[1] bit 1" != 0 (257 / 256 = 1, 257 % 256 = 1) @param _nonce The nonce to check @return Whether the nonce has been taken The check is for "!= 0" instead of "== 1" because the shiftedBit is not at the zero'th position, so it would require an additional shift to compare it with "== 1"
|
function _nonceTaken(uint256 _nonce) private view returns (bool) {
uint256 slotData = _nonce.div(256);
uint256 shiftedBit = uint256(1) << _nonce.mod(256);
uint256 bits = usedNonces[slotData];
return bits & shiftedBit != 0;
}
| 13,110,368 |
[
1,
4081,
309,
326,
1375,
67,
12824,
68,
9323,
2118,
7243,
9830,
18,
2974,
5459,
16189,
22793,
16,
279,
2202,
1375,
3668,
3989,
764,
68,
460,
353,
1399,
358,
1707,
326,
919,
434,
8303,
1661,
764,
16,
1450,
326,
8013,
30,
7448,
27486,
273,
315,
3668,
3989,
764,
63,
67,
12824,
342,
8303,
65,
2831,
261,
67,
12824,
738,
8303,
2225,
480,
374,
2457,
3454,
30,
7448,
374,
9830,
30,
315,
3668,
3989,
764,
63,
20,
65,
2831,
374,
6,
480,
374,
261,
20,
342,
8303,
273,
374,
16,
374,
738,
8303,
273,
374,
13,
7448,
404,
9830,
30,
315,
3668,
3989,
764,
63,
20,
65,
2831,
404,
6,
480,
374,
261,
21,
342,
8303,
273,
374,
16,
404,
738,
8303,
273,
404,
13,
7448,
576,
9830,
30,
315,
3668,
3989,
764,
63,
20,
65,
2831,
576,
6,
480,
374,
261,
22,
342,
8303,
273,
374,
16,
576,
738,
2
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
[
1,
565,
445,
389,
12824,
27486,
12,
11890,
5034,
389,
12824,
13,
3238,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
2254,
5034,
4694,
751,
273,
389,
12824,
18,
2892,
12,
5034,
1769,
203,
3639,
2254,
5034,
21340,
5775,
273,
2254,
5034,
12,
21,
13,
2296,
389,
12824,
18,
1711,
12,
5034,
1769,
203,
3639,
2254,
5034,
4125,
273,
1399,
3989,
764,
63,
14194,
751,
15533,
203,
203,
3639,
327,
4125,
473,
21340,
5775,
480,
374,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//Address: 0xb8a88034bcf46e26c6bae1269ff2d051e2dee65c
//Contract name: MintableToken
//Balance: 0 Ether
//Verification Date: 2/15/2018
//Transacion Count: 14
// CODE STARTS HERE
pragma solidity ^0.4.18;
/**
* @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;
}
}
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);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping (address => Snapshot[]) balances;
mapping (address => uint256) userWithdrawalBlocks;
/**
* @dev 'Snapshot' is the structure that attaches a block number to a
* given value, the block number attached is the one that last changed the value
* 'fromBlock' - is the block number that the value was generated from
* 'value' - is the amount of tokens at a specific block number
*/
struct Snapshot {
uint128 fromBlock;
uint128 value;
}
/**
* @dev tracks history of totalSupply
*/
Snapshot[] totalSupplyHistory;
/**
* @dev track history of 'ETH balance' for dividends
*/
Snapshot[] balanceForDividendsHistory;
/**
* @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) {
return doTransfer(msg.sender, to, value);
}
/**
* @dev internal function for transfers handling
*/
function doTransfer(address _from, address _to, uint _amount) internal returns(bool) {
if (_amount == 0) {
return true;
}
// Do not allow transfer to 0x0 or the token contract itself
require((_to != 0) && (_to != address(this)));
// If the amount being transfered is more than the balance of the
// account the transfer returns false
var previousBalanceFrom = balanceOfAt(_from, block.number);
if (previousBalanceFrom < _amount) {
return false;
}
// First update the balance array with the new value for the address
// sending the tokens
updateValueAtNow(balances[_from], previousBalanceFrom - _amount);
// Then update the balance array with the new value for the address
// receiving the tokens
var previousBalanceTo = balanceOfAt(_to, block.number);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(balances[_to], previousBalanceTo + _amount);
// An event to make the transfer easy to find on the blockchain
Transfer(_from, _to, _amount);
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 balanceOfAt(_owner, block.number);
}
/**
* @dev Queries the balance of `_owner` at a specific `_blockNumber`
* @param _owner The address from which the balance will be retrieved
* @param _blockNumber The block number when the balance is queried
* @return The balance at `_blockNumber`
*/
function balanceOfAt(address _owner, uint _blockNumber) public constant returns (uint) {
// These next few lines are used when the balance of the token is
// requested before a check point was ever created for this token
if ((balances[_owner].length == 0)|| (balances[_owner][0].fromBlock > _blockNumber)) {
return 0;
} else {
return getValueAt(balances[_owner], _blockNumber);
}
}
/**
* @dev Total amount of tokens at a specific `_blockNumber`.
* @param _blockNumber The block number when the totalSupply is queried
* @return The total amount of tokens at `_blockNumber`
*/
function totalSupplyAt(uint _blockNumber) public constant returns(uint) {
// These next few lines are used when the totalSupply of the token is
// requested before a check point was ever created for this token
if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) {
return 0;
} else {
return getValueAt(totalSupplyHistory, _blockNumber);
}
}
/**
* @dev `getValueAt` retrieves the number of tokens at a given block number
* @param checkpoints The history of values being queried
* @param _block The block number to retrieve the value at
* @return The number of tokens being queried
*/
function getValueAt(Snapshot[] storage checkpoints, uint _block) constant internal returns (uint) {
if (checkpoints.length == 0) return 0;
// Shortcut for the actual value
if (_block >= checkpoints[checkpoints.length-1].fromBlock)
return checkpoints[checkpoints.length-1].value;
if (_block < checkpoints[0].fromBlock) return 0;
// Binary search of the value in the array
uint min = 0;
uint max = checkpoints.length-1;
while (max > min) {
uint mid = (max + min + 1)/ 2;
if (checkpoints[mid].fromBlock<=_block) {
min = mid;
} else {
max = mid-1;
}
}
return checkpoints[min].value;
}
/**
* @dev `updateValueAtNow` used to update the `balances` map and the `totalSupplyHistory`
* @param checkpoints The history of data being updated
* @param _value The new number of tokens
*/
function updateValueAtNow(Snapshot[] storage checkpoints, uint _value) internal {
if ((checkpoints.length == 0) || (checkpoints[checkpoints.length -1].fromBlock < block.number)) {
Snapshot storage newCheckPoint = checkpoints[ checkpoints.length++ ];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Snapshot storage oldCheckPoint = checkpoints[checkpoints.length-1];
oldCheckPoint.value = uint128(_value);
}
}
/**
* @dev This function makes it easy to get the total number of tokens
* @return The total number of tokens
*/
function redeemedSupply() public constant returns (uint) {
return totalSupplyAt(block.number);
}
}
contract Ownable {
address public owner;
/**
* @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));
owner = newOwner;
}
}
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) {
return doTransfer(_from, _to, _value);
}
/**
* @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];
}
}
contract MintableToken is StandardToken {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
string public name = "Honey Mining Token";
string public symbol = "HMT";
uint8 public decimals = 8;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) public canMint returns (bool) {
totalSupply = totalSupply.add(_amount);
uint curTotalSupply = redeemedSupply();
require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow
uint previousBalanceTo = balanceOf(_to);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount);
updateValueAtNow(balances[_to], previousBalanceTo + _amount);
Mint(_to, _amount);
Transfer(0x0, _to, _amount);
return true;
}
/**
* @dev Function to record snapshot block and amount
*/
function recordDeposit(uint256 _amount) public {
updateValueAtNow(balanceForDividendsHistory, _amount);
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
/**
* @dev Function to calculate dividends
* @return awailable for withdrawal ethere (wei value)
*/
function awailableDividends(address userAddress) public view returns (uint256) {
uint256 userLastWithdrawalBlock = userWithdrawalBlocks[userAddress];
uint256 amountForWithdraw = 0;
for(uint i = 0; i<=balanceForDividendsHistory.length-1; i++){
Snapshot storage snapshot = balanceForDividendsHistory[i];
if(userLastWithdrawalBlock < snapshot.fromBlock)
amountForWithdraw = amountForWithdraw.add(balanceOfAt(userAddress, snapshot.fromBlock).mul(snapshot.value).div(totalSupplyAt(snapshot.fromBlock)));
}
return amountForWithdraw;
}
/**
* @dev Function to record user withdrawal
*/
function recordWithdraw(address userAddress) public {
userWithdrawalBlocks[userAddress] = balanceForDividendsHistory[balanceForDividendsHistory.length-1].fromBlock;
}
}
contract HoneyMiningToken is Ownable {
using SafeMath for uint256;
MintableToken public token;
/**
* @dev Info of max supply
*/
uint256 public maxSupply = 300000000000000;
/**
* event for token purchase logging
* @param purchaser who paid for the tokens, basically - 0x0, but could be user address on refferal case
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount - of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
/**
* event for referral comission logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the bonus tokens
* @param amount - of tokens as ref reward
*/
event ReferralBonus(address indexed purchaser, address indexed beneficiary, uint amount);
/**
* event for token dividends deposit logging
* @param amount - amount of ETH deposited
*/
event DepositForDividends(uint256 indexed amount);
/**
* event for dividends withdrawal logging
* @param holder - who has the tokens
* @param amount - amount of ETH which was withdraw
*/
event WithdrawDividends(address indexed holder, uint256 amount);
/**
* event for dev rewards logging
* @param purchaser - who paid for the tokens
* @param amount - representation of dev reward
*/
event DevReward(address purchaser, uint amount);
function HoneyMiningToken() public {
token = new MintableToken();
}
/**
* @dev fallback function can be used to buy tokens
*/
function () public payable {buyTokens(0x0);}
/**
* @dev low level token purchase function
* @param referrer - optional parameter for ref bonus
*/
function buyTokens(address referrer) public payable {
require(msg.sender != 0x0);
require(msg.sender != referrer);
require(validPurchase());
//we dont need 18 decimals - and will use only 8
uint256 amount = msg.value.div(10000000000);
// calculate token amount to be created
uint256 tokens = amount.mul(rate());
require(tokens >= 100000000);
uint256 devTokens = tokens.mul(30).div(100);
if(referrer != 0x0){
require(token.balanceOf(referrer) >= 100000000);
// 2.5% for referral and referrer
uint256 refTokens = tokens.mul(25).div(1000);
//tokens = tokens+refTokens;
require(maxSupply.sub(redeemedSupply()) >= tokens.add(refTokens.mul(2)).add(devTokens));
//generate tokens for purchser
token.mint(msg.sender, tokens.add(refTokens));
TokenPurchase(msg.sender, msg.sender, amount, tokens.add(refTokens));
token.mint(referrer, refTokens);
ReferralBonus(msg.sender, referrer, refTokens);
} else{
require(maxSupply.sub(redeemedSupply())>=tokens.add(devTokens));
//updatedReddemedSupply = redeemedSupply().add(tokens.add(devTokens));
//generate tokens for purchser
token.mint(msg.sender, tokens);
// log purchase
TokenPurchase(msg.sender, msg.sender, amount, tokens);
}
token.mint(owner, devTokens);
DevReward(msg.sender, devTokens);
forwardFunds();
}
/**
* @return true if the transaction can buy tokens
*/
function validPurchase() internal constant returns (bool) {
return !hasEnded() && msg.value != 0;
}
/**
* @return true if sale is over
*/
function hasEnded() public constant returns (bool) {
return maxSupply <= redeemedSupply();
}
/**
* @dev get current user balance
* @param userAddress - address of user
* @return current balance of tokens
*/
function checkBalance(address userAddress) public constant returns (uint){
return token.balanceOf(userAddress);
}
/**
* @dev get user balance of tokens on specific block
* @param userAddress - address of user
* @param targetBlock - block number
* @return address balance on block
*/
function checkBalanceAt(address userAddress, uint256 targetBlock) public constant returns (uint){
return token.balanceOfAt(userAddress, targetBlock);
}
/**
* @dev get awailable dividends for withdrawal
* @param userAddress - target
* @return amount of ether (wei value) for current user
*/
function awailableDividends(address userAddress) public constant returns (uint){
return token.awailableDividends(userAddress);
}
/**
* @return total purchased tokens value
*/
function redeemedSupply() public view returns (uint){
return token.totalSupply();
}
/**
* @dev user-related method for withdrawal dividends
*/
function withdrawDividends() public {
uint _amount = awailableDividends(msg.sender);
require(_amount > 0);
msg.sender.transfer(_amount);
token.recordWithdraw(msg.sender);
WithdrawDividends(msg.sender, _amount);
}
/**
* @dev function for deposit ether to token address as/for dividends
*/
function depositForDividends() public payable onlyOwner {
require(msg.value > 0);
token.recordDeposit(msg.value);
DepositForDividends(msg.value);
}
function stopSales() public onlyOwner{
maxSupply = token.totalSupply();
}
function forwardFunds() internal {
owner.transfer(msg.value);
}
function rate() internal constant returns (uint) {
if(redeemedSupply() < 1000000000000)
return 675;
else if (redeemedSupply() < 5000000000000)
return 563;
else
return 450;
}
}
|
* @dev `getValueAt` retrieves the number of tokens at a given block number @param checkpoints The history of values being queried @param _block The block number to retrieve the value at @return The number of tokens being queried/ Shortcut for the actual value Binary search of the value in the array
|
function getValueAt(Snapshot[] storage checkpoints, uint _block) constant internal returns (uint) {
if (checkpoints.length == 0) return 0;
if (_block >= checkpoints[checkpoints.length-1].fromBlock)
return checkpoints[checkpoints.length-1].value;
if (_block < checkpoints[0].fromBlock) return 0;
uint min = 0;
uint max = checkpoints.length-1;
while (max > min) {
uint mid = (max + min + 1)/ 2;
if (checkpoints[mid].fromBlock<=_block) {
min = mid;
max = mid-1;
}
}
return checkpoints[min].value;
}
| 1,836,330 |
[
1,
68,
24805,
861,
68,
9023,
326,
1300,
434,
2430,
622,
279,
864,
1203,
1300,
225,
26402,
1021,
4927,
434,
924,
3832,
23264,
225,
389,
2629,
1021,
1203,
1300,
358,
4614,
326,
460,
622,
327,
1021,
1300,
434,
2430,
3832,
23264,
19,
7925,
5150,
364,
326,
3214,
460,
7896,
1623,
434,
326,
460,
316,
326,
526,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
2366,
861,
12,
4568,
8526,
2502,
26402,
16,
2254,
389,
2629,
13,
5381,
2713,
1135,
261,
11890,
13,
288,
203,
3639,
309,
261,
1893,
4139,
18,
2469,
422,
374,
13,
327,
374,
31,
203,
203,
3639,
309,
261,
67,
2629,
1545,
26402,
63,
1893,
4139,
18,
2469,
17,
21,
8009,
2080,
1768,
13,
203,
5411,
327,
26402,
63,
1893,
4139,
18,
2469,
17,
21,
8009,
1132,
31,
203,
3639,
309,
261,
67,
2629,
411,
26402,
63,
20,
8009,
2080,
1768,
13,
327,
374,
31,
203,
203,
3639,
2254,
1131,
273,
374,
31,
203,
3639,
2254,
943,
273,
26402,
18,
2469,
17,
21,
31,
203,
3639,
1323,
261,
1896,
405,
1131,
13,
288,
203,
5411,
2254,
7501,
273,
261,
1896,
397,
1131,
397,
404,
13176,
576,
31,
203,
5411,
309,
261,
1893,
4139,
63,
13138,
8009,
2080,
1768,
32,
33,
67,
2629,
13,
288,
203,
7734,
1131,
273,
7501,
31,
203,
7734,
943,
273,
7501,
17,
21,
31,
203,
5411,
289,
203,
3639,
289,
203,
3639,
327,
26402,
63,
1154,
8009,
1132,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.3;
// Openzeppelin.
import "./openzeppelin-solidity/contracts/SafeMath.sol";
// Interfaces.
import './interfaces/external/ICandlestickDataFeedRegistry.sol';
import './interfaces/external/IBotPerformanceDataFeed.sol';
import './interfaces/IComponentsRegistry.sol';
// Inheritance.
import './interfaces/ITradingBot.sol';
contract TradingBot is ITradingBot {
using SafeMath for uint256;
// Trading bot owner.
address public override owner;
address public operator;
address public keeper;
// Address of the BotPerformanceDataFeed contract.
address public override dataFeed;
// Contracts.
IComponentsRegistry immutable componentsRegistry;
ICandlestickDataFeedRegistry immutable candlestickDataFeedRegistry;
address immutable tradingBotRegistry;
address immutable keeperRegistry;
address immutable tradingBots;
// Parameters.
string public name;
string public symbol;
Parameters public params;
BotState public botState;
// Entry rules.
uint256[] public entryRuleComponents;
uint256[] public entryRuleInstances;
// Exit rules.
uint256[] public exitRuleComponents;
uint256[] public exitRuleInstances;
// Contract management.
bool public initialized;
bool public setRules;
uint256 public numberOfUpdates;
constructor(address _owner, address _componentsRegistry, address _candlestickDataFeedRegistry, address _tradingBotRegistry, address _keeperRegistry, address _tradingBots) {
// Initialize contracts.
owner = _owner;
operator = _owner;
componentsRegistry = IComponentsRegistry(_componentsRegistry);
candlestickDataFeedRegistry = ICandlestickDataFeedRegistry(_candlestickDataFeedRegistry);
tradingBotRegistry = _tradingBotRegistry;
keeperRegistry = _keeperRegistry;
tradingBots = _tradingBots;
}
/* ========== VIEWS ========== */
/**
* @notice Returns the parameters of this trading bot.
* @return (uint256, uint256, uint256, uint256, string, uint256) The trading bot's timeframe (in minutes), max trade duration, profit target, stop loss, the traded asset symbol, and the asset's timeframe.
*/
function getTradingBotParameters() external view override returns (uint256, uint256, uint256, uint256, string memory, uint256) {
// Gas savings.
Parameters memory parameters = params;
return (parameters.timeframe, parameters.maxTradeDuration, parameters.profitTarget, parameters.stopLoss, parameters.tradedAsset, parameters.assetTimeframe);
}
/**
* @notice Returns whether the trading bot can be updated.
*/
function canUpdate() public view override returns (bool) {
if (!initialized || !setRules || dataFeed == address(0)) {
return false;
}
return block.timestamp >= botState.lastUpdatedTimestamp.add(params.timeframe.mul(60)).sub(2);
}
/**
* @notice Returns the state of the trading bot.
* @return (bool, uint256, uint256, uint256) Whether the bot is in a trade, the entry price, the update number at which the trade was made, and the timestamp at which the last update was made.
*/
function getState() external view override returns (bool, uint256, uint256, uint256) {
// Gas savings.
BotState memory tradingBotState = botState;
return (tradingBotState.inTrade, tradingBotState.entryPrice, tradingBotState.entryIndex, tradingBotState.lastUpdatedTimestamp);
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Sets the initial entry/exit rules.
* @notice Assumes that the TradingBotRegistry checked if the bot owner has access to each entry/exit rule before calling this function.
* @param _entryRuleComponents An array of component IDs used in entry rules.
* @param _entryRuleInstances An array of component instance IDs used in entry rules.
* @param _exitRuleComponents An array of component IDs used in exit rules.
* @param _exitRuleInstances An array of component instance IDs used in exit rules.
*/
function setInitialRules(uint256[] memory _entryRuleComponents, uint256[] memory _entryRuleInstances, uint256[] memory _exitRuleComponents, uint256[] memory _exitRuleInstances) external override onlyTradingBotRegistry haveNotSetRules {
setRules = true;
for (uint256 i = 0; i < _entryRuleComponents.length; i++) {
entryRuleComponents.push(_entryRuleComponents[i]);
}
for (uint256 i = 0; i < _entryRuleInstances.length; i++) {
entryRuleInstances.push(_entryRuleInstances[i]);
}
for (uint256 i = 0; i < _exitRuleComponents.length; i++) {
exitRuleComponents.push(_exitRuleComponents[i]);
}
for (uint256 i = 0; i < _exitRuleInstances.length; i++) {
exitRuleInstances.push(_exitRuleInstances[i]);
}
emit SetRules(_entryRuleComponents, _entryRuleInstances, _exitRuleComponents, _exitRuleInstances);
}
/**
* @notice Updates the owner of this trading bot.
* @dev This function is meant to be called by the TradingBots NFT contract.
* @param _newOwner Address of the new owner.
*/
function updateOwner(address _newOwner) external override onlyTradingBots {
owner = _newOwner;
operator = _newOwner;
emit UpdatedOwner(_newOwner);
}
/**
* @notice Initializes the parameters for the trading bot.
* @dev This function is meant to be called by the TradingBotRegistry contract when creating a trading bot.
* @param _name Name of the trading bot.
* @param _symbol Symbol of the trading bot.
* @param _timeframe Number of minutes between updates.
* @param _maxTradeDuration Maximum number of [_timeframe] a trade can last for.
* @param _profitTarget % profit target for a trade. Denominated in 10000.
* @param _stopLoss % stop loss for a trade. Denominated in 10000.
* @param _tradedAsset Symbol of the asset this bot will simulate trades for.
* @param _assetTimeframe Timeframe to use for asset prices.
*/
function initialize(string memory _name, string memory _symbol, uint256 _timeframe, uint256 _maxTradeDuration, uint256 _profitTarget, uint256 _stopLoss, string memory _tradedAsset, uint256 _assetTimeframe) external override onlyTradingBotRegistry {
initialized = true;
name = _name;
symbol = _symbol;
params = Parameters({
timeframe: _timeframe,
maxTradeDuration: _maxTradeDuration,
profitTarget: _profitTarget,
stopLoss: _stopLoss,
tradedAsset: _tradedAsset,
assetTimeframe: _assetTimeframe
});
emit Initialized(_name, _symbol, _timeframe, _maxTradeDuration, _profitTarget, _stopLoss, _tradedAsset, _assetTimeframe);
}
/**
* @notice Gets the latest price of the trading bot's traded asset and uses it to update the bot's state based on entry/exit rules.
* @dev Simulates an order if entry/exit rules are met.
* @dev This function is meant to be called once per timeframe by a Keeper contract.
*/
function update() external override onlyKeeper returns (bool) {
require(canUpdate(), "TradingBot: Cannot update yet.");
// Gas savings.
uint256 index = numberOfUpdates.add(1);
uint256 latestPrice;
uint256 highPrice;
uint256 lowPrice;
{
string memory asset = params.tradedAsset;
uint256 assetTimeframe = params.assetTimeframe;
(, highPrice, lowPrice,,latestPrice,,) = candlestickDataFeedRegistry.getCurrentCandlestick(asset, assetTimeframe);
}
numberOfUpdates = index;
botState.lastUpdatedTimestamp = block.timestamp;
// Trading bot is not currently in a trade.
if (!botState.inTrade) {
// Check entry rules.
if (_checkRules(true)) {
botState.inTrade = true;
botState.entryIndex = index;
botState.entryPrice = latestPrice;
IBotPerformanceDataFeed(dataFeed).updateData(params.tradedAsset, true, latestPrice, block.timestamp);
}
}
// Trading bot has an open position.
else {
// Check if profit target is met.
if (highPrice >= botState.entryPrice.mul(params.profitTarget.add(10000)).div(10000)) {
botState.inTrade = false;
IBotPerformanceDataFeed(dataFeed).updateData(params.tradedAsset, false, botState.entryPrice.mul(params.profitTarget.add(10000)).div(10000), block.timestamp);
}
// Check if stop loss is met.
else if (lowPrice <= botState.entryPrice.mul(uint256(10000).sub(params.stopLoss)).div(10000)) {
botState.inTrade = false;
IBotPerformanceDataFeed(dataFeed).updateData(params.tradedAsset, false, botState.entryPrice.mul(uint256(10000).sub(params.stopLoss)).div(10000), block.timestamp);
}
// Check if max trade duration is met or exit rules are met.
else if (index >= botState.entryIndex.add(params.maxTradeDuration) || _checkRules(false)) {
botState.inTrade = false;
IBotPerformanceDataFeed(dataFeed).updateData(params.tradedAsset, false, latestPrice, block.timestamp);
}
}
emit Updated(params.tradedAsset, latestPrice);
return true;
}
/**
* @notice Updates the dedicated keeper for the trading bot.
* @dev This function can only be called by the KeeperRegistry contract.
* @param _newKeeper Address of the new keeper contract.
*/
function setKeeper(address _newKeeper) external override onlyKeeperRegistry {
keeper = _newKeeper;
emit SetKeeper(_newKeeper);
}
/**
* @notice Updates the operator address for the trading bot.
* @dev This function can only be called by the current operator.
* @param _newOperator Address of the new operator.
*/
function setOperator(address _newOperator) external override onlyOperator {
require(_newOperator != address(0), "TradingBot: Invalid address for _newOperator.");
operator = _newOperator;
emit SetOperator(_newOperator);
}
/**
* @notice Adds a new entry/exit rule.
* @dev This function can only be called by the operator.
* @dev Transaction will revert if the bot's owner does not have access to the comparator's instance.
* @param _isEntryRule Whether the rule to add is an entry rule.
* @param _comparatorID ID of the comparator.
* @param _instanceID ID of the comparator's instance.
*/
function addRule(bool _isEntryRule, uint256 _comparatorID, uint256 _instanceID) external override onlyOperator {
require(componentsRegistry.hasPurchasedComponentInstance(owner, _comparatorID, _instanceID), "TradingBot: Owner has not purchased this comparator instance.");
if (_isEntryRule) {
require(entryRuleComponents.length < 7, "TradingBot: Already have max number of entry rules.");
entryRuleComponents.push(_comparatorID);
entryRuleInstances.push(_instanceID);
}
else {
require(exitRuleComponents.length < 7, "TradingBot: Already have max number of exit rules.");
exitRuleComponents.push(_comparatorID);
exitRuleInstances.push(_instanceID);
}
emit AddedRule(_isEntryRule, _comparatorID, _instanceID);
}
/**
* @notice Removes the rule at the given index.
* @dev This function can only be called by the operator.
* @dev Transaction will revert if the entry/exit rule is out of bounds.
* @param _isEntryRule Whether the rule to remove is an entry rule.
* @param _index Index in the array of entry/exit rules.
*/
function removeRule(bool _isEntryRule, uint256 _index) external override onlyOperator {
uint256 length = _isEntryRule ? entryRuleComponents.length : exitRuleComponents.length;
require(_index < length, "TradingBot: Index out of bounds.");
uint256 componentID = _isEntryRule ? entryRuleComponents[_index] : exitRuleComponents[_index];
uint256 instanceID = _isEntryRule ? entryRuleInstances[_index] : exitRuleInstances[_index];
if (_isEntryRule) {
entryRuleComponents[_index] = entryRuleComponents[length.sub(1)];
entryRuleComponents.pop();
entryRuleInstances[_index] = entryRuleInstances[length.sub(1)];
entryRuleInstances.pop();
}
else {
exitRuleComponents[_index] = exitRuleComponents[length.sub(1)];
exitRuleComponents.pop();
exitRuleInstances[_index] = exitRuleInstances[length.sub(1)];
exitRuleInstances.pop();
}
emit RemovedRule(_isEntryRule, componentID, instanceID);
}
/**
* @notice Replaces the rule at the given index with the new rule.
* @dev This function can only be called by the operator.
* @dev Transaction will revert if the entry/exit rule is out of bounds.
* @dev Transaction will revert if the trading bot owner does not have access to the new rule.
* @param _isEntryRule Whether the rule to replace is an entry rule.
* @param _index Index in the array of entry/exit rules.
* @param _comparatorID ID of the comparator.
* @param _instanceID ID of the comparator's instance.
*/
function replaceRule(bool _isEntryRule, uint256 _index, uint256 _comparatorID, uint256 _instanceID) external override onlyOperator {
require(componentsRegistry.hasPurchasedComponentInstance(owner, _comparatorID, _instanceID), "TradingBot: Owner has not purchased this comparator instance.");
uint256 length = _isEntryRule ? entryRuleComponents.length : exitRuleComponents.length;
require(_index < length, "TradingBot: Index out of bounds.");
uint256 oldComponentID = _isEntryRule ? entryRuleComponents[_index] : exitRuleComponents[_index];
uint256 oldInstanceID = _isEntryRule ? entryRuleInstances[_index] : exitRuleInstances[_index];
if (_isEntryRule) {
entryRuleComponents[_index] = _comparatorID;
entryRuleInstances[_index] = _instanceID;
}
else {
exitRuleComponents[_index] = _comparatorID;
exitRuleInstances[_index] = _instanceID;
}
emit ReplacedRule(_isEntryRule, oldComponentID, oldInstanceID, _comparatorID, _instanceID);
}
/**
* @notice Updates the bot's traded asset.
* @dev This function can only be called by the operator.
* @dev Transaction will revert if there's not data feed for the asset with the given timeframe.
* @param _newTradedAsset Symbol of the new traded asset.
* @param _newAssetTimeframe Timeframe to use for asset prices.
*/
function updateTradedAsset(string memory _newTradedAsset, uint256 _newAssetTimeframe) external override onlyOperator {
require(!botState.inTrade, "TradingBot: Cannot update traded asset while in a trade.");
require(candlestickDataFeedRegistry.hasDataFeed(_newTradedAsset, _newAssetTimeframe), "TradingBot: Data feed not found.");
params.tradedAsset = _newTradedAsset;
params.assetTimeframe = _newAssetTimeframe;
emit UpdatedTradedAsset(_newTradedAsset, _newAssetTimeframe);
}
/**
* @notice Updates the bot's timeframe.
* @dev This function can only be called by the operator.
* @param _newTimeframe The new timeframe, in minutes.
*/
function updateTimeframe(uint256 _newTimeframe) external override onlyOperator {
require(_newTimeframe >= 1 && _newTimeframe <= 1440, "TradingBot: Timeframe out of bounds.");
params.timeframe = _newTimeframe;
emit UpdatedTimeframe(_newTimeframe);
}
/**
* @notice Updates the bot's max trade duration.
* @dev This function can only be called by the operator.
* @param _newMaxTradeDuration The new max trade duration, in [timeframe].
*/
function updateMaxTradeDuration(uint256 _newMaxTradeDuration) external override onlyOperator {
require(_newMaxTradeDuration > 1 && _newMaxTradeDuration <= 100, "TradingBot: Max trade duration out of bounds.");
params.maxTradeDuration = _newMaxTradeDuration;
emit UpdatedMaxTradeDuration(_newMaxTradeDuration);
}
/**
* @notice Updates the bot's profit target.
* @dev This function can only be called by the operator.
* @param _newProfitTarget The new profit target %, denominated in 10000. Ex) 1% = 100.
*/
function updateProfitTarget(uint256 _newProfitTarget) external override onlyOperator {
require(_newProfitTarget >= 10 && _newProfitTarget <= 100000, "TradingBot: Profit target out of bounds.");
params.profitTarget = _newProfitTarget;
emit UpdatedProfitTarget(_newProfitTarget);
}
/**
* @notice Updates the bot's stop loss.
* @dev This function can only be called by the operator.
* @param _newStopLoss The new stop loss %, denominated in 10000. Ex) 1% = 100.
*/
function updateStopLoss(uint256 _newStopLoss) external override onlyOperator {
require(_newStopLoss >= 10 && _newStopLoss <= 9900, "TradingBot: Stop loss out of bounds.");
params.stopLoss = _newStopLoss;
emit UpdatedStopLoss(_newStopLoss);
}
/**
* @notice Sets the address of the trading bot's BotPerformanceDataFeed contract.
* @dev This function can only be called once by the TradingBotRegistry contract.
* @dev Trading bots only have a data feed once they are published to the platform.
* @param _dataFeed Address of the BotPerformanceDataFeed contract.
*/
function setDataFeed(address _dataFeed) external override onlyTradingBotRegistry {
dataFeed = _dataFeed;
emit SetDataFeed(_dataFeed);
}
/* ========== INTERNAL FUNCTIONS ========== */
/**
* @notice Returns whether each entry/exit rule meets conditions.
*/
function _checkRules(bool _checkEntryRules) internal view returns (bool) {
uint256 length = _checkEntryRules ? entryRuleComponents.length : exitRuleComponents.length;
if (_checkEntryRules) {
for (uint256 i = 0; i < length; i++) {
if (!componentsRegistry.meetsConditions(entryRuleComponents[i], entryRuleInstances[i])) {
return false;
}
}
}
else {
for (uint256 i = 0; i < length; i++) {
if (!componentsRegistry.meetsConditions(exitRuleComponents[i], exitRuleInstances[i])) {
return false;
}
}
}
return true;
}
/* ========== MODIFIERS ========== */
modifier onlyKeeper() {
require(msg.sender == keeper, "TradingBot: Only the dedicated keeper can call this function.");
_;
}
modifier onlyOperator() {
require(msg.sender == operator, "TradingBot: Only the operator can call this function.");
_;
}
modifier onlyKeeperRegistry() {
require(msg.sender == keeperRegistry, "TradingBot: Only the KeeperRegistry contract can call this function.");
_;
}
modifier onlyTradingBots() {
require(msg.sender == tradingBots, "TradingBot: Only the TradingBots NFT contract can call this function.");
_;
}
modifier onlyTradingBotRegistry() {
require(msg.sender == tradingBotRegistry, "TradingBot: Only the TradingBotRegistry contract can call this function.");
_;
}
modifier haveNotSetRules() {
require(!setRules, "TradingBot: Already set initial entry/exit rules.");
_;
}
/* ========== EVENTS ========== */
event UpdatedOwner(address newOwner);
event UpdatedOperator(address newOperator);
event Initialized(string name, string symbol, uint256 timeframe, uint256 maxTradeDuration, uint256 profitTarget, uint256 stopLoss, string tradedAsset, uint256 assetTimeframe);
event SetRules(uint256[] entryRuleComponents, uint256[] entryRuleInstances, uint256[] exitRuleComponents, uint256[] exitRuleInstances);
event SetKeeper(address newKeeper);
event SetOperator(address newOperator);
event SetDataFeed(address newDataFeed);
event UpdatedProfitTarget(uint256 newProfitTarget);
event UpdatedStopLoss(uint256 newStopLoss);
event UpdatedMaxTradeDuration(uint256 newMaxTradeDuration);
event UpdatedTimeframe(uint256 newTimeframe);
event UpdatedTradedAsset(string newTradedAsset, uint256 newAssetTimeframe);
event AddedRule(bool isEntryRule, uint256 componentID, uint256 instanceID);
event RemovedRule(bool isEntryRule, uint256 componentID, uint256 instanceID);
event ReplacedRule(bool isEntryRule, uint256 oldComponentID, uint256 oldInstanceID, uint256 newComponentID, uint256 newInstanceID);
event Updated(string asset, uint256 latestPrice);
}
|
* @notice Updates the bot's max trade duration. @dev This function can only be called by the operator. @param _newMaxTradeDuration The new max trade duration, in [timeframe]./
|
function updateMaxTradeDuration(uint256 _newMaxTradeDuration) external override onlyOperator {
require(_newMaxTradeDuration > 1 && _newMaxTradeDuration <= 100, "TradingBot: Max trade duration out of bounds.");
params.maxTradeDuration = _newMaxTradeDuration;
emit UpdatedMaxTradeDuration(_newMaxTradeDuration);
}
| 5,454,647 |
[
1,
5121,
326,
2512,
1807,
943,
18542,
3734,
18,
225,
1220,
445,
848,
1338,
506,
2566,
635,
326,
3726,
18,
225,
389,
2704,
2747,
22583,
5326,
1021,
394,
943,
18542,
3734,
16,
316,
306,
957,
3789,
8009,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
1089,
2747,
22583,
5326,
12,
11890,
5034,
389,
2704,
2747,
22583,
5326,
13,
3903,
3849,
1338,
5592,
288,
203,
3639,
2583,
24899,
2704,
2747,
22583,
5326,
405,
404,
597,
389,
2704,
2747,
22583,
5326,
1648,
2130,
16,
315,
1609,
7459,
6522,
30,
4238,
18542,
3734,
596,
434,
4972,
1199,
1769,
203,
203,
3639,
859,
18,
1896,
22583,
5326,
273,
389,
2704,
2747,
22583,
5326,
31,
203,
203,
3639,
3626,
19301,
2747,
22583,
5326,
24899,
2704,
2747,
22583,
5326,
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
] |
/*
* This code has not been reviewed.
* Do not use or deploy this code before reviewing it personally first.
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "../erc1820/ERC1820Client.sol";
import "../erc1820/ERC1820Implementer.sol";
import "../extensions/userExtensions/IERC1400TokensRecipient.sol";
import "../interface/IERC20HoldableToken.sol";
import "../interface/IHoldableERC1400TokenExtension.sol";
import "../IERC1400.sol";
import '../helpers/Errors.sol';
/**
* @title Swaps
* @dev Delivery-Vs-Payment contract for investor-to-investor token trades.
* @dev Intended usage:
* The purpose of the contract is to allow secure token transfers/exchanges between 2 stakeholders (called holder1 and holder2).
* From now on, an operation in the Swaps smart contract (transfer/exchange) is called a trade.
* Depending on the type of trade, one/multiple token transfers will be executed.
*
* The simplified workflow is the following:
* 1) A trade request is created in the Swaps smart contract, it specifies:
* - The token holder(s) involved in the trade
* - The trade executer (optional)
* - An expiration date
* - Details on the first token (address, requested amount, standard)
* - Details on the second token (address, requested amount, standard)
* - Whether the tokens need to be escrowed in the Swaps contract or not
* - The current status of the trade (pending / executed / forced / cancelled)
* 2) The trade is accepted by both token holders
* 3) [OPTIONAL] The trade is approved by token controllers (only if requested by tokens controllers)
* 4) The trade is executed (either by the executer in case the executer is specified, or by anyone)
*
* STANDARD-AGNOSTIC:
* The Swaps smart contract is standard-agnostic, it supports ETH, ERC20, ERC721, ERC1400.
* The advantage of using an ERC1400 token is to leverages its hook property, thus requiring ONE single
* transaction (operatorTransferByPartition()) to send tokens to the Swaps smart contract instead of TWO
* with the ERC20 token standard (approve() + transferFrom()).
*
* OFF-CHAIN PAYMENT:
* The contract can be used as escrow contract while waiting for an off-chain payment.
* Once payment is received off-chain, the token sender realeases the tokens escrowed in
* the Swaps contract to deliver them to the recipient.
*
* ESCROW VS SWAP MODE:
* In case escrow mode is selected, tokens need to be escrowed in Swaps smart contract
* before the trade can occur.
* In case swap mode is selected, tokens are not escrowed in the Swaps. Instead, the Swaps
* contract is only allowed to transfer tokens ON BEHALF of their owners. When trade is
* executed, an atomic token swap occurs.
*
* EXPIRATION DATE:
* The trade can be cancelled by both parties in case expiration date is passed.
*
* CLAIMS:
* The executer has the ability to force or cancel the trade.
* In case of disagreement/missing payment, both parties can contact the "executer"
* of the trade to deposit a claim and solve the issue.
*
* MARKETPLACE:
* The contract can be used as a token marketplace. Indeed, when trades are created
* without specifying the recipient address, anyone can purchase them by sending
* the requested payment in exchange.
*
* PRICE ORACLES:
* When price oracles are defined, those can define the price at which trades need to be executed.
* This feature is particularly useful for assets with NAV (net asset value).
*
*/
contract Swaps is Ownable, ERC1820Client, IERC1400TokensRecipient, ERC1820Implementer {
string constant internal DELIVERY_VS_PAYMENT = "DeliveryVsPayment";
string constant internal ERC1400_TOKENS_RECIPIENT = "ERC1400TokensRecipient";
uint256 constant internal SECONDS_IN_MONTH = 86400 * 30;
uint256 constant internal SECONDS_IN_WEEK = 86400 * 7;
bytes32 constant internal TRADE_PROPOSAL_FLAG = 0xcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc;
bytes32 constant internal TRADE_ACCEPTANCE_FLAG = 0xdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd;
bytes32 constant internal BYPASS_ACTION_FLAG = 0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;
bytes32 constant internal ALL_PARTITIONS = 0x0000000000000000000000000000000000000000000000000000000000000000;
enum Standard {OffChain, ETH, ERC20, ERC721, ERC1400}
enum State {Undefined, Pending, Executed, Forced, Cancelled}
enum TradeType {Allowance, Hold, Escrow}
enum Holder {Holder1, Holder2}
string internal constant ERC1400_TOKENS_VALIDATOR = "ERC1400TokensValidator";
/**
@dev Include token events so they can be parsed by Ethereum clients from the settlement transactions.
*/
// Holdable
event ExecutedHold(
address indexed token,
bytes32 indexed holdId,
bytes32 lockPreimage,
address recipient
);
// ERC20
event Transfer(address indexed from, address indexed to, uint256 tokens);
// ERC1400
event TransferByPartition(
bytes32 indexed fromPartition,
address operator,
address indexed from,
address indexed to,
uint256 value,
bytes data,
bytes operatorData
);
event CreateNote(
address indexed owner,
bytes32 indexed noteHash,
bytes metadata
);
event DestroyNote(address indexed owner, bytes32 indexed noteHash);
struct UserTradeData {
address tokenAddress;
uint256 tokenValue;
bytes32 tokenId;
Standard tokenStandard;
bool accepted;
bool approved;
TradeType tradeType;
address receiver;
}
/**
* @dev Input data for the requestTrade function
* @param holder1 Address of the first token holder.
* @param holder2 Address of the second token holder.
* @param executer Executer of the trade.
* @param expirationDate Expiration date of the trade.
* @param tokenAddress1 Address of the first token smart contract.
* @param tokenValue1 Amount of tokens to send for the first token.
* @param tokenId1 ERC721ID/holdId/partition of the first token.
* @param tokenStandard1 Standard of the first token (ETH | ERC20 | ERC721 | ERC1400).
* @param tokenAddress2 Address of the second token smart contract.
* @param tokenValue2 Amount of tokens to send for the second token.
* @param tokenId2 ERC721ID/holdId/partition of the second token.
* @param tokenStandard2 Standard of the second token (ETH | ERC20 | ERC721 | ERC1400).
* @param tradeType Indicates whether or not tokens shall be escrowed in the Swaps contract before the trade.
*/
struct TradeRequestInput {
address holder1;
address holder2;
address executer; // Set to address(0) if no executer is required for the trade
uint256 expirationDate;
address tokenAddress1;
uint256 tokenValue1;
bytes32 tokenId1;
Standard tokenStandard1;
address receiver1;
address tokenAddress2; // Set to address(0) if no token is expected in return (for example in case of an off-chain payment)
uint256 tokenValue2;
bytes32 tokenId2;
Standard tokenStandard2;
address receiver2;
TradeType tradeType1;
TradeType tradeType2;
uint256 settlementDate;
}
struct Trade {
address holder1;
address holder2;
address executer;
uint256 expirationDate;
uint256 settlementDate;
UserTradeData userTradeData1;
UserTradeData userTradeData2;
State state;
}
// Index of most recent trade request.
uint256 internal _index;
// Mapping from index to trade requests.
mapping(uint256 => Trade) internal _trades;
// Mapping from token to price oracles.
mapping(address => address[]) internal _priceOracles;
// Mapping from (token, operator) to price oracle status.
mapping(address => mapping(address => bool)) internal _isPriceOracle;
// Mapping from (token1, token2) to price ownership.
mapping(address => mapping(address => bool)) internal _priceOwnership;
// Mapping from (token1, token2, tokenId1, tokenId2) to price.
mapping(address => mapping (address => mapping (bytes32 => mapping (bytes32 => uint256)))) internal _tokenUnitPricesByPartition;
// Indicate whether Swaps smart contract is owned or not (for instance by an exchange, etc.).
bool internal _ownedContract;
// Array of trade execcuters.
address[] internal _tradeExecuters;
// Mapping from operator to trade executer status.
mapping(address => bool) internal _isTradeExecuter;
// Mapping from token to token controllers.
mapping(address => address[]) internal _tokenControllers;
// Mapping from (token, operator) to token controller status.
mapping(address => mapping(address => bool)) internal _isTokenController;
// Mapping from token to variable price start date.
mapping(address => uint256) internal _variablePriceStartDate;
/**
* @dev Modifier to verify if sender is a token controller.
*/
modifier onlyTokenController(address tokenAddress) {
require(
_msgSender() == Ownable(tokenAddress).owner() ||
_isTokenController[tokenAddress][_msgSender()],
Errors.SW_SENDER_NOT_TOKEN_CONTROLLER
);
_;
}
/**
* @dev Modifier to verify if sender is a price oracle.
*/
modifier onlyPriceOracle(address tokenAddress) {
require(_checkPriceOracle(tokenAddress, _msgSender()), Errors.SW_SENDER_NOT_PRICE_ORACLE);
_;
}
/**
* [Swaps CONSTRUCTOR]
* @dev Initialize Swaps + register
* the contract implementation in ERC1820Registry.
*/
constructor(bool owned) {
ERC1820Implementer._setInterface(DELIVERY_VS_PAYMENT);
ERC1820Implementer._setInterface(ERC1400_TOKENS_RECIPIENT);
setInterfaceImplementation(ERC1400_TOKENS_RECIPIENT, address(this));
_ownedContract = owned;
if(_ownedContract) {
address[] memory initialTradeExecuters = new address[] (1);
initialTradeExecuters[0] = _msgSender();
_setTradeExecuters(initialTradeExecuters);
}
}
/**
* [ERC1400TokensRecipient INTERFACE (1/2)]
* @dev Indicate whether or not the Swaps contract can receive the tokens or not. [USED FOR ERC1400 TOKENS ONLY]
* @param data Information attached to the token transfer.
* @param operatorData Information attached to the Swaps transfer, by the operator.
* @return 'true' if the Swaps contract can receive the tokens, 'false' if not.
*/
function canReceive(bytes calldata, bytes32, address, address, address, uint, bytes calldata data, bytes calldata operatorData) external override view returns(bool) {
return(_canReceive(data, operatorData));
}
/**
* [ERC1400TokensRecipient INTERFACE (2/2)]
* @dev Hook function executed when tokens are sent to the Swaps contract. [USED FOR ERC1400 TOKENS ONLY]
* @param partition Name of the partition.
* @param from Token holder.
* @param to Token recipient.
* @param value Number of tokens to transfer.
* @param data Information attached to the token transfer.
* @param operatorData Information attached to the Swaps transfer, by the operator.
*/
function tokensReceived(bytes calldata, bytes32 partition, address, address from, address to, uint value, bytes memory data, bytes calldata operatorData) external override {
require(interfaceAddr(_msgSender(), "ERC1400Token") == _msgSender(), Errors.TR_SENDER_NOT_ERC1400_TOKEN); // funds locked (lockup period)
require(to == address(this), Errors.TR_TO_ADDRESS_NOT_ME); // 0x50 transfer failure
require(_canReceive(data, operatorData), Errors.TR_INVALID_RECEIVER); // 0x57 invalid receiver
bytes32 flag = _getTradeFlag(data);
if(flag == TRADE_PROPOSAL_FLAG) {
address recipient;
address executor;
uint256 expirationDate;
uint256 settlementDate;
assembly {
recipient:= mload(add(data, 64))
executor:= mload(add(data, 96))
expirationDate:= mload(add(data, 128))
settlementDate:= mload(add(data, 160))
}
// Token data: < 1: address > < 2: amount > < 3: id/partition > < 4: standard > < 5: accepted > < 6: approved >
UserTradeData memory _tradeData1 = UserTradeData(_msgSender(), value, partition, Standard.ERC1400, true, false, TradeType.Escrow, address(0));
UserTradeData memory _tokenData2 = _getTradeTokenData(data);
_requestTrade(
from,
recipient,
executor,
expirationDate,
settlementDate,
_tradeData1,
_tokenData2
);
} else if (flag == TRADE_ACCEPTANCE_FLAG) {
uint256 index;
bytes32 preimage = bytes32(0);
assembly {
index:= mload(add(data, 64))
}
if (data.length == 96) {
//This field is optional
//If the data's length does not include the preimage
//then return an empty preimage
//canReceive accepts both data lengths
assembly {
preimage:= mload(add(data, 96))
}
}
Trade storage trade = _trades[index];
UserTradeData memory selectedUserTradeData = (from == trade.holder1) ? trade.userTradeData1 : trade.userTradeData2;
require(_msgSender() == selectedUserTradeData.tokenAddress, Errors.SW_WRONG_TOKEN_SENT);
require(partition == selectedUserTradeData.tokenId, Errors.SW_TOKENS_IN_WRONG_PARTITION);
require(Standard.ERC1400 == selectedUserTradeData.tokenStandard, Errors.SW_TOKEN_INCORRECT_STANDARD);
_acceptTrade(index, from, 0, value, preimage);
}
}
/**
* @dev Create a new trade request in the Swaps smart contract.
* @param inputData The input for this function
*/
function requestTrade(TradeRequestInput calldata inputData, bytes32 preimage)
external
payable
{
_requestTrade(
inputData.holder1,
inputData.holder2,
inputData.executer,
inputData.expirationDate,
inputData.settlementDate,
UserTradeData(inputData.tokenAddress1, inputData.tokenValue1, inputData.tokenId1, inputData.tokenStandard1, false, false, inputData.tradeType1, inputData.receiver1),
UserTradeData(inputData.tokenAddress2, inputData.tokenValue2, inputData.tokenId2, inputData.tokenStandard2, false, false, inputData.tradeType2, inputData.receiver2)
);
if(_msgSender() == inputData.holder1 || _msgSender() == inputData.holder2) {
_acceptTrade(_index, _msgSender(), msg.value, 0, preimage);
}
}
/**
* @dev Create a new trade request in the Swaps smart contract.
* @param holder1 Address of the first token holder.
* @param holder2 Address of the second token holder.
* @param executer Executer of the trade.
* @param expirationDate Expiration date of the trade.
* @param userTradeData1 Encoded pack of variables for token1 (address, amount, id/partition, standard, accepted, approved).
* @param userTradeData2 Encoded pack of variables for token2 (address, amount, id/partition, standard, accepted, approved).
*/
function _requestTrade(
address holder1,
address holder2,
address executer, // Set to address(0) if no executer is required for the trade
uint256 expirationDate,
uint256 settlementDate,
UserTradeData memory userTradeData1,
UserTradeData memory userTradeData2
)
internal
{
if(userTradeData1.tokenStandard == Standard.ETH) {
require(userTradeData1.tradeType == TradeType.Escrow, Errors.SW_ETH_TRADE_REQUIRES_ESCROW);
}
if(userTradeData2.tokenStandard == Standard.ETH) {
require(userTradeData2.tradeType == TradeType.Escrow, Errors.SW_ETH_TRADE_REQUIRES_ESCROW);
}
if (userTradeData1.tradeType == TradeType.Hold) {
require(userTradeData1.tokenStandard == Standard.ERC20 || userTradeData1.tokenStandard == Standard.ERC1400, Errors.SW_TOKEN_STANDARD_NOT_SUPPORTED);
require(userTradeData1.tokenId != bytes32(0), Errors.SW_NO_HOLDID_GIVEN);
}
if (userTradeData2.tradeType == TradeType.Hold) {
require(userTradeData2.tokenStandard == Standard.ERC20 || userTradeData2.tokenStandard == Standard.ERC1400, Errors.SW_TOKEN_STANDARD_NOT_SUPPORTED);
require(userTradeData2.tokenId != bytes32(0), Errors.SW_NO_HOLDID_GIVEN);
}
if(_ownedContract) {
require(_isTradeExecuter[executer], Errors.SW_TRADE_EXECUTER_NOT_ALLOWED);
}
require(holder1 != address(0), Errors.ZERO_ADDRESS_NOT_ALLOWED);
_index++;
uint256 _expirationDate = (expirationDate > block.timestamp) ? expirationDate : (block.timestamp + SECONDS_IN_MONTH);
_trades[_index] = Trade({
holder1: holder1,
holder2: holder2,
executer: executer,
expirationDate: _expirationDate,
settlementDate: settlementDate,
userTradeData1: userTradeData1,
userTradeData2: userTradeData2,
state: State.Pending
});
}
/**
* @dev Accept a given trade (+ potentially escrow tokens).
* @param index Index of the trade to be accepted.
*/
function acceptTrade(uint256 index, bytes32 preimage) external payable {
_acceptTrade(index, _msgSender(), msg.value, 0, preimage);
}
/**
* @dev Accept a given trade (+ potentially escrow tokens).
* @param index Index of the trade to be accepted.
* @param sender Message sender
* @param ethValue Value sent (only used for ETH)
* @param erc1400TokenValue Value sent (only used for ERC1400)
*/
function _acceptTrade(uint256 index, address sender, uint256 ethValue, uint256 erc1400TokenValue, bytes32 preimage) internal {
Trade storage trade = _trades[index];
require(trade.state == State.Pending, Errors.SW_TRADE_NOT_PENDING);
address recipientHolder;
if(sender == trade.holder1) {
recipientHolder = trade.holder2;
} else if(sender == trade.holder2) {
recipientHolder = trade.holder1;
} else if(trade.holder2 == address(0)) {
trade.holder2 = sender;
recipientHolder = trade.holder1;
} else {
revert(Errors.SW_ONLY_REGISTERED_HOLDERS);
}
UserTradeData memory selectedUserTradeData = (sender == trade.holder1) ? trade.userTradeData1 : trade.userTradeData2;
require(!selectedUserTradeData.accepted, Errors.SW_TRADE_ALREADY_ACCEPTED);
if(selectedUserTradeData.tradeType == TradeType.Escrow) {
if(selectedUserTradeData.tokenStandard == Standard.ETH) {
require(ethValue == selectedUserTradeData.tokenValue, Errors.SW_ETH_AMOUNT_INCORRECT);
} else if(selectedUserTradeData.tokenStandard == Standard.ERC20) {
IERC20(selectedUserTradeData.tokenAddress).transferFrom(sender, address(this), selectedUserTradeData.tokenValue);
} else if(selectedUserTradeData.tokenStandard == Standard.ERC721) {
IERC721(selectedUserTradeData.tokenAddress).transferFrom(sender, address(this), uint256(selectedUserTradeData.tokenId));
} else if((selectedUserTradeData.tokenStandard == Standard.ERC1400) && erc1400TokenValue == 0){
IERC1400(selectedUserTradeData.tokenAddress).operatorTransferByPartition(selectedUserTradeData.tokenId, sender, address(this), selectedUserTradeData.tokenValue, abi.encodePacked(BYPASS_ACTION_FLAG), abi.encodePacked(BYPASS_ACTION_FLAG));
} else if((selectedUserTradeData.tokenStandard == Standard.ERC1400) && erc1400TokenValue != 0){
require(erc1400TokenValue == selectedUserTradeData.tokenValue, Errors.SW_TOKEN_AMOUNT_INCORRECT);
}
} else if (selectedUserTradeData.tradeType == TradeType.Hold) {
require(_holdExists(sender, recipientHolder, selectedUserTradeData), Errors.SW_HOLD_DOESNT_EXIST);
} else { // trade.tradeType == TradeType.Allowance
require(_allowanceIsProvided(sender, selectedUserTradeData), Errors.SW_ALLOWANCE_NOT_GIVEN);
}
if(sender == trade.holder1) {
trade.userTradeData1.accepted = true;
} else {
trade.userTradeData2.accepted = true;
}
bool settlementDatePassed = block.timestamp >= trade.settlementDate;
bool tradeApproved = getTradeApprovalStatus(index);
//Execute both holds of a trade if the following conditions are met
//* There is no executer set. Only the executer should execute transactions if one is defined
//* Both trade types are holds
//* The trade is approved. Token controllers must pre-approve this trade. This is also true if the token has no token controllers
//* If both holds exist according to _holdExists
//* If the current block timestamp is after the settlement date
if (settlementDatePassed && trade.executer == address(0) && trade.userTradeData1.tradeType == TradeType.Hold && trade.userTradeData2.tradeType == TradeType.Hold && tradeApproved) {
//we know selectedUserTradeData has a hold that exists, so check the other one
UserTradeData memory otherUserTradeData = (sender == trade.holder1) ? trade.userTradeData2 : trade.userTradeData1;
if (_holdExists(recipientHolder, sender, otherUserTradeData)) {
//If both holds exist, then mark both sides of trade as accepted
//Next if will execute trade
trade.userTradeData1.accepted = true;
trade.userTradeData2.accepted = true;
}
}
if(
trade.executer == address(0) && getTradeAcceptanceStatus(index) && tradeApproved && settlementDatePassed) {
_executeTrade(index, preimage);
}
}
/**
* @dev Verify if a trade has been accepted by the token holders.
*
* The trade needs to be accepted by both parties (token holders) before it gets executed.
*
* @param index Index of the trade to be accepted.
*/
function getTradeAcceptanceStatus(uint256 index) public view returns(bool) {
Trade storage trade = _trades[index];
if(trade.state == State.Pending) {
if(trade.userTradeData1.tradeType == TradeType.Allowance && !_allowanceIsProvided(trade.holder1, trade.userTradeData1)) {
return false;
}
if(trade.userTradeData2.tradeType == TradeType.Allowance && !_allowanceIsProvided(trade.holder2, trade.userTradeData2)) {
return false;
}
}
return(trade.userTradeData1.accepted && trade.userTradeData2.accepted);
}
/**
* @dev Verify if a token allowance has been provided in token smart contract.
*
* @param sender Address of the sender.
* @param userTradeData Encoded pack of variables for the token (address, amount, id/partition, standard, accepted, approved).
*/
function _allowanceIsProvided(address sender, UserTradeData memory userTradeData) internal view returns(bool) {
address tokenAddress = userTradeData.tokenAddress;
uint256 tokenValue = userTradeData.tokenValue;
bytes32 tokenId = userTradeData.tokenId;
Standard tokenStandard = userTradeData.tokenStandard;
if(tokenStandard == Standard.ERC20) {
return(IERC20(tokenAddress).allowance(sender, address(this)) >= tokenValue);
} else if(tokenStandard == Standard.ERC721) {
return(IERC721(tokenAddress).getApproved(uint256(tokenId)) == address(this));
} else if(tokenStandard == Standard.ERC1400){
return(IERC1400(tokenAddress).allowanceByPartition(tokenId, sender, address(this)) >= tokenValue);
}
return true;
}
function approveTrade(uint256 index, bool approved) external {
approveTradeWithPreimage(index, approved, 0);
}
/**
* @dev Approve a trade (if the tokens involved in the trade are controlled)
*
* This function can only be called by a token controller of one of the tokens involved in the trade.
*
* Indeed, when a token smart contract is controlled by an owner, the owner can decide to open the
* secondary market by:
* - Allowlisting the Swaps smart contract
* - Setting "token controllers" in the Swaps smart contract, in order to approve all the trades made with his token
*
* @param index Index of the trade to be executed.
* @param approved 'true' if trade is approved, 'false' if not.
*/
function approveTradeWithPreimage(uint256 index, bool approved, bytes32 preimage) public {
Trade storage trade = _trades[index];
require(trade.state == State.Pending, Errors.SW_TRADE_ALREADY_ACCEPTED);
require(_isTokenController[trade.userTradeData1.tokenAddress][_msgSender()] || _isTokenController[trade.userTradeData2.tokenAddress][_msgSender()], Errors.SW_SENDER_NOT_TOKEN_CONTROLLER);
if(_isTokenController[trade.userTradeData1.tokenAddress][_msgSender()]) {
trade.userTradeData1.approved = approved;
}
if(_isTokenController[trade.userTradeData2.tokenAddress][_msgSender()]) {
trade.userTradeData2.approved = approved;
}
if(trade.executer == address(0) && getTradeAcceptanceStatus(index) && getTradeApprovalStatus(index)) {
_executeTrade(index, preimage);
}
}
/**
* @dev Verify if a trade has been approved by the token controllers.
*
* In case a given token has token controllers, those need to validate the trade before it gets executed.
*
* @param index Index of the trade to be approved.
*/
function getTradeApprovalStatus(uint256 index) public view returns(bool) {
Trade storage trade = _trades[index];
if(_tokenControllers[trade.userTradeData1.tokenAddress].length != 0 && !trade.userTradeData1.approved) {
return false;
}
if(_tokenControllers[trade.userTradeData2.tokenAddress].length != 0 && !trade.userTradeData2.approved) {
return false;
}
return true;
}
function executeTrade(uint256 index) external {
executeTradeWithPreimage(index, 0);
}
/**
* @dev Execute a trade in the Swaps contract if possible (e.g. if tokens have been esccrowed, in case it is required).
*
* This function can only be called by the executer specified at trade creation.
* If no executer is specified, the trade can be launched by anyone.
*
* @param index Index of the trade to be executed.
*/
function executeTradeWithPreimage(uint256 index, bytes32 preimage) public {
Trade storage trade = _trades[index];
require(trade.state == State.Pending, Errors.SW_TRADE_NOT_PENDING);
if(trade.executer != address(0)) {
require(_msgSender() == trade.executer, Errors.SW_SENDER_NOT_EXECUTER);
}
require(block.timestamp >= trade.settlementDate, Errors.SW_BEFORE_SETTLEMENT_DATE);
require(getTradeAcceptanceStatus(index), Errors.SW_TRADE_NOT_FULLY_ACCEPTED);
require(getTradeApprovalStatus(index), Errors.SW_TRADE_NOT_FULLY_APPROVED);
_executeTrade(index, preimage);
}
/**
* @dev Execute a trade in the Swaps contract if possible (e.g. if tokens have been esccrowed, in case it is required).
* @param index Index of the trade to be executed.
*/
function _executeTrade(uint256 index, bytes32 preimage) internal {
Trade storage trade = _trades[index];
uint256 price = getPrice(index);
uint256 tokenValue1 = trade.userTradeData1.tokenValue;
uint256 tokenValue2 = trade.userTradeData2.tokenValue;
if(price == tokenValue2) {
_transferUsersTokens(index, Holder.Holder1, tokenValue1, false, preimage);
_transferUsersTokens(index, Holder.Holder2, tokenValue2, false, preimage);
} else {
//Holds cannot move a specific amount of tokens
//So require that if the price is less than the value
//that the trade is not a hold trade
require(price <= tokenValue2 && trade.userTradeData2.tradeType != TradeType.Hold, Errors.SW_PRICE_HIGHER_THAN_AMOUNT);
_transferUsersTokens(index, Holder.Holder1, tokenValue1, false, preimage);
_transferUsersTokens(index, Holder.Holder2, price, false, preimage);
if(trade.userTradeData2.tradeType == TradeType.Escrow) {
_transferUsersTokens(index, Holder.Holder2, tokenValue2 - price, true, preimage);
}
}
trade.state = State.Executed;
}
function forceTrade(uint256 index) external {
forceTradeWithPreimage(index, 0);
}
/**
* @dev Force a trade execution in the Swaps contract by transferring tokens back to their target recipients.
* @param index Index of the trade to be forced.
*/
function forceTradeWithPreimage(uint256 index, bytes32 preimage) public {
Trade storage trade = _trades[index];
require(trade.state == State.Pending, Errors.SW_TRADE_NOT_PENDING);
address tokenAddress1 = trade.userTradeData1.tokenAddress;
uint256 tokenValue1 = trade.userTradeData1.tokenValue;
bool accepted1 = trade.userTradeData1.accepted;
address tokenAddress2 = trade.userTradeData2.tokenAddress;
uint256 tokenValue2 = trade.userTradeData2.tokenValue;
bool accepted2 = trade.userTradeData2.accepted;
require(!(accepted1 && accepted2), Errors.SW_EXECUTE_TRADE_POSSIBLE);
require(_tokenControllers[tokenAddress1].length == 0 && _tokenControllers[tokenAddress2].length == 0, "Trade can not be forced if tokens have controllers");
if(trade.executer != address(0)) {
require(_msgSender() == trade.executer, Errors.SW_ONLY_EXECUTER_CAN_FORCE_TRADE);
} else if(accepted1) {
require(_msgSender() == trade.holder1, Errors.SW_SENDER_CANT_FORCE_TRADE);
} else if(accepted2) {
require(_msgSender() == trade.holder2, Errors.SW_SENDER_CANT_FORCE_TRADE);
} else {
revert(Errors.SW_FORCE_TRADE_NOT_POSSIBLE_NO_TOKENS);
}
if(accepted1) {
_transferUsersTokens(index, Holder.Holder1, tokenValue1, false, preimage);
}
if(accepted2) {
_transferUsersTokens(index, Holder.Holder2, tokenValue2, false, preimage);
}
trade.state = State.Forced;
}
/**
* @dev Cancel a trade execution in the Swaps contract by transferring tokens back to their initial owners.
* @param index Index of the trade to be cancelled.
*/
function cancelTrade(uint256 index) external {
Trade storage trade = _trades[index];
require(trade.state == State.Pending, Errors.SW_TRADE_NOT_PENDING);
uint256 tokenValue1 = trade.userTradeData1.tokenValue;
bool accepted1 = trade.userTradeData1.accepted;
uint256 tokenValue2 = trade.userTradeData2.tokenValue;
bool accepted2 = trade.userTradeData2.accepted;
if(accepted1 && accepted2) {
require(_msgSender() == trade.executer || (block.timestamp >= trade.expirationDate && (_msgSender() == trade.holder1 || _msgSender() == trade.holder2) ), Errors.SW_SENDER_CANT_CANCEL_TRADE_0);
if(trade.userTradeData1.tradeType == TradeType.Escrow) {
_transferUsersTokens(index, Holder.Holder1, tokenValue1, true, bytes32(0));
}
if(trade.userTradeData2.tradeType == TradeType.Escrow) {
_transferUsersTokens(index, Holder.Holder2, tokenValue2, true, bytes32(0));
}
} else if(accepted1) {
require(_msgSender() == trade.executer || (block.timestamp >= trade.expirationDate && _msgSender() == trade.holder1), Errors.SW_SENDER_CANT_CANCEL_TRADE_1);
if(trade.userTradeData1.tradeType == TradeType.Escrow) {
_transferUsersTokens(index, Holder.Holder1, tokenValue1, true, bytes32(0));
}
} else if(accepted2) {
require(_msgSender() == trade.executer || (block.timestamp >= trade.expirationDate && _msgSender() == trade.holder2), Errors.SW_SENDER_CANT_CANCEL_TRADE_2);
if(trade.userTradeData2.tradeType == TradeType.Escrow) {
_transferUsersTokens(index, Holder.Holder2, tokenValue2, true, bytes32(0));
}
} else {
require(_msgSender() == trade.executer || _msgSender() == trade.holder1 || _msgSender() == trade.holder2, Errors.SW_SENDER_CANT_CANCEL_TRADE_3);
}
trade.state = State.Cancelled;
}
function _transferUsersTokens(uint256 index, Holder holder, uint256 value, bool revertTransfer, bytes32 preimage) internal {
Trade storage trade = _trades[index];
UserTradeData memory senderUserTradeData = (holder == Holder.Holder1) ? trade.userTradeData1 : trade.userTradeData2;
TradeType tokenTradeType = senderUserTradeData.tradeType;
if (tokenTradeType == TradeType.Hold) {
_executeHoldOnUsersTokens(index, holder, value, revertTransfer, preimage);
} else {
_executeTransferOnUsersTokens(index, holder, value, revertTransfer);
}
}
function _executeHoldOnUsersTokens(uint256 index, Holder holder, uint256, bool, bytes32 preimage) internal {
Trade storage trade = _trades[index];
address sender = (holder == Holder.Holder1) ? trade.holder1 : trade.holder2;
address recipient = (holder == Holder.Holder1) ? trade.holder2 : trade.holder1;
UserTradeData memory senderUserTradeData = (holder == Holder.Holder1) ? trade.userTradeData1 : trade.userTradeData2;
require(block.timestamp <= trade.expirationDate, Errors.SW_TRADE_EXPIRED);
address tokenAddress = senderUserTradeData.tokenAddress;
bytes32 tokenId = senderUserTradeData.tokenId;
Standard tokenStandard = senderUserTradeData.tokenStandard;
require(tokenStandard == Standard.ERC20 || tokenStandard == Standard.ERC1400, Errors.SW_TOKEN_STANDARD_NOT_SUPPORTED);
require(_holdExists(sender, recipient, senderUserTradeData), Errors.SW_HOLD_DOESNT_EXIST);
_executeHold(tokenAddress, tokenId, tokenStandard, preimage, recipient);
}
/**
* @dev Internal function to transfer tokens to their recipient by taking the token standard into account.
* @param index Index of the trade the token transfer is execcuted for.
* @param holder Sender of the tokens (currently owning the tokens).
* @param value Amount of tokens to send.
* @param revertTransfer If set to true + trade has been accepted, tokens need to be sent back to their initial owners instead of sent to the target recipient.
*/
function _executeTransferOnUsersTokens(uint256 index, Holder holder, uint256 value, bool revertTransfer) internal {
Trade storage trade = _trades[index];
UserTradeData storage senderUserTradeData = (holder == Holder.Holder1) ? trade.userTradeData1 : trade.userTradeData2;
UserTradeData storage recipientUserTradeData = (holder == Holder.Holder1) ? trade.userTradeData2 : trade.userTradeData1;
address sender = (holder == Holder.Holder1) ? trade.holder1 : trade.holder2;
address recipient = recipientUserTradeData.receiver;
if (recipient == address(0)) {
recipient = (holder == Holder.Holder1) ? trade.holder2 : trade.holder1;
}
address tokenAddress = senderUserTradeData.tokenAddress;
bytes32 tokenId = senderUserTradeData.tokenId;
Standard tokenStandard = senderUserTradeData.tokenStandard;
address currentHolder = sender;
if(senderUserTradeData.tradeType == TradeType.Escrow) {
currentHolder = address(this);
}
if(revertTransfer) {
recipient = sender;
} else {
require(block.timestamp <= trade.expirationDate, Errors.SW_TRADE_EXPIRED);
}
if(tokenStandard == Standard.ETH) {
address payable payableRecipient = payable(recipient);
payableRecipient.transfer(value);
} else if(tokenStandard == Standard.ERC20) {
if(currentHolder == address(this)) {
IERC20(tokenAddress).transfer(recipient, value);
} else {
IERC20(tokenAddress).transferFrom(currentHolder, recipient, value);
}
} else if(tokenStandard == Standard.ERC721) {
IERC721(tokenAddress).transferFrom(currentHolder, recipient, uint256(tokenId));
} else if(tokenStandard == Standard.ERC1400) {
IERC1400(tokenAddress).operatorTransferByPartition(tokenId, currentHolder, recipient, value, "", "");
}
}
function _executeHold(
address token,
bytes32 tokenHoldId,
Standard tokenStandard,
bytes32 preimage,
address tokenRecipient
) internal {
// Token 1
if (tokenStandard == Standard.ERC20) {
require(token != address(0), Errors.ZERO_ADDRESS_NOT_ALLOWED);
IERC20HoldableToken(token).executeHold(tokenHoldId, preimage);
} else if (tokenStandard == Standard.ERC1400) {
require(token != address(0), Errors.ZERO_ADDRESS_NOT_ALLOWED);
address tokenExtension = interfaceAddr(token, ERC1400_TOKENS_VALIDATOR);
require(
tokenExtension != address(0),
Errors.SW_HOLD_TOKEN_EXTENSION_MISSING
);
uint256 holdValue;
(,,,,holdValue,,,,) = IHoldableERC1400TokenExtension(tokenExtension).retrieveHoldData(token, tokenHoldId);
IHoldableERC1400TokenExtension(tokenExtension).executeHold(
token,
tokenHoldId,
holdValue,
preimage
);
} else {
revert(Errors.SW_TOKEN_STANDARD_NOT_SUPPORTED);
}
emit ExecutedHold(
token,
tokenHoldId,
preimage,
tokenRecipient
);
}
function _holdExists(address sender, address recipient, UserTradeData memory userTradeData) internal view returns(bool) {
address tokenAddress = userTradeData.tokenAddress;
bytes32 holdId = userTradeData.tokenId;
Standard tokenStandard = userTradeData.tokenStandard;
if(tokenStandard == Standard.ERC1400) {
address tokenExtension = interfaceAddr(tokenAddress, ERC1400_TOKENS_VALIDATOR);
require(
tokenExtension != address(0),
Errors.SW_HOLD_TOKEN_EXTENSION_MISSING
);
HoldStatusCode holdStatus;
address holdSender;
address holdRecipient;
uint256 holdValue;
address notary;
bytes32 secretHash;
(,holdSender,holdRecipient,notary,holdValue,,secretHash,,holdStatus) = IHoldableERC1400TokenExtension(tokenExtension).retrieveHoldData(tokenAddress, holdId);
return holdStatus == HoldStatusCode.Ordered && holdValue == userTradeData.tokenValue && (holdSender == sender || holdSender == address(0)) && holdRecipient == recipient && (secretHash != bytes32(0) || notary == address(this));
} else if (tokenStandard == Standard.ERC20) {
ERC20HoldData memory data = IERC20HoldableToken(tokenAddress).retrieveHoldData(holdId);
return (data.sender == sender || data.sender == address(0)) && data.recipient == recipient && data.amount == userTradeData.tokenValue && data.status == HoldStatusCode.Ordered && (data.secretHash != bytes32(0) || data.notary == address(this));
} else {
revert(Errors.SW_TOKEN_INCORRECT_STANDARD);
}
}
/**
* @dev Indicate whether or not the Swaps contract can receive the tokens or not.
*
* By convention, the 32 first bytes of a token transfer to the Swaps smart contract contain a flag.
*
* - When tokens are transferred to Swaps contract to propose a new trade. The 'data' field starts with the
* following flag: 0xcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
* In this case the data structure is the the following:
* <tradeFlag (32 bytes)><recipient address (32 bytes)><executer address (32 bytes)><expiration date (32 bytes)><requested token data (4 * 32 bytes)>
*
* - When tokens are transferred to Swaps contract to accept an existing trade. The 'data' field starts with the
* following flag: 0xdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd
* In this case the data structure is the the following:
* <tradeFlag (32 bytes)><request index (32 bytes)>
*
* If the 'data' doesn't start with one of those flags, the Swaps contract won't accept the token transfer.
*
* @param data Information attached to the Swaps transfer.
* @param operatorData Information attached to the Swaps transfer, by the operator.
* @return 'true' if the Swaps contract can receive the tokens, 'false' if not.
*/
function _canReceive(bytes memory data, bytes memory operatorData) internal pure returns(bool) {
if(operatorData.length == 0) { // The reason for this check is to avoid a certificate gets interpreted as a flag by mistake
return false;
}
bytes32 flag = _getTradeFlag(data);
if(data.length == 320 && flag == TRADE_PROPOSAL_FLAG) {
return true;
} else if ((data.length == 64 || data.length == 96) && flag == TRADE_ACCEPTANCE_FLAG) {
return true;
} else if (data.length == 32 && flag == BYPASS_ACTION_FLAG) {
return true;
} else {
return false;
}
}
/**
* @dev Retrieve the trade flag from the 'data' field.
*
* By convention, the 32 first bytes of a token transfer to the Swaps smart contract contain a flag.
* - When tokens are transferred to Swaps contract to propose a new trade. The 'data' field starts with the
* following flag: 0xcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
* - When tokens are transferred to Swaps contract to accept an existing trade. The 'data' field starts with the
* following flag: 0xdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd
*
* @param data Concatenated information about the trade proposal.
* @return flag Trade flag.
*/
function _getTradeFlag(bytes memory data) internal pure returns(bytes32 flag) {
assembly {
flag:= mload(add(data, 32))
}
}
/**
* By convention, when tokens are transferred to Swaps contract to propose a new trade, the 'data' of a token transfer has the following structure:
* <tradeFlag (32 bytes)><recipient address (32 bytes)><executer address (32 bytes)><expiration date (32 bytes)><requested token data (5 * 32 bytes)>
*
* The first 32 bytes are the flag 0xcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
*
* The next 32 bytes contain the trade recipient address (or the zero address if the recipient is not chosen).
*
* The next 32 bytes contain the trade executer address (or zero if the executer is not chosen).
*
* The next 32 bytes contain the trade expiration date (or zero if the expiration date is not chosen).
*
* The next 32 bytes contain the trade requested token address (or the zero address if the recipient is not chosen).
* The next 32 bytes contain the trade requested token amount.
* The next 32 bytes contain the trade requested token id/partition (used when token standard is ERC721 or ERC1400).
* The next 32 bytes contain the trade requested token standard (OffChain, ERC20, ERC721, ERC1400, ETH).
* The next 32 bytes contain a boolean precising wether trade has been accepted by token holder or not.
* The next 32 bytes contain a boolean precising wether trade has been approved by token controller or not.
*
* Example input for recipient address '0xb5747835141b46f7C472393B31F8F5A57F74A44f', expiration date '1576348418',
* trade executer address '0x32F54098916ceb5f57a117dA9554175Fe25611bA', requested token address '0xC6F0410A667a5BEA528d6bc9efBe10270089Bb11',
* requested token amount '5', requested token id/partition '37252', and requested token type 'ERC1400', accepted and approved:
* 0xcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc000000000000000000000000b5747835141b46f7C472393B31F8F5A57F74A44f
* 000000000000000000000000000000000000000000000000000000157634841800000000000000000000000032F54098916ceb5f57a117dA9554175Fe25611bA
* 000000000000000000000000C6F0410A667a5BEA528d6bc9efBe10270089Bb110000000000000000000000000000000000000000000000000000000000000005
* 000000000000000000000000000000000000000000000000000000000037252000000000000000000000000000000000000000000000000000000000000002
* 000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000001
*/
/**
* @dev Retrieve the tokenData from the 'data' field.
*
* @param data Concatenated information about the trade proposal.
* @return tokenData Trade token data < 1: address > < 2: amount > < 3: id/partition > < 4: standard > < 5: accepted > < 6: approved >.
*/
function _getTradeTokenData(bytes memory data) internal pure returns(UserTradeData memory tokenData) {
address tokenAddress;
uint256 tokenAmount;
bytes32 tokenId;
Standard tokenStandard;
TradeType tradeType;
assembly {
tokenAddress:= mload(add(data, 192))
tokenAmount:= mload(add(data, 224))
tokenId:= mload(add(data, 256))
tokenStandard:= mload(add(data, 288))
tradeType:= mload(add(data, 320))
}
tokenData = UserTradeData(
tokenAddress,
tokenAmount,
tokenId,
tokenStandard,
false,
false,
tradeType,
address(0) //TODO Should this be included in data?
);
}
/**
* @dev Retrieve the trade index from the 'data' field.
*
* By convention, when tokens are transferred to Swaps contract to accept an existing trade, the 'data' of a token transfer has the following structure:
* <tradeFlag (32 bytes)><index uint256 (32 bytes)>
*
* The first 32 bytes are the flag 0xdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd
*
* The next 32 bytes contain the trade index.
*
* Example input for trade index #2985:
* 0xdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd0000000000000000000000000000000000000000000000000000000000002985
*
* @param data Concatenated information about the trade validation.
* @return index Trade index.
*/
/**************************** TRADE EXECUTERS *******************************/
/**
* @dev Renounce ownership of the contract.
*/
function renounceOwnership() public override onlyOwner {
Ownable.renounceOwnership();
_ownedContract = false;
}
/**
* @dev Get the list of trade executers as defined by the Swaps contract.
* @return List of addresses of all the trade executers.
*/
function tradeExecuters() external view returns (address[] memory) {
return _tradeExecuters;
}
/**
* @dev Set list of trade executers for the Swaps contract.
* @param operators Trade executers addresses.
*/
function setTradeExecuters(address[] calldata operators) external onlyOwner {
require(_ownedContract, Errors.NO_CONTRACT_OWNER);
_setTradeExecuters(operators);
}
/**
* @dev Set list of trade executers for the Swaps contract.
* @param operators Trade executers addresses.
*/
function _setTradeExecuters(address[] memory operators) internal {
for (uint i = 0; i<_tradeExecuters.length; i++){
_isTradeExecuter[_tradeExecuters[i]] = false;
}
for (uint j = 0; j<operators.length; j++){
_isTradeExecuter[operators[j]] = true;
}
_tradeExecuters = operators;
}
/************************** TOKEN CONTROLLERS *******************************/
/**
* @dev Get the list of token controllers for a given token.
* @param tokenAddress Token address.
* @return List of addresses of all the token controllers for a given token.
*/
function tokenControllers(address tokenAddress) external view returns (address[] memory) {
return _tokenControllers[tokenAddress];
}
/**
* @dev Set list of token controllers for a given token.
* @param tokenAddress Token address.
* @param operators Operators addresses.
*/
function setTokenControllers(address tokenAddress, address[] calldata operators) external onlyTokenController(tokenAddress) {
for (uint i = 0; i<_tokenControllers[tokenAddress].length; i++){
_isTokenController[tokenAddress][_tokenControllers[tokenAddress][i]] = false;
}
for (uint j = 0; j<operators.length; j++){
_isTokenController[tokenAddress][operators[j]] = true;
}
_tokenControllers[tokenAddress] = operators;
}
/************************** TOKEN PRICE ORACLES *******************************/
/**
* @dev Get the list of price oracles for a given token.
* @param tokenAddress Token address.
* @return List of addresses of all the price oracles for a given token.
*/
function priceOracles(address tokenAddress) external view returns (address[] memory) {
return _priceOracles[tokenAddress];
}
/**
* @dev Set list of price oracles for a given token.
* @param tokenAddress Token address.
* @param oracles Oracles addresses.
*/
function setPriceOracles(address tokenAddress, address[] calldata oracles) external onlyPriceOracle(tokenAddress) {
for (uint i = 0; i<_priceOracles[tokenAddress].length; i++){
_isPriceOracle[tokenAddress][_priceOracles[tokenAddress][i]] = false;
}
for (uint j = 0; j<oracles.length; j++){
_isPriceOracle[tokenAddress][oracles[j]] = true;
}
_priceOracles[tokenAddress] = oracles;
}
/**
* @dev Check if address is oracle of a given token.
* @param tokenAddress Token address.
* @param oracle Oracle address.
* @return 'true' if the address is oracle of the given token.
*/
function _checkPriceOracle(address tokenAddress, address oracle) internal view returns(bool) {
return(_isPriceOracle[tokenAddress][oracle] || oracle == Ownable(tokenAddress).owner());
}
/****************************** Swaps PRICES *********************************/
/**
* @dev Get price of the token.
* @param tokenAddress1 Address of the token to be priced.
* @param tokenAddress2 Address of the token to pay for token1.
*/
function getPriceOwnership(address tokenAddress1, address tokenAddress2) external view returns(bool) {
return _priceOwnership[tokenAddress1][tokenAddress2];
}
/**
* @dev Take ownership for setting the price of a token.
* @param tokenAddress1 Address of the token to be priced.
* @param tokenAddress2 Address of the token to pay for token1.
*/
function setPriceOwnership(address tokenAddress1, address tokenAddress2, bool priceOwnership) external onlyPriceOracle(tokenAddress1) {
_priceOwnership[tokenAddress1][tokenAddress2] = priceOwnership;
}
/**
* @dev Get date after which the token price can potentially be set by an oracle (0 if price can not be set by an oracle).
* @param tokenAddress Token address.
*/
function variablePriceStartDate(address tokenAddress) external view returns(uint256) {
return _variablePriceStartDate[tokenAddress];
}
/**
* @dev Set date after which the token price can potentially be set by an oracle (0 if price can not be set by an oracle).
* @param tokenAddress Token address.
* @param startDate Date after which token price can potentially be set by an oracle (0 if price can not be set by an oracle).
*/
function setVariablePriceStartDate(address tokenAddress, uint256 startDate) external onlyPriceOracle(tokenAddress) {
require((startDate > block.timestamp + SECONDS_IN_WEEK) || startDate == 0, Errors.SW_START_DATE_MUST_BE_ONE_WEEK_BEFORE);
_variablePriceStartDate[tokenAddress] = startDate;
}
/**
* @dev Get price of the token.
* @param tokenAddress1 Address of the token to be priced.
* @param tokenAddress2 Address of the token to pay for token1.
* @param tokenId1 ID/partition of the token1 (set to 0 bytes32 if price is set for all IDs/partitions).
* @param tokenId1 ID/partition of the token2 (set to 0 bytes32 if price is set for all IDs/partitions).
*/
function getTokenPrice(address tokenAddress1, address tokenAddress2, bytes32 tokenId1, bytes32 tokenId2) external view returns(uint256) {
return _tokenUnitPricesByPartition[tokenAddress1][tokenAddress2][tokenId1][tokenId2];
}
/**
* @dev Set price of a token.
* @param tokenAddress1 Address of the token to be priced.
* @param tokenAddress2 Address of the token to pay for token1.
* @param tokenId1 ID/partition of the token1 (set to 0 bytes32 if price is set for all IDs/partitions).
* @param tokenId2 ID/partition of the token2 (set to 0 bytes32 if price is set for all IDs/partitions).
* @param newPrice New price of the token.
*/
function setTokenPrice(address tokenAddress1, address tokenAddress2, bytes32 tokenId1, bytes32 tokenId2, uint256 newPrice) external {
require(!(_priceOwnership[tokenAddress1][tokenAddress2] && _priceOwnership[tokenAddress2][tokenAddress1]), Errors.SW_COMPETITION_ON_PRICE_OWNERSHIP);
if(_priceOwnership[tokenAddress1][tokenAddress2]) {
require(_checkPriceOracle(tokenAddress1, _msgSender()), Errors.SW_PRICE_SETTER_NOT_TOKEN_ORACLE_1);
} else if(_priceOwnership[tokenAddress2][tokenAddress1]) {
require(_checkPriceOracle(tokenAddress2, _msgSender()), Errors.SW_PRICE_SETTER_NOT_TOKEN_ORACLE_2);
} else {
revert(Errors.SW_NO_PRICE_OWNERSHIP);
}
_tokenUnitPricesByPartition[tokenAddress1][tokenAddress2][tokenId1][tokenId2] = newPrice;
}
/**
* @dev Get amount of token2 to pay to acquire the token1.
* @param index Index of the Swaps request.
*/
function getPrice(uint256 index) public view returns(uint256) {
Trade storage trade = _trades[index];
address tokenAddress1 = trade.userTradeData1.tokenAddress;
uint256 tokenValue1 = trade.userTradeData1.tokenValue;
bytes32 tokenId1 = trade.userTradeData1.tokenId;
address tokenAddress2 = trade.userTradeData2.tokenAddress;
uint256 tokenValue2 = trade.userTradeData2.tokenValue;
bytes32 tokenId2 = trade.userTradeData2.tokenId;
require(!(_priceOwnership[tokenAddress1][tokenAddress2] && _priceOwnership[tokenAddress2][tokenAddress1]), Errors.SW_COMPETITION_ON_PRICE_OWNERSHIP);
if(_variablePriceStartDate[tokenAddress1] == 0 || block.timestamp < _variablePriceStartDate[tokenAddress1]) {
return tokenValue2;
}
if(_priceOwnership[tokenAddress1][tokenAddress2] || _priceOwnership[tokenAddress2][tokenAddress1]) {
if(_tokenUnitPricesByPartition[tokenAddress1][tokenAddress2][tokenId1][tokenId2] != 0) {
return tokenValue1 * (_tokenUnitPricesByPartition[tokenAddress1][tokenAddress2][tokenId1][tokenId2]);
} else if(_tokenUnitPricesByPartition[tokenAddress2][tokenAddress1][tokenId2][tokenId1] != 0) {
return tokenValue1 / (_tokenUnitPricesByPartition[tokenAddress2][tokenAddress1][tokenId2][tokenId1]);
} else if(_tokenUnitPricesByPartition[tokenAddress1][tokenAddress2][tokenId1][ALL_PARTITIONS] != 0) {
return tokenValue1 * (_tokenUnitPricesByPartition[tokenAddress1][tokenAddress2][tokenId1][ALL_PARTITIONS]);
} else if(_tokenUnitPricesByPartition[tokenAddress2][tokenAddress1][ALL_PARTITIONS][tokenId1] != 0) {
return tokenValue1 / (_tokenUnitPricesByPartition[tokenAddress2][tokenAddress1][ALL_PARTITIONS][tokenId1]);
} else if(_tokenUnitPricesByPartition[tokenAddress1][tokenAddress2][ALL_PARTITIONS][tokenId2] != 0) {
return tokenValue1 * (_tokenUnitPricesByPartition[tokenAddress1][tokenAddress2][ALL_PARTITIONS][tokenId2]);
} else if(_tokenUnitPricesByPartition[tokenAddress2][tokenAddress1][tokenId2][ALL_PARTITIONS] != 0) {
return tokenValue1 / (_tokenUnitPricesByPartition[tokenAddress2][tokenAddress1][tokenId2][ALL_PARTITIONS]);
} else if(_tokenUnitPricesByPartition[tokenAddress1][tokenAddress2][ALL_PARTITIONS][ALL_PARTITIONS] != 0) {
return tokenValue1 * (_tokenUnitPricesByPartition[tokenAddress1][tokenAddress2][ALL_PARTITIONS][ALL_PARTITIONS]);
} else if(_tokenUnitPricesByPartition[tokenAddress2][tokenAddress1][ALL_PARTITIONS][ALL_PARTITIONS] != 0) {
return tokenValue1 / (_tokenUnitPricesByPartition[tokenAddress2][tokenAddress1][ALL_PARTITIONS][ALL_PARTITIONS]);
} else {
return tokenValue2;
}
} else {
return tokenValue2;
}
}
/**************************** VIEW FUNCTIONS *******************************/
/**
* @dev Get the trade.
* @param index Index of the trade.
* @return Trade.
*/
function getTrade(uint256 index) external view returns(Trade memory) {
Trade storage trade = _trades[index];
return trade;
}
/**
* @dev Get the total number of requests in the Swaps contract.
* @return Total number of requests in the Swaps contract.
*/
function getNbTrades() external view returns(uint256) {
return _index;
}
}
|
* [ERC1400TokensRecipient INTERFACE (2/2)] @dev Hook function executed when tokens are sent to the Swaps contract. [USED FOR ERC1400 TOKENS ONLY] @param partition Name of the partition. @param from Token holder. @param to Token recipient. @param value Number of tokens to transfer. @param data Information attached to the token transfer. @param operatorData Information attached to the Swaps transfer, by the operator./This field is optionalIf the data's length does not include the preimagethen return an empty preimagecanReceive accepts both data lengths
|
function tokensReceived(bytes calldata, bytes32 partition, address, address from, address to, uint value, bytes memory data, bytes calldata operatorData) external override {
bytes32 flag = _getTradeFlag(data);
if(flag == TRADE_PROPOSAL_FLAG) {
address recipient;
address executor;
uint256 expirationDate;
uint256 settlementDate;
assembly {
recipient:= mload(add(data, 64))
executor:= mload(add(data, 96))
expirationDate:= mload(add(data, 128))
settlementDate:= mload(add(data, 160))
}
UserTradeData memory _tokenData2 = _getTradeTokenData(data);
_requestTrade(
from,
recipient,
executor,
expirationDate,
settlementDate,
_tradeData1,
_tokenData2
);
uint256 index;
bytes32 preimage = bytes32(0);
assembly {
index:= mload(add(data, 64))
}
if (data.length == 96) {
assembly {
preimage:= mload(add(data, 96))
}
}
Trade storage trade = _trades[index];
UserTradeData memory selectedUserTradeData = (from == trade.holder1) ? trade.userTradeData1 : trade.userTradeData2;
require(_msgSender() == selectedUserTradeData.tokenAddress, Errors.SW_WRONG_TOKEN_SENT);
require(partition == selectedUserTradeData.tokenId, Errors.SW_TOKENS_IN_WRONG_PARTITION);
require(Standard.ERC1400 == selectedUserTradeData.tokenStandard, Errors.SW_TOKEN_INCORRECT_STANDARD);
_acceptTrade(index, from, 0, value, preimage);
}
}
| 12,733,432 |
[
1,
63,
654,
39,
3461,
713,
5157,
18241,
11391,
11300,
261,
22,
19,
22,
25887,
225,
13725,
445,
7120,
1347,
2430,
854,
3271,
358,
326,
5434,
6679,
6835,
18,
306,
20093,
12108,
4232,
39,
3461,
713,
14275,
55,
20747,
65,
225,
3590,
1770,
434,
326,
3590,
18,
225,
628,
3155,
10438,
18,
225,
358,
3155,
8027,
18,
225,
460,
3588,
434,
2430,
358,
7412,
18,
225,
501,
15353,
7495,
358,
326,
1147,
7412,
18,
225,
3726,
751,
15353,
7495,
358,
326,
5434,
6679,
7412,
16,
635,
326,
3726,
18,
19,
2503,
652,
353,
3129,
2047,
326,
501,
1807,
769,
1552,
486,
2341,
326,
675,
15374,
546,
275,
327,
392,
1008,
675,
2730,
4169,
11323,
8104,
3937,
501,
10917,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
225,
445,
2430,
8872,
12,
3890,
745,
892,
16,
1731,
1578,
3590,
16,
1758,
16,
1758,
628,
16,
1758,
358,
16,
2254,
460,
16,
1731,
3778,
501,
16,
1731,
745,
892,
3726,
751,
13,
3903,
3849,
288,
203,
203,
203,
565,
1731,
1578,
2982,
273,
389,
588,
22583,
4678,
12,
892,
1769,
203,
565,
309,
12,
6420,
422,
21492,
1639,
67,
3373,
7057,
1013,
67,
9651,
13,
288,
203,
1377,
1758,
8027,
31,
203,
1377,
1758,
6601,
31,
203,
1377,
2254,
5034,
7686,
1626,
31,
203,
1377,
2254,
5034,
26319,
806,
1626,
31,
203,
1377,
19931,
288,
203,
3639,
8027,
30,
33,
312,
945,
12,
1289,
12,
892,
16,
5178,
3719,
203,
3639,
6601,
30,
33,
312,
945,
12,
1289,
12,
892,
16,
19332,
3719,
203,
3639,
7686,
1626,
30,
33,
312,
945,
12,
1289,
12,
892,
16,
8038,
3719,
203,
3639,
26319,
806,
1626,
30,
33,
312,
945,
12,
1289,
12,
892,
16,
25430,
3719,
203,
1377,
289,
203,
1377,
2177,
22583,
751,
3778,
389,
2316,
751,
22,
273,
389,
588,
22583,
1345,
751,
12,
892,
1769,
203,
203,
1377,
389,
2293,
22583,
12,
203,
3639,
628,
16,
203,
3639,
8027,
16,
203,
3639,
6601,
16,
203,
3639,
7686,
1626,
16,
203,
3639,
26319,
806,
1626,
16,
203,
3639,
389,
20077,
751,
21,
16,
203,
3639,
389,
2316,
751,
22,
203,
1377,
11272,
203,
203,
1377,
2254,
5034,
770,
31,
203,
1377,
1731,
1578,
675,
2730,
273,
1731,
1578,
12,
20,
1769,
203,
1377,
19931,
288,
203,
3639,
770,
30,
33,
312,
945,
2
] |
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma experimental ABIEncoderV2;
import "./IPermissions.sol";
import "../token/IRusd.sol";
/// @title Core Interface
/// @author Ring Protocol
interface ICore is IPermissions {
// ----------- Events -----------
event RusdUpdate(address indexed _rusd);
event RingUpdate(address indexed _ring);
event GenesisGroupUpdate(address indexed _genesisGroup);
event RingAllocation(address indexed _to, uint256 _amount);
event GenesisPeriodComplete(uint256 _timestamp);
// ----------- Governor only state changing api -----------
function init() external;
// ----------- Governor only state changing api -----------
function setRusd(address token) external;
function setRing(address token) external;
function setGenesisGroup(address _genesisGroup) external;
function allocateRing(address to, uint256 amount) external;
// ----------- Genesis Group only state changing api -----------
function completeGenesisGroup() external;
// ----------- Getters -----------
function rusd() external view returns (IRusd);
function ring() external view returns (IERC20);
function genesisGroup() external view returns (address);
function hasGenesisGroupCompleted() external view returns (bool);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma experimental ABIEncoderV2;
/// @title Permissions interface
/// @author Ring Protocol
interface IPermissions {
// ----------- Governor only state changing api -----------
function createRole(bytes32 role, bytes32 adminRole) external;
function grantMinter(address minter) external;
function grantBurner(address burner) external;
function grantPCVController(address pcvController) external;
function grantGovernor(address governor) external;
function grantGuardian(address guardian) external;
function revokeMinter(address minter) external;
function revokeBurner(address burner) external;
function revokePCVController(address pcvController) external;
function revokeGovernor(address governor) external;
function revokeGuardian(address guardian) external;
// ----------- Revoker only state changing api -----------
function revokeOverride(bytes32 role, address account) external;
// ----------- Getters -----------
function isBurner(address _address) external view returns (bool);
function isMinter(address _address) external view returns (bool);
function isGovernor(address _address) external view returns (bool);
function isGuardian(address _address) external view returns (bool);
function isPCVController(address _address) external view returns (bool);
}
/*
Copyright 2019 dYdX Trading Inc.
Copyright 2020 Empty Set Squad <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
import "./SafeMathCopy.sol";
/**
* @title Decimal
* @author dYdX
*
* Library that defines a fixed-point number with 18 decimal places.
*/
library Decimal {
using SafeMathCopy for uint256;
// ============ Constants ============
uint256 private constant BASE = 10**18;
// ============ Structs ============
struct D256 {
uint256 value;
}
// ============ Static Functions ============
function zero()
internal
pure
returns (D256 memory)
{
return D256({ value: 0 });
}
function one()
internal
pure
returns (D256 memory)
{
return D256({ value: BASE });
}
function from(
uint256 a
)
internal
pure
returns (D256 memory)
{
return D256({ value: a.mul(BASE) });
}
function ratio(
uint256 a,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(a, BASE, b) });
}
// ============ Self Functions ============
function add(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.add(b.mul(BASE)) });
}
function sub(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.mul(BASE)) });
}
function sub(
D256 memory self,
uint256 b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.mul(BASE), reason) });
}
function mul(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.mul(b) });
}
function div(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.div(b) });
}
function pow(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
if (b == 0) {
return from(1);
}
D256 memory temp = D256({ value: self.value });
for (uint256 i = 1; i < b; i++) {
temp = mul(temp, self);
}
return temp;
}
function add(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.add(b.value) });
}
function sub(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.value) });
}
function sub(
D256 memory self,
D256 memory b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.value, reason) });
}
function mul(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(self.value, b.value, BASE) });
}
function div(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(self.value, BASE, b.value) });
}
function equals(D256 memory self, D256 memory b) internal pure returns (bool) {
return self.value == b.value;
}
function greaterThan(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) == 2;
}
function lessThan(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) == 0;
}
function greaterThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) > 0;
}
function lessThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) < 2;
}
function isZero(D256 memory self) internal pure returns (bool) {
return self.value == 0;
}
function asUint256(D256 memory self) internal pure returns (uint256) {
return self.value.div(BASE);
}
// ============ Core Methods ============
function getPartial(
uint256 target,
uint256 numerator,
uint256 denominator
)
private
pure
returns (uint256)
{
return target.mul(numerator).div(denominator);
}
function compareTo(
D256 memory a,
D256 memory b
)
private
pure
returns (uint256)
{
if (a.value == b.value) {
return 1;
}
return a.value > b.value ? 2 : 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathCopy { // To avoid namespace collision between openzeppelin safemath and uniswap safemath
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma experimental ABIEncoderV2;
import "../external/Decimal.sol";
/// @title generic oracle interface for Ring Protocol
/// @author Ring Protocol
interface IOracle {
// ----------- Getters -----------
function read() external view returns (Decimal.D256 memory, bool);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
import "@uniswap/lib/contracts/libraries/TransferHelper.sol";
import "@uniswap/v3-core/contracts/libraries/SafeCast.sol";
import "./IUniswapPCVController.sol";
import "../refs/UniRef.sol";
import "../utils/Timed.sol";
import "../utils/Roots.sol";
/// @title a IUniswapPCVController implementation for ERC20
/// @author Ring Protocol
contract ERC20UniswapPCVController is IUniswapPCVController, UniRef, Timed {
using Decimal for Decimal.D256;
using SafeMathCopy for uint128;
using SafeMathCopy for uint256;
using SafeCast for uint256;
using Roots for uint256;
uint256 public override reweightWithdrawBPs = 9900;
uint256 internal _reweightDuration = 4 hours;
uint256 internal constant BASIS_POINTS_GRANULARITY = 10000;
uint24 public override fee = 500;
/// @notice returns the linked pcv deposit contract
IPCVDeposit public override pcvDeposit;
/// @notice gets the RUSD reward incentive for reweighting
uint256 public override reweightIncentiveAmount;
Decimal.D256 internal _minDistanceForReweight;
/// @notice ERC20UniswapPCVController constructor
/// @param _core Ring Core for reference
/// @param _pcvDeposit PCV Deposit to reweight
/// @param _oracle oracle for reference
/// @param _incentiveAmount amount of RUSD for triggering a reweight
/// @param _minDistanceForReweightBPs minimum distance from peg to reweight in basis points
/// @param _pool Uniswap V3 pool contract to reweight
/// @param _nft Uniswap V3 position manager to reference
/// @param _router Uniswap Router
constructor(
address _core,
address _pcvDeposit,
address _oracle,
uint256 _incentiveAmount,
uint256 _minDistanceForReweightBPs,
address _pool,
address _nft,
address _router
) UniRef(_core, _pool, _nft, _router, _oracle) Timed(_reweightDuration) {
pcvDeposit = IPCVDeposit(_pcvDeposit);
reweightIncentiveAmount = _incentiveAmount;
_minDistanceForReweight = Decimal.ratio(
_minDistanceForReweightBPs,
BASIS_POINTS_GRANULARITY
);
// start timer
_initTimed();
}
/// @notice reweights the linked PCV Deposit to the peg price. Needs to be reweight eligible
function reweight() external override whenNotPaused {
require(
reweightEligible(),
"ERC20UniswapPCVController: Not passed reweight time or not at min distance"
);
_reweight();
_incentivize();
}
/// @notice reinvest the fee income into the linked PCV Deposit.
function reinvest() external override whenNotPaused {
pcvDeposit.collect();
pcvDeposit.deposit();
emit Reinvest(msg.sender);
}
/// @notice reweights regardless of eligibility
function forceReweight() external override onlyGuardianOrGovernor {
_reweight();
}
/// @notice sets the target PCV Deposit address
function setPCVDeposit(address _pcvDeposit) external override onlyGovernor {
pcvDeposit = IPCVDeposit(_pcvDeposit);
emit PCVDepositUpdate(_pcvDeposit);
}
/// @notice sets the target PCV Deposit parameters
function setPCVDepositParameters(uint24 _fee, int24 _tickLower, int24 _tickUpper) external override onlyGovernor {
pcvDeposit.withdraw(address(pcvDeposit), pcvDeposit.totalLiquidity());
pcvDeposit.burnAndReset(_fee, _tickLower, _tickUpper);
pcvDeposit.deposit();
emit PCVDepositParametersUpdate(address(pcvDeposit), fee, _tickLower, _tickUpper);
}
/// @notice sets the reweight incentive amount
function setReweightIncentive(uint256 amount)
external
override
onlyGovernor
{
reweightIncentiveAmount = amount;
emit ReweightIncentiveUpdate(amount);
}
/// @notice sets the reweight withdrawal BPs
function setReweightWithdrawBPs(uint256 _reweightWithdrawBPs)
external
override
onlyGovernor
{
require(_reweightWithdrawBPs <= BASIS_POINTS_GRANULARITY, "ERC20UniswapPCVController: withdraw percent too high");
reweightWithdrawBPs = _reweightWithdrawBPs;
emit ReweightWithdrawBPsUpdate(_reweightWithdrawBPs);
}
/// @notice sets the reweight min distance in basis points
function setReweightMinDistance(uint256 basisPoints)
external
override
onlyGovernor
{
_minDistanceForReweight = Decimal.ratio(
basisPoints,
BASIS_POINTS_GRANULARITY
);
emit ReweightMinDistanceUpdate(basisPoints);
}
/// @notice sets the reweight duration
function setDuration(uint256 _duration)
external
override
onlyGovernor
{
_setDuration(_duration);
}
/// @notice sets the fee
function setFee(uint24 _fee) external override onlyGovernor {
fee = _fee;
emit SwapFeeUpdate(_fee);
}
/// @notice signal whether the reweight is available. Must have incentive parity and minimum distance from peg
function reweightEligible() public view override returns (bool) {
bool magnitude =
_getDistanceToPeg().greaterThan(_minDistanceForReweight);
// incentive parity is achieved after a certain time relative to distance from peg
bool time = isTimeEnded();
return magnitude && time;
}
/// @notice minimum distance as a percentage from the peg for a reweight to be eligible
function minDistanceForReweight()
external
view
override
returns (Decimal.D256 memory)
{
return _minDistanceForReweight;
}
function _incentivize() internal ifMinterSelf {
rusd().mint(msg.sender, reweightIncentiveAmount);
}
function _reweight() internal {
_withdraw();
_returnToPeg();
// resupply PCV at peg ratio
uint256 balance = IERC20(token()).balanceOf(address(this));
// transfer the entire pcv erc20 token balance to pcvDeposit, then run deposit
TransferHelper.safeTransfer(token(), address(pcvDeposit), balance);
pcvDeposit.deposit();
_burnRusdHeld();
// reset timer
_initTimed();
emit Reweight(msg.sender);
}
function _returnToPeg() internal {
Decimal.D256 memory _peg = peg();
require(
_isBelowPeg(_peg),
"ERC20UniswapPCVController: already at or above peg"
);
_swapErc20();
}
function _swapErc20() internal {
uint256 balance = IERC20(token()).balanceOf(address(this));
if (balance != 0) {
uint256 endOfTime = uint256(-1);
address _token = token();
address _rusd = address(rusd());
Decimal.D256 memory _peg = (_token < _rusd) ? peg() : invert(peg());
uint160 priceLimit = _peg.mul(2**96).asUint256().mul(2**96).sqrt().toUint160();
router.exactInputSingle(
ISwapRouter.ExactInputSingleParams({
tokenIn: _token,
tokenOut: _rusd,
fee: fee,
recipient: address(this),
deadline: endOfTime,
amountIn: balance,
amountOutMinimum: 0,
sqrtPriceLimitX96: priceLimit
})
);
}
}
function _withdraw() internal {
// Only withdraw a portion to prevent rounding errors on Uni LP dust
uint256 value =
pcvDeposit.totalLiquidity().mul(reweightWithdrawBPs) /
BASIS_POINTS_GRANULARITY;
require(value > 0, "ERC20UniswapPCVController: No liquidity to withdraw");
pcvDeposit.withdraw(address(this), value);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title a PCV Deposit interface
/// @author Ring Protocol
interface IPCVDeposit {
// ----------- Events -----------
event Deposit(address indexed _from, uint256 _amount);
event Collect(address indexed _from, uint256 _amount0, uint256 _amount1);
event Withdrawal(
address indexed _caller,
address indexed _to,
uint256 _amount
);
// ----------- State changing api -----------
function deposit() external payable;
function collect() external returns (uint256 amount0, uint256 amount1);
// ----------- PCV Controller only state changing api -----------
function withdraw(address to, uint256 amount) external;
function burnAndReset(uint24 _fee, int24 _tickLower, int24 _tickUpper) external;
// ----------- Getters -----------
function fee() external view returns (uint24);
function tickLower() external view returns (int24);
function tickUpper() external view returns (int24);
function totalLiquidity() external view returns (uint128);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma experimental ABIEncoderV2;
import "./IPCVDeposit.sol";
import "../external/Decimal.sol";
/// @title a Uniswap PCV Controller interface
/// @author Ring Protocol
interface IUniswapPCVController {
// ----------- Events -----------
event Reweight(address indexed _caller);
event Reinvest(address indexed _caller);
event PCVDepositUpdate(address indexed _pcvDeposit);
event PCVDepositParametersUpdate(address indexed pcvDeposit, uint24 fee, int24 tickLower, int24 tickUpper);
event ReweightIncentiveUpdate(uint256 _amount);
event ReweightMinDistanceUpdate(uint256 _basisPoints);
event ReweightWithdrawBPsUpdate(uint256 _reweightWithdrawBPs);
event SwapFeeUpdate(uint24 _fee);
// ----------- State changing API -----------
function reweight() external;
function reinvest() external;
// ----------- Governor only state changing API -----------
function forceReweight() external;
function setPCVDeposit(address _pcvDeposit) external;
function setPCVDepositParameters(uint24 _fee, int24 _tickLower, int24 _tickUpper) external;
function setDuration(uint256 _duration) external;
function setReweightIncentive(uint256 amount) external;
function setReweightMinDistance(uint256 basisPoints) external;
function setReweightWithdrawBPs(uint256 _reweightWithdrawBPs) external;
function setFee(uint24 _fee) external;
// ----------- Getters -----------
function fee() external view returns (uint24);
function pcvDeposit() external view returns (IPCVDeposit);
function reweightIncentiveAmount() external view returns (uint256);
function reweightEligible() external view returns (bool);
function reweightWithdrawBPs() external view returns (uint256);
function minDistanceForReweight()
external
view
returns (Decimal.D256 memory);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
import "./ICoreRef.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts/utils/Address.sol";
/// @title A Reference to Core
/// @author Ring Protocol
/// @notice defines some modifiers and utilities around interacting with Core
abstract contract CoreRef is ICoreRef, Pausable {
ICore private _core;
/// @notice CoreRef constructor
/// @param newCore Ring Core to reference
constructor(address newCore) {
_core = ICore(newCore);
}
modifier ifMinterSelf() {
if (_core.isMinter(address(this))) {
_;
}
}
modifier ifBurnerSelf() {
if (_core.isBurner(address(this))) {
_;
}
}
modifier onlyMinter() {
require(_core.isMinter(msg.sender), "CoreRef: Caller is not a minter");
_;
}
modifier onlyBurner() {
require(_core.isBurner(msg.sender), "CoreRef: Caller is not a burner");
_;
}
modifier onlyPCVController() {
require(
_core.isPCVController(msg.sender),
"CoreRef: Caller is not a PCV controller"
);
_;
}
modifier onlyGovernor() {
require(
_core.isGovernor(msg.sender),
"CoreRef: Caller is not a governor"
);
_;
}
modifier onlyGuardianOrGovernor() {
require(
_core.isGovernor(msg.sender) ||
_core.isGuardian(msg.sender),
"CoreRef: Caller is not a guardian or governor"
);
_;
}
modifier onlyRusd() {
require(msg.sender == address(rusd()), "CoreRef: Caller is not RUSD");
_;
}
modifier onlyGenesisGroup() {
require(
msg.sender == _core.genesisGroup(),
"CoreRef: Caller is not GenesisGroup"
);
_;
}
modifier nonContract() {
require(!Address.isContract(msg.sender), "CoreRef: Caller is a contract");
_;
}
/// @notice set new Core reference address
/// @param _newCore the new core address
function setCore(address _newCore) external override onlyGovernor {
_core = ICore(_newCore);
emit CoreUpdate(_newCore);
}
/// @notice set pausable methods to paused
function pause() public override onlyGuardianOrGovernor {
_pause();
}
/// @notice set pausable methods to unpaused
function unpause() public override onlyGuardianOrGovernor {
_unpause();
}
/// @notice address of the Core contract referenced
/// @return ICore implementation address
function core() public view override returns (ICore) {
return _core;
}
/// @notice address of the Rusd contract referenced by Core
/// @return IRusd implementation address
function rusd() public view override returns (IRusd) {
return _core.rusd();
}
/// @notice address of the Ring contract referenced by Core
/// @return IERC20 implementation address
function ring() public view override returns (IERC20) {
return _core.ring();
}
/// @notice rusd balance of contract
/// @return rusd amount held
function rusdBalance() public view override returns (uint256) {
return rusd().balanceOf(address(this));
}
/// @notice ring balance of contract
/// @return ring amount held
function ringBalance() public view override returns (uint256) {
return ring().balanceOf(address(this));
}
function _burnRusdHeld() internal {
rusd().burn(rusdBalance());
}
function _mintRusd(uint256 amount) internal {
rusd().mint(address(this), amount);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma experimental ABIEncoderV2;
import "../core/ICore.sol";
/// @title CoreRef interface
/// @author Ring Protocol
interface ICoreRef {
// ----------- Events -----------
event CoreUpdate(address indexed _core);
// ----------- Governor only state changing api -----------
function setCore(address _newCore) external;
function pause() external;
function unpause() external;
// ----------- Getters -----------
function core() external view returns (ICore);
function rusd() external view returns (IRusd);
function ring() external view returns (IERC20);
function rusdBalance() external view returns (uint256);
function ringBalance() external view returns (uint256);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma experimental ABIEncoderV2;
import "../oracle/IOracle.sol";
/// @title OracleRef interface
/// @author Ring Protocol
interface IOracleRef {
// ----------- Events -----------
event OracleUpdate(address indexed _oracle);
// ----------- Governor only state changing API -----------
function setOracle(address _oracle) external;
// ----------- Getters -----------
function oracle() external view returns (IOracle);
function peg() external view returns (Decimal.D256 memory);
function invert(Decimal.D256 calldata price)
external
pure
returns (Decimal.D256 memory);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma experimental ABIEncoderV2;
import "@uniswap/v3-periphery/contracts/interfaces/INonfungiblePositionManager.sol";
import "@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol";
import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
/// @title UniRef interface
/// @author Ring Protocol
interface IUniRef {
// ----------- Events -----------
event PoolUpdate(address indexed _pool);
// ----------- Governor only state changing api -----------
function setPool(address _pool) external;
// ----------- Getters -----------
function nft() external view returns (INonfungiblePositionManager);
function router() external view returns (ISwapRouter);
function pool() external view returns (IUniswapV3Pool);
function tokenId() external view returns (uint256);
function token() external view returns (address);
function liquidityOwned() external view returns (uint128);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
import "./IOracleRef.sol";
import "./CoreRef.sol";
/// @title Reference to an Oracle
/// @author Ring Protocol
/// @notice defines some utilities around interacting with the referenced oracle
abstract contract OracleRef is IOracleRef, CoreRef {
using Decimal for Decimal.D256;
/// @notice the oracle reference by the contract
IOracle public override oracle;
/// @notice OracleRef constructor
/// @param _core Ring Core to reference
/// @param _oracle oracle to reference
constructor(address _core, address _oracle) CoreRef(_core) {
_setOracle(_oracle);
}
/// @notice sets the referenced oracle
/// @param _oracle the new oracle to reference
function setOracle(address _oracle) external override onlyGovernor {
_setOracle(_oracle);
}
/// @notice invert a peg price
/// @param price the peg price to invert
/// @return the inverted peg as a Decimal
/// @dev the inverted peg would be X per RUSD
function invert(Decimal.D256 memory price)
public
pure
override
returns (Decimal.D256 memory)
{
return Decimal.one().div(price);
}
/// @notice the peg price of the referenced oracle
/// @return the peg as a Decimal
/// @dev the peg is defined as RUSD per X with X being ETH, dollars, etc
function peg() public view override returns (Decimal.D256 memory) {
(Decimal.D256 memory _peg, bool valid) = oracle.read();
require(valid, "OracleRef: oracle invalid");
return _peg;
}
function _setOracle(address _oracle) internal {
oracle = IOracle(_oracle);
emit OracleUpdate(_oracle);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
import "@uniswap/lib/contracts/libraries/TransferHelper.sol";
import "./OracleRef.sol";
import "./IUniRef.sol";
/// @title A Reference to Uniswap
/// @author Ring Protocol
/// @notice defines some modifiers and utilities around interacting with Uniswap
/// @dev the uniswap v3 pool should be RUSD and another asset
abstract contract UniRef is IUniRef, OracleRef {
using Decimal for Decimal.D256;
using SafeMathCopy for uint256;
using SafeMathCopy for uint160;
uint256 private constant FIXED_POINT_GRANULARITY = 2**96;
/// @notice the Uniswap V3 position manager
INonfungiblePositionManager public override nft;
/// @notice the Uniswap router contract
ISwapRouter public override router;
/// @notice the referenced Uniswap V3 pool contract
IUniswapV3Pool public override pool;
/// @notice the referenced Uniswap V3 pool position id
uint256 public override tokenId;
/// @notice UniRef constructor
/// @param _core Ring Core to reference
/// @param _pool Uniswap V3 pool to reference
/// @param _nft Uniswap V3 position manager to reference
/// @param _router Uniswap Router to reference
/// @param _oracle oracle to reference
constructor(
address _core,
address _pool,
address _nft,
address _router,
address _oracle
) OracleRef(_core, _oracle) {
_setupPool(_pool);
nft = INonfungiblePositionManager(_nft);
router = ISwapRouter(_router);
_approveTokenToRouter(address(rusd()));
_approveTokenToRouter(token());
_approveTokenToNFT(address(rusd()));
_approveTokenToNFT(token());
}
/// @notice set the new pool contract
/// @param _pool the new pool
/// @dev also approves the router for the new pool token and underlying token
function setPool(address _pool) external override onlyGovernor {
_setupPool(_pool);
_approveTokenToRouter(token());
_approveTokenToNFT(token());
}
/// @notice the address of the non-rusd underlying token
function token() public view override returns (address) {
address token0 = pool.token0();
if (address(rusd()) == token0) {
return pool.token1();
}
return token0;
}
/// @notice amount of pool liquidity owned by this contract
/// @return amount of liquidity
function liquidityOwned() public view override returns (uint128) {
(, , , , , , , uint128 liquidity, , , , ) = nft.positions(tokenId);
return liquidity;
}
/// @notice returns true if price is below the peg
/// @dev counterintuitively checks if peg < price because price is reported as RUSD per X
function _isBelowPeg(Decimal.D256 memory peg) internal view returns (bool) {
Decimal.D256 memory price = _getUniswapPrice();
return peg.lessThan(price);
}
/// @notice approves a token for the router
function _approveTokenToRouter(address _token) internal {
uint256 maxTokens = uint256(-1);
TransferHelper.safeApprove(_token, address(router), maxTokens);
}
/// @notice approves a token for the position manager
function _approveTokenToNFT(address _token) internal {
uint256 maxTokens = uint256(-1);
TransferHelper.safeApprove(_token, address(nft), maxTokens);
}
function _setupPool(address _pool) internal {
pool = IUniswapV3Pool(_pool);
emit PoolUpdate(_pool);
}
/// @notice get uniswap price
/// @return price reported as Rusd per X
function _getUniswapPrice()
internal
view
returns (Decimal.D256 memory)
{
(uint160 sqrtPriceX96, , , , , , ) = pool.slot0();
if (token() < address(rusd())) {
return Decimal.ratio(sqrtPriceX96, FIXED_POINT_GRANULARITY).pow(2);
} else {
return Decimal.ratio(FIXED_POINT_GRANULARITY, sqrtPriceX96).pow(2);
}
}
/// @notice return current percent distance from peg
/// @dev will return Decimal.zero() if above peg
function _getDistanceToPeg()
internal
view
returns (Decimal.D256 memory distance)
{
Decimal.D256 memory price = _getUniswapPrice();
return _deviationBelowPeg(price, peg());
}
/// @notice get deviation from peg as a percent given price
/// @dev will return Decimal.zero() if above peg
function _deviationBelowPeg(
Decimal.D256 memory price,
Decimal.D256 memory peg
) internal pure returns (Decimal.D256 memory) {
// If price <= peg, then RUSD is more expensive and above peg
// In this case we can just return zero for deviation
if (price.lessThanOrEqualTo(peg)) {
return Decimal.zero();
}
Decimal.D256 memory delta = price.sub(peg, "Impossible underflow");
return delta.div(peg);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title RUSD stablecoin interface
/// @author Ring Protocol
interface IRusd is IERC20 {
// ----------- Events -----------
event Minting(
address indexed _to,
address indexed _minter,
uint256 _amount
);
event Burning(
address indexed _to,
address indexed _burner,
uint256 _amount
);
event IncentiveContractUpdate(
address indexed _incentiveContract
);
// ----------- State changing api -----------
function burn(uint256 amount) external;
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
// ----------- Burner only state changing api -----------
function burnFrom(address account, uint256 amount) external;
// ----------- Minter only state changing api -----------
function mint(address account, uint256 amount) external;
// ----------- Governor only state changing api -----------
function setIncentiveContract(address incentive) external;
// ----------- Getters -----------
function incentiveContract() external view returns (address);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
import "@uniswap/lib/contracts/libraries/Babylonian.sol";
library Roots {
// Newton's method https://en.wikipedia.org/wiki/Cube_root#Numerical_methods
function cubeRoot(uint256 y) internal pure returns (uint256 z) {
if (y > 7) {
z = y;
uint256 x = y / 3 + 1;
while (x < z) {
z = x;
x = (y / (x * x) + (2 * x)) / 3;
}
} else if (y != 0) {
z = 1;
}
}
function sqrt(uint256 y) internal pure returns (uint256) {
return Babylonian.sqrt(y);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
/// @title an abstract contract for timed events
/// @author Ring Protocol
abstract contract Timed {
/// @notice the start timestamp of the timed period
uint256 public startTime;
/// @notice the duration of the timed period
uint256 public duration;
event DurationUpdate(uint256 _duration);
event TimerReset(uint256 _startTime);
constructor(uint256 _duration) {
_setDuration(_duration);
}
modifier duringTime() {
require(isTimeStarted(), "Timed: time not started");
require(!isTimeEnded(), "Timed: time ended");
_;
}
modifier afterTime() {
require(isTimeEnded(), "Timed: time not ended");
_;
}
/// @notice return true if time period has ended
function isTimeEnded() public view returns (bool) {
return remainingTime() == 0;
}
/// @notice number of seconds remaining until time is up
/// @return remaining
function remainingTime() public view returns (uint256) {
return duration - timeSinceStart(); // duration always >= timeSinceStart which is on [0,d]
}
/// @notice number of seconds since contract was initialized
/// @return timestamp
/// @dev will be less than or equal to duration
function timeSinceStart() public view returns (uint256) {
if (!isTimeStarted()) {
return 0; // uninitialized
}
uint256 _duration = duration;
// solhint-disable-next-line not-rely-on-time
uint256 timePassed = block.timestamp - startTime; // block timestamp always >= startTime
return timePassed > _duration ? _duration : timePassed;
}
function isTimeStarted() public view returns (bool) {
return startTime != 0;
}
function _initTimed() internal {
// solhint-disable-next-line not-rely-on-time
startTime = block.timestamp;
// solhint-disable-next-line not-rely-on-time
emit TimerReset(block.timestamp);
}
function _setDuration(uint _duration) internal {
duration = _duration;
emit DurationUpdate(_duration);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.4.0;
// computes square roots using the babylonian method
// https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
library Babylonian {
function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
// else z = 0
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.6.0;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import './pool/IUniswapV3PoolImmutables.sol';
import './pool/IUniswapV3PoolState.sol';
import './pool/IUniswapV3PoolDerivedState.sol';
import './pool/IUniswapV3PoolActions.sol';
import './pool/IUniswapV3PoolOwnerActions.sol';
import './pool/IUniswapV3PoolEvents.sol';
/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
IUniswapV3PoolImmutables,
IUniswapV3PoolState,
IUniswapV3PoolDerivedState,
IUniswapV3PoolActions,
IUniswapV3PoolOwnerActions,
IUniswapV3PoolEvents
{
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
function initialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
/// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
/// with 0 amount{0,1} and sending the donation amount(s) from the callback
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
/// @notice Increase the maximum number of price and liquidity observations that this pool will store
/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
/// the input observationCardinalityNext.
/// @param observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
/// you must call it with secondsAgos = [3600, 0].
/// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
/// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
/// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
/// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
/// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
/// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
/// snapshot is taken and the second snapshot is taken.
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
/// @return tickCumulativeInside The snapshot of the tick accumulator for the range
/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
/// @return secondsInside The snapshot of seconds per liquidity for the range
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
view
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
/// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 sqrtPriceX96, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
/// @param owner The owner of the position for which fees are collected
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(
address indexed owner,
address recipient,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount0,
uint128 amount1
);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of price of the pool after the swap
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick
);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(
address indexed sender,
address indexed recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1
);
/// @notice Emitted by the pool for increases to the number of observations that can be stored
/// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
/// just before a mint/swap/burn.
/// @param observationCardinalityNextOld The previous value of the next observation cardinality
/// @param observationCardinalityNextNew The updated value of the next observation cardinality
event IncreaseObservationCardinalityNext(
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
/// @notice Emitted when the protocol fee is changed by the pool
/// @param feeProtocol0Old The previous value of the token0 protocol fee
/// @param feeProtocol1Old The previous value of the token1 protocol fee
/// @param feeProtocol0New The updated value of the token0 protocol fee
/// @param feeProtocol1New The updated value of the token1 protocol fee
event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
/// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
/// @param sender The address that collects the protocol fees
/// @param recipient The address that receives the collected protocol fees
/// @param amount0 The amount of token0 protocol fees that is withdrawn
/// @param amount0 The amount of token1 protocol fees that is withdrawn
event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
/// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
/// @notice Set the denominator of the protocol's % share of the fees
/// @param feeProtocol0 new protocol fee for token0 of the pool
/// @param feeProtocol1 new protocol fee for token1 of the pool
function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;
/// @notice Collect the protocol fee accrued to the pool
/// @param recipient The address to which collected protocol fees should be sent
/// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
/// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
/// @return amount0 The protocol fee collected in token0
/// @return amount1 The protocol fee collected in token1
function collectProtocol(
address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// observationIndex The index of the last oracle observation that was written,
/// observationCardinality The current maximum number of observations stored in the pool,
/// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal0X128() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal1X128() external view returns (uint256);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
function protocolFees() external view returns (uint128 token0, uint128 token1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks
function liquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
/// tick upper,
/// liquidityNet how much liquidity changes when the pool price crosses the tick,
/// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
/// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
/// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
/// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
/// secondsOutside the seconds spent on the other side of the tick from the current tick,
/// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
/// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
/// In addition, these values are only relative and must be used only in comparison to previous snapshots for
/// a specific position.
function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128,
int56 tickCumulativeOutside,
uint160 secondsPerLiquidityOutsideX128,
uint32 secondsOutside,
bool initialized
);
/// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
function tickBitmap(int16 wordPosition) external view returns (uint256);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return _liquidity The amount of liquidity in the position,
/// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(bytes32 key)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
/// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
/// Returns initialized whether the observation has been initialized and the values are safe to use
function observations(uint256 index)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
/// @notice Cast a uint256 to a uint160, revert on overflow
/// @param y The uint256 to be downcasted
/// @return z The downcasted integer, now type uint160
function toUint160(uint256 y) internal pure returns (uint160 z) {
require((z = uint160(y)) == y);
}
/// @notice Cast a int256 to a int128, revert on overflow or underflow
/// @param y The int256 to be downcasted
/// @return z The downcasted integer, now type int128
function toInt128(int256 y) internal pure returns (int128 z) {
require((z = int128(y)) == y);
}
/// @notice Cast a uint256 to a int256, revert on overflow
/// @param y The uint256 to be casted
/// @return z The casted integer, now type int256
function toInt256(uint256 y) internal pure returns (int256 z) {
require(y < 2**255);
z = int256(y);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
import '@openzeppelin/contracts/token/ERC721/IERC721.sol';
/// @title ERC721 with permit
/// @notice Extension to ERC721 that includes a permit function for signature based approvals
interface IERC721Permit is IERC721 {
/// @notice The permit typehash used in the permit signature
/// @return The typehash for the permit
function PERMIT_TYPEHASH() external pure returns (bytes32);
/// @notice The domain separator used in the permit signature
/// @return The domain seperator used in encoding of permit signature
function DOMAIN_SEPARATOR() external view returns (bytes32);
/// @notice Approve of a specific token ID for spending by spender via signature
/// @param spender The account that is being approved
/// @param tokenId The ID of the token that is being approved for spending
/// @param deadline The deadline timestamp by which the call must be mined for the approve to work
/// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
/// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
/// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
function permit(
address spender,
uint256 tokenId,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external payable;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
import '@openzeppelin/contracts/token/ERC721/IERC721Metadata.sol';
import '@openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol';
import './IPoolInitializer.sol';
import './IERC721Permit.sol';
import './IPeripheryPayments.sol';
import './IPeripheryImmutableState.sol';
import '../libraries/PoolAddress.sol';
/// @title Non-fungible token for positions
/// @notice Wraps Uniswap V3 positions in a non-fungible token interface which allows for them to be transferred
/// and authorized.
interface INonfungiblePositionManager is
IPoolInitializer,
IPeripheryPayments,
IPeripheryImmutableState,
IERC721Metadata,
IERC721Enumerable,
IERC721Permit
{
/// @notice Emitted when liquidity is increased for a position NFT
/// @dev Also emitted when a token is minted
/// @param tokenId The ID of the token for which liquidity was increased
/// @param liquidity The amount by which liquidity for the NFT position was increased
/// @param amount0 The amount of token0 that was paid for the increase in liquidity
/// @param amount1 The amount of token1 that was paid for the increase in liquidity
event IncreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
/// @notice Emitted when liquidity is decreased for a position NFT
/// @param tokenId The ID of the token for which liquidity was decreased
/// @param liquidity The amount by which liquidity for the NFT position was decreased
/// @param amount0 The amount of token0 that was accounted for the decrease in liquidity
/// @param amount1 The amount of token1 that was accounted for the decrease in liquidity
event DecreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
/// @notice Emitted when tokens are collected for a position NFT
/// @dev The amounts reported may not be exactly equivalent to the amounts transferred, due to rounding behavior
/// @param tokenId The ID of the token for which underlying tokens were collected
/// @param recipient The address of the account that received the collected tokens
/// @param amount0 The amount of token0 owed to the position that was collected
/// @param amount1 The amount of token1 owed to the position that was collected
event Collect(uint256 indexed tokenId, address recipient, uint256 amount0, uint256 amount1);
/// @notice Returns the position information associated with a given token ID.
/// @dev Throws if the token ID is not valid.
/// @param tokenId The ID of the token that represents the position
/// @return nonce The nonce for permits
/// @return operator The address that is approved for spending
/// @return token0 The address of the token0 for a specific pool
/// @return token1 The address of the token1 for a specific pool
/// @return fee The fee associated with the pool
/// @return tickLower The lower end of the tick range for the position
/// @return tickUpper The higher end of the tick range for the position
/// @return liquidity The liquidity of the position
/// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position
/// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position
/// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation
/// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation
function positions(uint256 tokenId)
external
view
returns (
uint96 nonce,
address operator,
address token0,
address token1,
uint24 fee,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
struct MintParams {
address token0;
address token1;
uint24 fee;
int24 tickLower;
int24 tickUpper;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
address recipient;
uint256 deadline;
}
/// @notice Creates a new position wrapped in a NFT
/// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized
/// a method does not exist, i.e. the pool is assumed to be initialized.
/// @param params The params necessary to mint a position, encoded as `MintParams` in calldata
/// @return tokenId The ID of the token that represents the minted position
/// @return liquidity The amount of liquidity for this position
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function mint(MintParams calldata params)
external
payable
returns (
uint256 tokenId,
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
struct IncreaseLiquidityParams {
uint256 tokenId;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender`
/// @param params tokenId The ID of the token for which liquidity is being increased,
/// amount0Desired The desired amount of token0 to be spent,
/// amount1Desired The desired amount of token1 to be spent,
/// amount0Min The minimum amount of token0 to spend, which serves as a slippage check,
/// amount1Min The minimum amount of token1 to spend, which serves as a slippage check,
/// deadline The time by which the transaction must be included to effect the change
/// @return liquidity The new liquidity amount as a result of the increase
/// @return amount0 The amount of token0 to acheive resulting liquidity
/// @return amount1 The amount of token1 to acheive resulting liquidity
function increaseLiquidity(IncreaseLiquidityParams calldata params)
external
payable
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
struct DecreaseLiquidityParams {
uint256 tokenId;
uint128 liquidity;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Decreases the amount of liquidity in a position and accounts it to the position
/// @param params tokenId The ID of the token for which liquidity is being decreased,
/// amount The amount by which liquidity will be decreased,
/// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity,
/// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity,
/// deadline The time by which the transaction must be included to effect the change
/// @return amount0 The amount of token0 accounted to the position's tokens owed
/// @return amount1 The amount of token1 accounted to the position's tokens owed
function decreaseLiquidity(DecreaseLiquidityParams calldata params)
external
payable
returns (uint256 amount0, uint256 amount1);
struct CollectParams {
uint256 tokenId;
address recipient;
uint128 amount0Max;
uint128 amount1Max;
}
/// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient
/// @param params tokenId The ID of the NFT for which tokens are being collected,
/// recipient The account that should receive the tokens,
/// amount0Max The maximum amount of token0 to collect,
/// amount1Max The maximum amount of token1 to collect
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1);
/// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens
/// must be collected first.
/// @param tokenId The ID of the token that is being burned
function burn(uint256 tokenId) external payable;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Immutable state
/// @notice Functions that return immutable state of the router
interface IPeripheryImmutableState {
/// @return Returns the address of the Uniswap V3 factory
function factory() external view returns (address);
/// @return Returns the address of WETH9
function WETH9() external view returns (address);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
/// @title Periphery Payments
/// @notice Functions to ease deposits and withdrawals of ETH
interface IPeripheryPayments {
/// @notice Unwraps the contract's WETH9 balance and sends it to recipient as ETH.
/// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users.
/// @param amountMinimum The minimum amount of WETH9 to unwrap
/// @param recipient The address receiving ETH
function unwrapWETH9(uint256 amountMinimum, address recipient) external payable;
/// @notice Refunds any ETH balance held by this contract to the `msg.sender`
/// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps
/// that use ether for the input amount
function refundETH() external payable;
/// @notice Transfers the full amount of a token held by this contract to recipient
/// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users
/// @param token The contract address of the token which will be transferred to `recipient`
/// @param amountMinimum The minimum amount of token required for a transfer
/// @param recipient The destination address of the token
function sweepToken(
address token,
uint256 amountMinimum,
address recipient
) external payable;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
/// @title Creates and initializes V3 Pools
/// @notice Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that
/// require the pool to exist.
interface IPoolInitializer {
/// @notice Creates a new pool if it does not exist, then initializes if not initialized
/// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool
/// @param token0 The contract address of token0 of the pool
/// @param token1 The contract address of token1 of the pool
/// @param fee The fee amount of the v3 pool for the specified token pair
/// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value
/// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary
function createAndInitializePoolIfNecessary(
address token0,
address token1,
uint24 fee,
uint160 sqrtPriceX96
) external payable returns (address pool);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol';
/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Uniswap V3
interface ISwapRouter is IUniswapV3SwapCallback {
struct ExactInputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another token
/// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
/// @return amountOut The amount of the received token
function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);
struct ExactInputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
/// @return amountOut The amount of the received token
function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);
struct ExactOutputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another token
/// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata
/// @return amountIn The amount of the input token
function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);
struct ExactOutputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata
/// @return amountIn The amount of the input token
function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Provides functions for deriving a pool address from the factory, tokens, and the fee
library PoolAddress {
bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54;
/// @notice The identifying key of the pool
struct PoolKey {
address token0;
address token1;
uint24 fee;
}
/// @notice Returns PoolKey: the ordered tokens with the matched fee levels
/// @param tokenA The first token of a pool, unsorted
/// @param tokenB The second token of a pool, unsorted
/// @param fee The fee level of the pool
/// @return Poolkey The pool details with ordered token0 and token1 assignments
function getPoolKey(
address tokenA,
address tokenB,
uint24 fee
) internal pure returns (PoolKey memory) {
if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA);
return PoolKey({token0: tokenA, token1: tokenB, fee: fee});
}
/// @notice Deterministically computes the pool address given the factory and PoolKey
/// @param factory The Uniswap V3 factory contract address
/// @param key The PoolKey
/// @return pool The contract address of the V3 pool
function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) {
require(key.token0 < key.token1);
pool = address(
uint256(
keccak256(
abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encode(key.token0, key.token1, key.fee)),
POOL_INIT_CODE_HASH
)
)
)
);
}
}
|
@notice approves a token for the router
|
function _approveTokenToRouter(address _token) internal {
uint256 maxTokens = uint256(-1);
TransferHelper.safeApprove(_token, address(router), maxTokens);
}
| 5,929,667 |
[
1,
12908,
3324,
279,
1147,
364,
326,
4633,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
12908,
537,
1345,
774,
8259,
12,
2867,
389,
2316,
13,
2713,
288,
203,
3639,
2254,
5034,
943,
5157,
273,
2254,
5034,
19236,
21,
1769,
203,
3639,
12279,
2276,
18,
4626,
12053,
537,
24899,
2316,
16,
1758,
12,
10717,
3631,
943,
5157,
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
] |
./partial_match/56/0x44A77bf493BC22bA5D150E418F9dF8d0eFAc5ccb/sources/ErntePair.sol
|
single check is sufficient
|
require(getPair[token0][token1] == address(0), 'Ernte: PAIR_EXISTS');
| 11,099,745 |
[
1,
7526,
866,
353,
18662,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2583,
12,
588,
4154,
63,
2316,
20,
6362,
2316,
21,
65,
422,
1758,
12,
20,
3631,
296,
29228,
496,
73,
30,
15662,
7937,
67,
21205,
8284,
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
] |
./full_match/43113/0xda9513Ec655bF38afD831f71F246824A7b096dE6/sources/Database.sol
|
application에 등록된 user 모음입니다.
|
mapping(address => user) userList;
| 7,157,889 |
[
1,
3685,
173,
250,
243,
225,
172,
246,
114,
172,
99,
256,
172,
243,
255,
729,
225,
172,
108,
106,
173,
256,
239,
173,
257,
232,
172,
238,
235,
172,
238,
102,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
202,
6770,
12,
2867,
516,
729,
13,
729,
682,
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
] |
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.7;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "./interfaces/IIdleCDOStrategy.sol";
import "./interfaces/IERC20Detailed.sol";
import "./interfaces/IIdleCDOTrancheRewards.sol";
import "./interfaces/IIdleCDO.sol";
import "./IdleCDOTrancheRewardsStorage.sol";
/// @author Idle Labs Inc.
/// @title IdleCDOTrancheRewards
/// @notice Contract used for staking specific tranche tokens and getting incentive rewards
/// This contract keeps the accounting of how many rewards each user is entitled to using 2 indexs:
/// a per-user index (`usersIndexes[user][reward]`) and a global index (`rewardsIndexes[reward]`)
/// The difference of those indexes
contract IdleCDOTrancheRewards is Initializable, PausableUpgradeable, OwnableUpgradeable, ReentrancyGuardUpgradeable, IIdleCDOTrancheRewards, IdleCDOTrancheRewardsStorage {
using SafeERC20Upgradeable for IERC20Detailed;
// Used to prevent initialization of the implementation contract
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
tranche = address(1);
}
/// @notice Initialize the contract
/// @param _trancheToken tranche address
/// @param _rewards rewards token array
/// @param _owner The owner of the contract
/// @param _idleCDO The CDO where the reward tokens come from
/// @param _governanceRecoveryFund address where rewards will be sent in case of transferToken call
/// @param _coolingPeriod number of blocks that needs to pass since last rewards deposit
/// before all rewards are unlocked. Rewards are unlocked linearly for `_coolingPeriod` blocks
function initialize(
address _trancheToken, address[] memory _rewards, address _owner,
address _idleCDO, address _governanceRecoveryFund, uint256 _coolingPeriod
) public initializer {
require(tranche == address(0), 'Initialized');
require(_owner != address(0) && _trancheToken != address(0) && _idleCDO != address(0) && _governanceRecoveryFund != address(0), "IS_0");
// Initialize inherited contracts
OwnableUpgradeable.__Ownable_init();
ReentrancyGuardUpgradeable.__ReentrancyGuard_init();
PausableUpgradeable.__Pausable_init();
// transfer ownership to owner
transferOwnership(_owner);
// set state variables
idleCDO = _idleCDO;
tranche = _trancheToken;
rewards = _rewards;
governanceRecoveryFund = _governanceRecoveryFund;
coolingPeriod = _coolingPeriod;
}
/// @notice Stake _amount of tranche token to receive rewards
/// @param _amount The amount of tranche tokens to stake
function stake(uint256 _amount) external whenNotPaused override {
_stake(msg.sender, msg.sender, _amount);
}
/// @notice Stake _amount of tranche token to receive rewards
/// used by IdleCDO to stake tranche tokens received as fees in an handy way
/// @param _user address of the user to stake for
/// @param _amount The amount of tranche tokens to stake
function stakeFor(address _user, uint256 _amount) external whenNotPaused override {
require(msg.sender == idleCDO, "!AUTH");
_stake(_user, msg.sender, _amount);
}
/// @notice Stake _amount of tranche token to receive rewards
/// @param _user address of the user to stake for
/// @param _payer address from which tranche tokens gets transferred
/// @param _amount The amount of tranche tokens to stake
function _stake(address _user, address _payer, uint256 _amount) internal {
if (_amount == 0) {
return;
}
// update user index for each reward, used to calculate the correct reward amount
// of rewards for each user
_updateUserIdx(_user, _amount);
// increase the staked amount associated with the user
usersStakes[_user] += _amount;
// increase the total staked amount counter
totalStaked += _amount;
// get _amount of `tranche` tokens from the payer
IERC20Detailed(tranche).safeTransferFrom(_payer, address(this), _amount);
}
/// @notice Unstake _amount of tranche tokens and redeem ALL accrued rewards
/// @dev if the contract is paused, unstaking any amount will cause the loss of all
/// accrued and unclaimed rewards so far
/// @param _amount The amount of tranche tokens to unstake
function unstake(uint256 _amount) external nonReentrant override {
if (_amount == 0) {
return;
}
if (paused()) {
// If the contract is paused, "unstake" will skip the claim of the rewards,
// and those rewards won't be claimable in the future.
address reward;
for (uint256 i = 0; i < rewards.length; i++) {
reward = rewards[i];
// set the user index equal to the global one, which means 0 rewards
usersIndexes[msg.sender][reward] = adjustedRewardIndex(reward);
}
} else {
// Claim all rewards accrued
_claim();
}
// if _amount is greater than usersStakes[msg.sender], the next line fails
usersStakes[msg.sender] -= _amount;
// update the total staked counter
totalStaked -= _amount;
// send funds to the user
IERC20Detailed(tranche).safeTransfer(msg.sender, _amount);
}
/// @notice Sends all the expected rewards to the msg.sender
/// @dev User index is reset
function claim() whenNotPaused nonReentrant external {
_claim();
}
/// @notice Claim all rewards, used by `claim` and `unstake`
function _claim() internal {
address[] memory _rewards = rewards;
for (uint256 i = 0; i < _rewards.length; i++) {
address reward = _rewards[i];
// get how much `reward` we should send to the user
uint256 amount = expectedUserReward(msg.sender, reward);
uint256 balance = IERC20Detailed(reward).balanceOf(address(this));
// Check that the amount is available in the contract
if (amount > balance) {
amount = balance;
}
// Set the user index equal to the global one, which means 0 rewards
usersIndexes[msg.sender][reward] = adjustedRewardIndex(reward);
// transfer the reward to the user
IERC20Detailed(reward).safeTransfer(msg.sender, amount);
}
}
/// @notice Calculates the expected rewards for a user
/// @param user The user address
/// @param reward The reward token address
/// @return The expected reward amount
function expectedUserReward(address user, address reward) public view returns (uint256) {
require(_includesAddress(rewards, reward), "!SUPPORTED");
// The amount of rewards for a specific reward token is given by the difference
// between the global index and the user's one multiplied by the user staked balance
// The rewards deposited are not unlocked right away, but linearly over `coolingPeriod`
// blocks so an adjusted global index is used.
// NOTE: stakes made when the coolingPeriod is not concluded won't receive any of those
// rewards (ie the index set for the user is the global, non adjusted, index)
uint256 _globalIdx = adjustedRewardIndex(reward);
uint256 _userIdx = usersIndexes[user][reward];
if (_userIdx > _globalIdx) {
return 0;
}
return ((_globalIdx - _userIdx) * usersStakes[user]) / ONE_TRANCHE_TOKEN;
}
/// @notice Calculates the adjusted global index for calculating rewards,
/// considering that rewards will be released over `coolingPeriod` blocks
/// @param _reward The reward token address
/// @return _index The adjusted global index
function adjustedRewardIndex(address _reward) public view returns (uint256 _index) {
uint256 _totalStaked = totalStaked;
// get number of rewards deposited in the last `depositReward` call
uint256 _lockedRewards = lockedRewards[_reward];
// get current global index, which considers all rewards
_index = rewardsIndexes[_reward];
if (_totalStaked > 0 && _lockedRewards > 0) {
// get blocks since last reward deposit
uint256 distance = block.number - lockedRewardsLastBlock[_reward];
if (distance < coolingPeriod) {
// if the cooling period has not passed, calculate the rewards that should
// still be locked
uint256 unlockedRewards = _lockedRewards * distance / coolingPeriod;
uint256 lockedRewards = _lockedRewards - unlockedRewards;
// and reduce the 'real' global index proportionally to the total amount staked
_index -= lockedRewards * ONE_TRANCHE_TOKEN / _totalStaked;
}
}
}
/// @notice Called by IdleCDO to deposit incentive rewards
/// @param _reward The rewards token address
/// @param _amount The amount to deposit
function depositReward(address _reward, uint256 _amount) external override {
require(msg.sender == idleCDO, "!AUTH");
require(_includesAddress(rewards, _reward), "!SUPPORTED");
// Get rewards from IdleCDO
IERC20Detailed(_reward).safeTransferFrom(msg.sender, address(this), _amount);
if (totalStaked > 0) {
// rewards are splitted among all stakers by increasing the global index
// proportionally for everyone (based on totalStaked)
// NOTE: for calculations `adjustedRewardIndex` is used instead, to release
// rewards linearly over `coolingPeriod` blocks
rewardsIndexes[_reward] += _amount * ONE_TRANCHE_TOKEN / totalStaked;
}
// save _amount of reward amount and block
lockedRewards[_reward] = _amount;
lockedRewardsLastBlock[_reward] = block.number;
}
/// @notice It sets the coolingPeriod that a user needs to wait since his last stake
/// before the unstake will be possible
/// @param _newCoolingPeriod The new cooling period
function setCoolingPeriod(uint256 _newCoolingPeriod) external onlyOwner {
coolingPeriod = _newCoolingPeriod;
}
/// @notice Update user index for each reward, based on the amount being staked
/// @param _user user who is staking
/// @param _amountToStake amount staked
function _updateUserIdx(address _user, uint256 _amountToStake) internal {
address[] memory _rewards = rewards;
uint256 userIndex;
address reward;
uint256 _currStake = usersStakes[_user];
for (uint256 i = 0; i < _rewards.length; i++) {
reward = _rewards[i];
if (_currStake == 0) {
// Set the user address equal to the global one which means 0 reward for the user
usersIndexes[_user][reward] = rewardsIndexes[reward];
} else {
userIndex = usersIndexes[_user][reward];
// Calculate the new user idx
// The user already staked something so he already have some accrued rewards
// which are: r = (rewardsIndexes - userIndex) * _currStake -> (see expectedUserReward method)
// Those same rewards should now be splitted between more staked tokens
// specifically (_currStake + _amountToStake) so the userIndex should increase.
usersIndexes[_user][reward] = userIndex + (
// Accrued rewards should not change after adding more staked tokens so
// we can calculate the increase of the userIndex by solving the following equation
// (rewardsIndexes - userIndex) * _currStake = (rewardsIndexes - (userIndex + X)) * (_currStake + _amountToStake)
// for X we get the increase for the userIndex:
_amountToStake * (rewardsIndexes[reward] - userIndex) / (_currStake + _amountToStake)
);
}
}
}
/// @dev this method is only used to check whether a token is an incentive tokens or not
/// in the depositReward call. The maximum number of element in the array will be a small number (eg at most 3-5)
/// @param _array array of addresses to search for an element
/// @param _val address of an element to find
/// @return flag if the _token is an incentive token or not
function _includesAddress(address[] memory _array, address _val) internal pure returns (bool) {
for (uint256 i = 0; i < _array.length; i++) {
if (_array[i] == _val) {
return true;
}
}
// explicit return to fix linter
return false;
}
// @notice Emergency method, funds gets transferred to the governanceRecoveryFund address
function transferToken(address token, uint256 value) external onlyOwner nonReentrant {
require(token != address(0), 'Address is 0');
IERC20Detailed(token).safeTransfer(governanceRecoveryFund, value);
}
/// @notice can be called by both the owner and the guardian
/// @dev Pauses deposits and redeems
function pause() external onlyOwner {
_pause();
}
/// @notice can be called by both the owner and the guardian
/// @dev Unpauses deposits and redeems
function unpause() external onlyOwner {
_unpause();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which 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
// solhint-disable-next-line compiler-version
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
import "../../../utils/AddressUpgradeable.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20Upgradeable {
using AddressUpgradeable for address;
function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// 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(IERC20Upgradeable token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.7;
interface IIdleCDOStrategy {
function strategyToken() external view returns(address);
function token() external view returns(address);
function tokenDecimals() external view returns(uint256);
function oneToken() external view returns(uint256);
function redeemRewards() external returns(uint256[] memory);
function pullStkAAVE() external returns(uint256);
function price() external view returns(uint256);
function getRewardTokens() external view returns(address[] memory);
function deposit(uint256 _amount) external returns(uint256);
// _amount in `strategyToken`
function redeem(uint256 _amount) external returns(uint256);
// _amount in `token`
function redeemUnderlying(uint256 _amount) external returns(uint256);
function getApr() external view returns(uint256);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.7;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
interface IERC20Detailed is IERC20Upgradeable {
function name() external view returns(string memory);
function symbol() external view returns(string memory);
function decimals() external view returns(uint256);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.7;
interface IIdleCDOTrancheRewards {
function stake(uint256 _amount) external;
function stakeFor(address _user, uint256 _amount) external;
function unstake(uint256 _amount) external;
function depositReward(address _reward, uint256 _amount) external;
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.7;
interface IIdleCDO {
function redeemRewards() external;
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.7;
contract IdleCDOTrancheRewardsStorage {
uint256 public constant ONE_TRANCHE_TOKEN = 10**18;
address public idleCDO;
address public tranche;
address public governanceRecoveryFund;
address[] public rewards;
// amount staked for each user
mapping(address => uint256) public usersStakes;
// globalIndex for each reward token
mapping(address => uint256) public rewardsIndexes;
// per-user index for each reward token
mapping(address => mapping(address => uint256)) public usersIndexes;
// rewards => last amount of reward deposited
mapping(address => uint256) public lockedRewards;
// rewards => block in which last rewards have been deposited
mapping(address => uint256) public lockedRewardsLastBlock;
// total amount of tranche tokens staked
uint256 public totalStaked;
// number of blocks during which rewards will be released for stakers
uint256 public coolingPeriod;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
|
increase the staked amount associated with the user
|
usersStakes[_user] += _amount;
| 11,824,168 |
[
1,
267,
11908,
326,
384,
9477,
3844,
3627,
598,
326,
729,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3677,
510,
3223,
63,
67,
1355,
65,
1011,
389,
8949,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x3f60E778e38608775d9c2D6f31ee44691ee3a455/sources/OceanGate.sol
|
0.15% swap tokens amount
|
swapTokensAtAmount = totalSupply * 15 / 10000;
| 8,411,617 |
[
1,
20,
18,
3600,
9,
7720,
2430,
3844,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
3639,
7720,
5157,
861,
6275,
273,
2078,
3088,
1283,
380,
4711,
342,
12619,
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/1/0xf1264873436A0771E440E2b28072FAfcC5EEBd01/sources/contracts/Kenshi.sol
|
* @title Kenshi @notice This is a basic implementation of the ERC20 protocol. It includes an ownable feature, which allows for a recovery mechanism for tokens that are accidentally sent to the contract address. Only the owner of the contract can retrieve these tokens to prevent unauthorized access./
|
contract Kenshi is ERC20, Ownable {
using SafeERC20 for IERC20;
pragma solidity 0.8.19;
constructor(uint256 totalSupply) ERC20("Kenshi", "KNS") {
_mint(msg.sender, totalSupply);
}
function recoverERC20(
address token,
address recipient,
uint256 amount
) external onlyOwner {
IERC20(token).safeTransfer(recipient, amount);
}
}
| 4,149,511 |
[
1,
47,
275,
674,
77,
225,
1220,
353,
279,
5337,
4471,
434,
326,
4232,
39,
3462,
1771,
18,
2597,
6104,
392,
4953,
429,
2572,
16,
1492,
5360,
364,
279,
11044,
12860,
364,
2430,
716,
854,
25961,
1230,
3271,
358,
326,
6835,
1758,
18,
5098,
326,
3410,
434,
326,
6835,
848,
4614,
4259,
2430,
358,
5309,
640,
8434,
2006,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
16351,
1475,
275,
674,
77,
353,
4232,
39,
3462,
16,
14223,
6914,
288,
203,
565,
1450,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
203,
683,
9454,
18035,
560,
374,
18,
28,
18,
3657,
31,
203,
565,
3885,
12,
11890,
5034,
2078,
3088,
1283,
13,
4232,
39,
3462,
2932,
47,
275,
674,
77,
3113,
315,
47,
3156,
7923,
288,
203,
3639,
389,
81,
474,
12,
3576,
18,
15330,
16,
2078,
3088,
1283,
1769,
203,
565,
289,
203,
203,
565,
445,
5910,
654,
39,
3462,
12,
203,
3639,
1758,
1147,
16,
203,
3639,
1758,
8027,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
3903,
1338,
5541,
288,
203,
3639,
467,
654,
39,
3462,
12,
2316,
2934,
4626,
5912,
12,
20367,
16,
3844,
1769,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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 <0.7.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "./YourToken.sol";
import "hardhat/console.sol";
contract Vendor is Ownable {
YourToken yourToken;
uint256 public constant tokensPerEth = 100;
event BuyTokens(address indexed buyer, uint256 amountOfETH, uint256 amountOfTokens);
event BuyBackTokens(address indexed buyer, uint256 amountOfETH, uint256 amountOfTokens);
constructor(address tokenAddress) public {
yourToken = YourToken(tokenAddress);
}
function buyTokens() payable public {
require(msg.value > 0, "Token value need to be greater than 0");
// Expect eth to come in. divide by eth decimal and * tokens per Eth
uint256 token = (msg.value * tokensPerEth / (10 ** 18)) ;
require(token > 0, "Require token greater than 0 and is an int");
yourToken.transfer(msg.sender,token);
emit BuyTokens(msg.sender, msg.value, token);
}
function buyBack() public {
// allow the sender to buyback all the token.
uint256 balance = yourToken.balanceOf(msg.sender);
require(balance > 0, "You do not own any tokens");
uint256 balanceInWei = (balance * 10 ** 18/ tokensPerEth);
yourToken.transferFrom(msg.sender,address(this),balance);
//send eth to sender.
msg.sender.transfer(balanceInWei);
emit BuyBackTokens(msg.sender, balanceInWei, balance);
}
function getBalanceInWei() public view returns(uint256) {
// allow the sender to buyback all the token.
uint256 balance = yourToken.balanceOf(msg.sender);
require(balance > 0, "You do not own any tokens");
uint256 balanceInWei = (balance * 10 ** 18/ tokensPerEth);
return balanceInWei;
}
receive() external payable
{
buyTokens();
}
}
|
allow the sender to buyback all the token.
|
function getBalanceInWei() public view returns(uint256) {
uint256 balance = yourToken.balanceOf(msg.sender);
require(balance > 0, "You do not own any tokens");
uint256 balanceInWei = (balance * 10 ** 18/ tokensPerEth);
return balanceInWei;
}
receive() external payable
| 5,488,700 |
[
1,
5965,
326,
5793,
358,
30143,
823,
777,
326,
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,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
225,
445,
2882,
6112,
382,
3218,
77,
1435,
1071,
1476,
1135,
12,
11890,
5034,
13,
288,
203,
565,
2254,
5034,
11013,
273,
3433,
1345,
18,
12296,
951,
12,
3576,
18,
15330,
1769,
203,
565,
2583,
12,
12296,
405,
374,
16,
315,
6225,
741,
486,
4953,
1281,
2430,
8863,
203,
565,
2254,
5034,
11013,
382,
3218,
77,
273,
261,
12296,
380,
1728,
2826,
6549,
19,
2430,
2173,
41,
451,
1769,
203,
565,
327,
11013,
382,
3218,
77,
31,
203,
225,
289,
203,
203,
225,
6798,
1435,
3903,
8843,
429,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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 <0.6.0;
import "./installed_contracts/zeppelin/contracts/math/SafeMath.sol";
import "./installed_contracts/zeppelin/contracts/math/SafeMath16.sol";
import "./installed_contracts/zeppelin/contracts/ownership/Ownable.sol";
/**
* @title Certification Smart Contract
* @author Harsh Rajat | https://github.com/HarshRajat/
* @notice Create Certification Smart Contract to administer, award and manage pupils certifications
* @dev This Contract handles management of pupils certications
*/
contract Certification is Ownable {
// Using SafeMath Library
using SafeMath for uint;
using SafeMath16 for uint16;
/* ***************
* DEFINE ENUMS
*************** */
enum grades { Good, Great, Outstanding, Epic, Legendary } // for grades
enum assignmentStatus { Inactive, Pending, Completed, Cancelled } // for assignment information
/* ***************
* DEFINE CONSTANTS
*************** */
/* ***************
* DEFINE STRUCTURES
*************** */
/* Admin Struct handles the admin mapping of address as well as the id to which they are
assigned to.
*/
struct Admin {
bool authorized;
uint id;
}
/* Assignment Struct handles the assignments given to the studens. the assignmentInfo enum is
used to find out if the assignment is active or not and the associated status. Since all assignment
will have their status as Inactive at first, it can also be used to determine the status of final project.
The mapping 0 of Assignment Struct for these reasons is reserved as index 0.
*/
struct Assignment {
string link; //the github link of the assignment
assignmentStatus status; // for the assignment information
}
/* Certification of Students can be handled in a struct, proposed solution:
We use mapping of uint to store id which is mapped to individual students, a
reverse function to map that id to student email id is also used to retrieve the student
using their email id.
- firstName - using bytes32 to save space, handles 32 characters
- lastName - using bytes32 to save space, handles 32 characters
- commendation - using bytes32 to save space, handles 32 characters
- grade - using grades enum since grade is from 1 to 5, max range 256
- assignmentIndex - using uint16 to handle it, max range 65536 | IMP: 0 is always reserved for Final Project
- active - determines if the student has been deemed active or inactive by the admins
- email - is used to reverse map for a student and to display email as well
- assigments - is a mapping of uint16 to struct Assignment
*/
struct Student {
bytes32 firstName;
bytes32 lastName;
bytes32 commendation;
grades grade;
uint16 assignmentIndex;
bool active;
string email;
mapping (uint16 => Assignment) assignments;
}
/* ***************
* DEFINE VARIABLES
*************** */
mapping (address => Admin) public admins;
mapping (uint => address) public adminsReverseMapping;
uint public adminIndex;
uint public maxAdmins; // for setting the max admin limit
mapping (uint => Student) public students;
mapping (string => uint) public studentsReverseMapping;
uint public studentIndex;
/* ***************
* DEFINE EVENTS
*************** */
// Admins Related
event AdminAdded(address adminAddr, uint adminIndex); // Admin Added
event AdminRemoved(address adminAddr, uint adminIndex); // Admin Removed
event AdminLimitChanged(uint newLimit); // Max Admin Limit Changed
// Students Related
event StudentAdded(string email, bytes32 firstName, bytes32 lastName, bytes32 commendation, grades grade);
event StudentRemoved(string email);
event StudentNameUpdated(string email, bytes32 firstName, bytes32 lastName);
event StudentCommendationUpdated(string email, bytes32 commendation);
event StudentGradeUpdated(string email, grades grade);
event StudentEmailUpdated(string oldEmail, string newEmail);
// Assignments Related
event AssignmentAdded(string indexed email, string link, assignmentStatus status, uint16 index);
event AssignmentUpdated(string indexed email, uint16 index, assignmentStatus status);
/* ***************
* DEFINE MODIFIERS
*************** */
// The modifier restricts function access to only admins or owners
modifier onlyAdmins() {
require(
admins[msg.sender].authorized,
"Only Admins allowed"
);
_;
}
// The modifier restricts function access to only non-owner admins
modifier onlyNonOwnerAdmins(address _addr) {
require(
admins[_addr].authorized && owner() != _addr,
"Only Non-Owner Admin allower"
);
_;
}
// The modifier checks the limit of number of Admins allowed
modifier onlyPermissibleAdminLimit() {
require(
adminIndex < maxAdmins,
"Admins Limit Exceeded"
);
_;
}
// The modifier checks for non-existent students
modifier onlyNonExistentStudents(string memory _email) {
require(
!students[studentsReverseMapping[_email]].active,
"Student already Exists"
);
_;
}
// The modifier checks for valid students
modifier onlyValidStudents(string memory _email) {
require(
students[studentsReverseMapping[_email]].active,
"Student doesn't Exists"
);
_;
}
/* ***************
* DEFINE FUNCTIONS
*************** */
constructor () public {
maxAdmins = 2; // mapping the max number of admins including the owner
// Add Owner as admin
_addAdmin(msg.sender);
}
// 1. OVERRIDE OWANABLE FUNCTIONS FOR ADMIN FUNCTIONALITY
// Remove Previous Admin and Add New Owner if necessary | Overriding Ownable.sol
function transferOwnership(address newOwner) public onlyOwner {
// Remove Admin
_removeAdmin(owner());
// Add New Admin
_addAdmin(newOwner);
// Call parent
super._transferOwnership(newOwner);
}
// Remove Owner from Admin as well | Overriding Ownable.sol
function renounceOwnership() public onlyOwner {
// Remove Admin
_removeAdmin(owner());
// Call parent
super.renounceOwnership();
}
// 2. ADMIN RELATED FUNCTIONS
// To Add Administrator
function addAdmin(address _addr) onlyOwner onlyPermissibleAdminLimit public {
// call helper function since constructor needs this
_addAdmin(_addr);
}
// Private helper function to add administrator
function _addAdmin(address _addr) private {
// If Admin doesn't exist alread then add
if (!admins[_addr].authorized) {
// Add to admins
admins[_addr] = Admin(
true, // authorized value
adminIndex // admin count
);
// Add to admins info for reverse mapping
adminsReverseMapping[adminIndex] = _addr;
// Increase admin index
adminIndex = adminIndex.add(1);
// Emit event
emit AdminAdded(_addr, adminIndex);
}
}
// To Remove Administrator, can't remove an owner address
function removeAdmin(address _addr) onlyOwner onlyNonOwnerAdmins(_addr) external {
_removeAdmin(_addr);
}
// Private helper function to remove administrator
function _removeAdmin(address _addr) private {
// check if the admin index is greater than 0
require(
adminIndex > 0,
"Requires atleast 1 Admin"
);
// a bit tricky, swap and delete to maintain mapping
if (admins[_addr].authorized) {
// get id of the admin to be deleted
uint swappableId = admins[_addr].id;
// swap the admins info and update admins mapping
// get the last adminsReverseMapping address for swapping
address swappableAddress = adminsReverseMapping[adminIndex];
// swap the adminsReverseMapping and then reduce admin index
adminsReverseMapping[swappableId] = adminsReverseMapping[adminIndex];
// also remap the admins id
admins[swappableAddress].id = swappableId;
// delete and reduce admin index
delete(admins[_addr]);
delete(adminsReverseMapping[adminIndex]);
adminIndex = adminIndex.sub(1);
// Emit event
emit AdminRemoved(_addr, adminIndex);
}
}
// To Change Administrator Limit
function changeAdminLimit(uint _newLimit) external {
require(
_newLimit >= 1 && _newLimit > adminIndex, "Limit Mismatch"
);
maxAdmins = _newLimit;
// Emit event
emit AdminLimitChanged(maxAdmins);
}
// 3. STUDENTS RELATED FUNCTIONS
// To Add Student
function addStudent(
bytes32 _firstName,
bytes32 _lastName,
bytes32 _commendation,
grades _grade,
string calldata _email
)
external onlyAdmins onlyNonExistentStudents(_email) {
// Add to students
students[studentIndex] = Student(
_firstName,
_lastName,
_commendation,
_grade,
0, // assignmentIndex always starts with 0
true, // active defaults to true
_email
);
// Reverse map for look up based on email
studentsReverseMapping[_email] = studentIndex;
// Increment the student index
studentIndex = studentIndex.add(1);
// Emit event
emit StudentAdded(_email, _firstName, _lastName, _commendation, _grade);
}
// To Remove Student
function removeStudent(string calldata _email) external onlyAdmins onlyValidStudents(_email) {
// update active status
students[studentsReverseMapping[_email]].active = false;
// Emit event
emit StudentRemoved(_email);
}
// To Change Student Name
function changeStudentName(
bytes32 _firstName,
bytes32 _lastName,
string calldata _email
)
external onlyAdmins onlyValidStudents(_email) {
// Update Name
students[studentsReverseMapping[_email]].firstName = _firstName;
students[studentsReverseMapping[_email]].lastName = _lastName;
// Emit event
emit StudentNameUpdated(_email, _firstName, _lastName);
}
// To Change Student commendation
function changeStudentCommendation(
bytes32 _commendation,
string calldata _email
)
external onlyAdmins onlyValidStudents(_email) {
// Update commendation
students[studentsReverseMapping[_email]].commendation = _commendation;
// Emit event
emit StudentCommendationUpdated(_email, _commendation);
}
// To Change Student Grade
function changeStudentGrade(
grades _grade,
string calldata _email
)
external onlyAdmins onlyValidStudents(_email) {
// Update Grade
students[studentsReverseMapping[_email]].grade = _grade;
// Emit event
emit StudentGradeUpdated(_email, _grade);
}
// To Change Student Email
function changeStudentEmail(
string calldata _oldEmail,
string calldata _newEmail
)
external onlyAdmins onlyValidStudents(_oldEmail) onlyNonExistentStudents(_newEmail) {
// update emails
students[studentsReverseMapping[_oldEmail]].email = _newEmail;
studentsReverseMapping[_newEmail] = studentsReverseMapping[_oldEmail];
// delete old email
delete(studentsReverseMapping[_oldEmail]);
// Emit event
emit StudentEmailUpdated(_oldEmail, _newEmail);
}
// 4. ASSIGNMENT RELATED FUNCTIONS
// to add a new assignment
function addAssignment(
string calldata _studentEmail,
string calldata _link,
assignmentStatus _status,
bool _isFinalProject
) external onlyAdmins onlyValidStudents(_studentEmail) {
// get the student
Student storage stud = students[studentsReverseMapping[_studentEmail]];
// get the proper assignment ID
uint16 assignmentID = _calcAndFetchAssignmentIndex(stud, _isFinalProject);
// get the Assignment
Assignment storage assign = stud.assignments[assignmentID];
// update it
assign.link = _link;
assign.status = _status;
// Emit event
emit AssignmentAdded(_studentEmail, _link, _status, stud.assignmentIndex);
}
// To update assignment status
function updateAssignmentStatus(
string calldata _studentEmail,
assignmentStatus _status,
bool _isFinalProject
) external onlyAdmins onlyValidStudents(_studentEmail) {
// get the student
Student storage stud = students[studentsReverseMapping[_studentEmail]];
// get the proper assignment ID
uint16 assignmentID = _calcAndFetchAssignmentIndex(stud, _isFinalProject);
// get the Assignment
Assignment storage assign = stud.assignments[assignmentID];
// update it
assign.status = _status;
// Emit event
emit AssignmentUpdated(_studentEmail, stud.assignmentIndex, _status);
}
// Private helper function to get assignment struct
function _calcAndFetchAssignmentIndex(
Student storage stud,
bool _isFinalProject
) private
returns (uint16 assignmentID) {
if (!_isFinalProject) {
// add to assignmentIndex and assign that as assignmentID
stud.assignmentIndex = stud.assignmentIndex.add(1);
assignmentID = stud.assignmentIndex;
}
}
// Get Assignment Info
function getAssignmentInfo(
string calldata _studentEmail,
uint16 _assignmentID
) external view onlyValidStudents(_studentEmail)
returns (
string memory link,
assignmentStatus status
) {
// get the student
Student storage stud = students[studentsReverseMapping[_studentEmail]];
// check assignment index requirement
require(
_assignmentID <= stud.assignmentIndex && stud.assignmentIndex >= 0,
"Invalid Assignment ID"
);
// get the Assignment
Assignment storage assign = stud.assignments[_assignmentID];
link = assign.link;
status = assign.status;
}
// 5. STRING / BYTE CONVERSION
/**
* @dev Helper Function to convert string to bytes32 format
* @param _source is the string which needs to be converted
* @return result is the bytes32 representation of that string
*/
function stringToBytes32(string memory _source)
public pure
returns (bytes32 result) {
bytes memory tempEmptyStringTest = bytes(_source);
string memory tempSource = _source;
if (tempEmptyStringTest.length == 0) {
return 0x0;
}
assembly {
result := mload(add(tempSource, 32))
}
}
/**
* @dev Helper Function to convert bytes32 to string format
* @param _x is the bytes32 format which needs to be converted
* @return result is the string representation of that bytes32 string
*/
function bytes32ToString(bytes32 _x)
public pure
returns (string memory result) {
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 (uint j = 0; j < charCount; j++) {
bytesStringTrimmed[j] = bytesString[j];
}
result = string(bytesStringTrimmed);
}
}
|
*************** DEFINE ENUMS / *************** DEFINE CONSTANTS / *************** DEFINE STRUCTURES / Admin Struct handles the admin mapping of address as well as the id to which they are/
|
struct Admin {
bool authorized;
uint id;
}
will have their status as Inactive at first, it can also be used to determine the status of final project.
The mapping 0 of Assignment Struct for these reasons is reserved as index 0.
| 909,681 |
[
1,
12904,
3740,
24776,
55,
342,
225,
25957,
3740,
24023,
55,
342,
225,
25957,
3740,
7128,
9749,
4830,
55,
342,
7807,
7362,
7372,
326,
3981,
2874,
434,
1758,
487,
5492,
487,
326,
612,
358,
1492,
2898,
854,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
1958,
7807,
288,
203,
3639,
1426,
10799,
31,
203,
3639,
2254,
612,
31,
203,
565,
289,
203,
377,
203,
565,
903,
1240,
3675,
1267,
487,
657,
3535,
622,
1122,
16,
518,
848,
2546,
506,
1399,
358,
4199,
326,
1267,
434,
727,
1984,
18,
203,
565,
1021,
2874,
374,
434,
15499,
7362,
364,
4259,
14000,
353,
8735,
487,
770,
374,
18,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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.3;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../interfaces/IHologramAccumulator.sol";
/// @title HologramAccumulator - counts the behavior.
/// @author Shumpei Koike - <[email protected]>
contract HologramAccumulator is IHologramAccumulator, Ownable {
using Address for address;
uint256 public constant DENOMINATOR = 1000;
mapping(address => uint256) private _weighted;
mapping(address => uint256) private _accumulate;
/// Events
event Accumulate(address caller, address account, uint256 weight);
event AccumulateBatch2(address caller, address[2] accounts, uint256 weight);
event AccumulateBatch3(address caller, address[3] accounts, uint256 weight);
event Undermine(address caller, address account, uint256 weight);
event UndermineBatch2(address caller, address[2] accounts, uint256 weight);
event UndermineBatch3(address caller, address[3] accounts, uint256 weight);
event ChangeCoefficient(address accessor, uint256 coefficient);
event Accept(address accessor);
/// @dev Initializes the msg.sender as 1000.
constructor() Ownable() {
_weighted[msg.sender] = DENOMINATOR;
}
/// @dev Prevents calling a function from anyone except the accepted address.
modifier onlyAccepted() {
require(_weighted[msg.sender] != 0, "HL301");
_;
}
/// @dev Counts a positive behavior.
/// @param account address who behaves positively
function accumulateSmall(address account) public override onlyAccepted {
_accumulate[account]++;
emit Accumulate(msg.sender, account, _weighted[msg.sender]);
}
/// @dev Counts a positive behavior.
/// @param account address who behaves positively
function accumulateMedium(address account) public override onlyAccepted {
_accumulate[account] += 2;
emit Accumulate(msg.sender, account, _weighted[msg.sender]);
}
/// @dev Counts a positive behavior.
/// @param account address who behaves positively
function accumulateLarge(address account) public override onlyAccepted {
_accumulate[account] += 3;
emit Accumulate(msg.sender, account, _weighted[msg.sender]);
}
/// @dev Counts a positive behavior.
/// @param accounts a set of addresses who behave positively
function accumulateBatch2Small(address[2] memory accounts)
public
override
onlyAccepted
{
for (uint256 i = 0; i < accounts.length; i++) {
_accumulate[accounts[i]]++;
}
emit AccumulateBatch2(msg.sender, accounts, _weighted[msg.sender]);
}
/// @dev Counts a positive behavior.
/// @param accounts a set of addresses who behave positively
function accumulateBatch2Medium(address[2] memory accounts)
public
override
onlyAccepted
{
for (uint256 i = 0; i < accounts.length; i++) {
_accumulate[accounts[i]] += 2;
}
emit AccumulateBatch2(msg.sender, accounts, _weighted[msg.sender]);
}
/// @dev Counts a positive behavior.
/// @param accounts a set of addresses who behave positively
function accumulateBatch2Large(address[2] memory accounts)
public
override
onlyAccepted
{
for (uint256 i = 0; i < accounts.length; i++) {
_accumulate[accounts[i]] += 3;
}
emit AccumulateBatch2(msg.sender, accounts, _weighted[msg.sender]);
}
/// @dev Counts a positive behavior.
/// @param accounts a set of addresses who behave positively
function accumulateBatch3Small(address[3] memory accounts)
public
override
onlyAccepted
{
for (uint256 i = 0; i < accounts.length; i++) {
_accumulate[accounts[i]]++;
}
emit AccumulateBatch3(msg.sender, accounts, _weighted[msg.sender]);
}
/// @dev Counts a positive behavior.
/// @param accounts a set of addresses who behave positively
function accumulateBatch3Medium(address[3] memory accounts)
public
override
onlyAccepted
{
for (uint256 i = 0; i < accounts.length; i++) {
_accumulate[accounts[i]] += 2;
}
emit AccumulateBatch3(msg.sender, accounts, _weighted[msg.sender]);
}
/// @dev Counts a positive behavior.
/// @param accounts a set of addresses who behave positively
function accumulateBatch3Large(address[3] memory accounts)
public
override
onlyAccepted
{
for (uint256 i = 0; i < accounts.length; i++) {
_accumulate[accounts[i]] += 3;
}
emit AccumulateBatch3(msg.sender, accounts, _weighted[msg.sender]);
}
/// @dev Counts a nagative behavior.
/// @param account address who behaves negatively
function undermineSmall(address account) public override onlyAccepted {
_accumulate[account] > 0
? _accumulate[account]--
: _accumulate[account] = 0;
emit Undermine(msg.sender, account, _weighted[msg.sender]);
}
/// @dev Counts a nagative behavior.
/// @param account address who behaves negatively
function undermineMedium(address account) public override onlyAccepted {
_accumulate[account] > 1
? _accumulate[account] -= 2
: _accumulate[account] = 0;
emit Undermine(msg.sender, account, _weighted[msg.sender]);
}
/// @dev Counts a nagative behavior.
/// @param account address who behaves negatively
function undermineLarge(address account) public override onlyAccepted {
_accumulate[account] > 2
? _accumulate[account] -= 3
: _accumulate[account] = 0;
emit Undermine(msg.sender, account, _weighted[msg.sender]);
}
/// @dev Counts a nagative behavior.
/// @param accounts a set of addresses who behave negatively
function undermineBatch2Small(address[2] memory accounts)
public
override
onlyAccepted
{
for (uint256 i = 0; i < accounts.length; i++) {
_accumulate[accounts[i]] > 0
? _accumulate[accounts[i]]--
: _accumulate[accounts[i]] = 0;
}
emit UndermineBatch2(msg.sender, accounts, _weighted[msg.sender]);
}
/// @dev Counts a nagative behavior.
/// @param accounts a set of addresses who behave negatively
function undermineBatch2Medium(address[2] memory accounts)
public
override
onlyAccepted
{
for (uint256 i = 0; i < accounts.length; i++) {
_accumulate[accounts[i]] > 1
? _accumulate[accounts[i]] -= 2
: _accumulate[accounts[i]] = 0;
}
emit UndermineBatch2(msg.sender, accounts, _weighted[msg.sender]);
}
/// @dev Counts a nagative behavior.
/// @param accounts a set of addresses who behave negatively
function undermineBatch2Large(address[2] memory accounts)
public
override
onlyAccepted
{
for (uint256 i = 0; i < accounts.length; i++) {
_accumulate[accounts[i]] > 2
? _accumulate[accounts[i]] -= 3
: _accumulate[accounts[i]] = 0;
}
emit UndermineBatch2(msg.sender, accounts, _weighted[msg.sender]);
}
/// @dev Counts a nagative behavior.
/// @param accounts a set of addresses who behave negatively
function undermineBatch3Small(address[3] memory accounts)
public
override
onlyAccepted
{
for (uint256 i = 0; i < accounts.length; i++) {
_accumulate[accounts[i]] > 0
? _accumulate[accounts[i]]--
: _accumulate[accounts[i]] = 0;
}
emit UndermineBatch3(msg.sender, accounts, _weighted[msg.sender]);
}
/// @dev Counts a nagative behavior.
/// @param accounts a set of addresses who behave negatively
function undermineBatch3Medium(address[3] memory accounts)
public
override
onlyAccepted
{
for (uint256 i = 0; i < accounts.length; i++) {
_accumulate[accounts[i]] > 1
? _accumulate[accounts[i]] -= 2
: _accumulate[accounts[i]] = 0;
}
emit UndermineBatch3(msg.sender, accounts, _weighted[msg.sender]);
}
/// @dev Counts a nagative behavior.
/// @param accounts a set of addresses who behave negatively
function undermineBatch3Large(address[3] memory accounts)
public
override
onlyAccepted
{
for (uint256 i = 0; i < accounts.length; i++) {
_accumulate[accounts[i]] > 2
? _accumulate[accounts[i]] -= 3
: _accumulate[accounts[i]] = 0;
}
emit UndermineBatch3(msg.sender, accounts, _weighted[msg.sender]);
}
/// @dev Accepts a new contract address that can
/// accumulate or undermine the credit.
/// @param accessor address of a contract address
function accept(address accessor) public onlyOwner {
require(accessor.isContract(), "HL302");
_weighted[accessor] = DENOMINATOR;
emit Accept(accessor);
}
/// @dev Sets the coefficient for the account.
/// If the accessor is over writing, the coeffient is decreased,
/// meaning the accumulation converges to an appropriate value.
/// @param accessor address of the contract address
/// @param coefficient value of the coefficient
function changeCoefficient(address accessor, uint256 coefficient)
public
onlyOwner
{
_weighted[accessor] = coefficient;
emit ChangeCoefficient(accessor, coefficient);
}
/// @dev Gets the weight value of the accessor. The default value is 1000.
/// @param accessor address of the contract address
function weighted(address accessor) public view returns (uint256) {
return _weighted[accessor] != 0 ? _weighted[accessor] : DENOMINATOR;
}
}
|
@dev Sets the coefficient for the account. If the accessor is over writing, the coeffient is decreased, meaning the accumulation converges to an appropriate value. @param accessor address of the contract address @param coefficient value of the coefficient
|
function changeCoefficient(address accessor, uint256 coefficient)
public
onlyOwner
{
_weighted[accessor] = coefficient;
emit ChangeCoefficient(accessor, coefficient);
}
| 1,794,453 |
[
1,
2785,
326,
16554,
364,
326,
2236,
18,
1377,
971,
326,
9789,
353,
1879,
7410,
16,
326,
11943,
1979,
353,
23850,
8905,
16,
1377,
12256,
326,
8822,
367,
14581,
2852,
358,
392,
5505,
460,
18,
225,
9789,
1758,
434,
326,
6835,
1758,
225,
16554,
460,
434,
326,
16554,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
202,
915,
2549,
4249,
25403,
12,
2867,
9789,
16,
2254,
5034,
16554,
13,
203,
202,
202,
482,
203,
202,
202,
3700,
5541,
203,
202,
95,
203,
202,
202,
67,
30890,
63,
3860,
280,
65,
273,
16554,
31,
203,
202,
202,
18356,
7576,
4249,
25403,
12,
3860,
280,
16,
16554,
1769,
203,
202,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/97/0x39d71a752bAF5aA4012fF3830cb3775311F9bce0/sources/Users/oscar1/Crocoswapv2/Crocoswap-token/contracts/Croco.sol
|
* @notice Mint new tokens @param dst The address of the destination account @param rawAmount The number of tokens to be minted/ record the mint mint the amount transfer the amount to the recipient move delegates
|
function mint(address dst, uint rawAmount) external {
require(msg.sender == minter, "Croco::mint: only the minter can mint");
require(block.timestamp >= mintingAllowedAfter, "Croco::mint: minting not allowed yet");
require(dst != address(0), "Croco::mint: cannot transfer to the zero address");
mintingAllowedAfter = SafeMath.add(block.timestamp, minimumTimeBetweenMints);
uint96 amount = safe96(rawAmount, "Croco::mint: amount exceeds 96 bits");
require(amount <= SafeMath.div(SafeMath.mul(totalSupply, mintCap), 100), "Croco::mint: exceeded mint cap");
totalSupply = safe96(SafeMath.add(totalSupply, amount), "Croco::mint: totalSupply exceeds 96 bits");
balances[dst] = add96(balances[dst], amount, "Croco::mint: transfer amount overflows");
emit Transfer(address(0), dst, amount);
_moveDelegates(address(0), delegates[dst], amount);
}
| 3,265,221 |
[
1,
49,
474,
394,
2430,
225,
3046,
1021,
1758,
434,
326,
2929,
2236,
225,
1831,
6275,
1021,
1300,
434,
2430,
358,
506,
312,
474,
329,
19,
1409,
326,
312,
474,
312,
474,
326,
3844,
7412,
326,
3844,
358,
326,
8027,
3635,
22310,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
312,
474,
12,
2867,
3046,
16,
2254,
1831,
6275,
13,
3903,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
1131,
387,
16,
315,
39,
303,
2894,
2866,
81,
474,
30,
1338,
326,
1131,
387,
848,
312,
474,
8863,
203,
3639,
2583,
12,
2629,
18,
5508,
1545,
312,
474,
310,
5042,
4436,
16,
315,
39,
303,
2894,
2866,
81,
474,
30,
312,
474,
310,
486,
2935,
4671,
8863,
203,
3639,
2583,
12,
11057,
480,
1758,
12,
20,
3631,
315,
39,
303,
2894,
2866,
81,
474,
30,
2780,
7412,
358,
326,
3634,
1758,
8863,
203,
203,
3639,
312,
474,
310,
5042,
4436,
273,
14060,
10477,
18,
1289,
12,
2629,
18,
5508,
16,
5224,
950,
11831,
49,
28142,
1769,
203,
203,
3639,
2254,
10525,
3844,
273,
4183,
10525,
12,
1899,
6275,
16,
315,
39,
303,
2894,
2866,
81,
474,
30,
3844,
14399,
19332,
4125,
8863,
203,
3639,
2583,
12,
8949,
1648,
14060,
10477,
18,
2892,
12,
9890,
10477,
18,
16411,
12,
4963,
3088,
1283,
16,
312,
474,
4664,
3631,
2130,
3631,
315,
39,
303,
2894,
2866,
81,
474,
30,
12428,
312,
474,
3523,
8863,
203,
3639,
2078,
3088,
1283,
273,
4183,
10525,
12,
9890,
10477,
18,
1289,
12,
4963,
3088,
1283,
16,
3844,
3631,
315,
39,
303,
2894,
2866,
81,
474,
30,
2078,
3088,
1283,
14399,
19332,
4125,
8863,
203,
203,
3639,
324,
26488,
63,
11057,
65,
273,
527,
10525,
12,
70,
26488,
63,
11057,
6487,
3844,
16,
315,
39,
303,
2894,
2866,
81,
474,
30,
7412,
3844,
9391,
87,
8863,
203,
3639,
3626,
2
] |
./partial_match/1/0x442335a9114fdd46E20a56C984Acbcf0C882Fca2/sources/CPTToken.sol
|
public variables public functions
|
contract CPTToken is FreezeableToken {
string public name = "CPT Token";
string public symbol = "CPT";
uint8 public decimals = 18;
}
constructor(address _owner, address _freezer) public {
_totalSupply = 21000000000 * (10 ** uint256(decimals));
_balances[_owner] = _totalSupply;
emit Transfer(0x0, _owner, _totalSupply);
setOwner(_owner);
setFreezer(_freezer);
}
}
| 3,718,517 |
[
1,
482,
3152,
1071,
4186,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
16351,
385,
1856,
1345,
353,
15217,
8489,
429,
1345,
288,
203,
225,
533,
1071,
508,
273,
315,
39,
1856,
3155,
14432,
203,
225,
533,
1071,
3273,
273,
315,
39,
1856,
14432,
203,
225,
2254,
28,
1071,
15105,
273,
6549,
31,
203,
203,
97,
203,
225,
3885,
12,
2867,
389,
8443,
16,
1758,
389,
9156,
24355,
13,
1071,
288,
203,
565,
389,
4963,
3088,
1283,
273,
9035,
2787,
11706,
380,
261,
2163,
2826,
2254,
5034,
12,
31734,
10019,
203,
203,
565,
389,
70,
26488,
63,
67,
8443,
65,
273,
389,
4963,
3088,
1283,
31,
203,
565,
3626,
12279,
12,
20,
92,
20,
16,
389,
8443,
16,
389,
4963,
3088,
1283,
1769,
203,
203,
565,
31309,
24899,
8443,
1769,
203,
565,
444,
9194,
24355,
24899,
9156,
24355,
1769,
203,
225,
289,
203,
97,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.7;
import "@rari-capital/solmate/src/tokens/ERC20.sol";
import "@rari-capital/solmate/src/utils/SafeTransferLib.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "../../libraries/Babylonian.sol";
import "../../interfaces/IStrategy.sol";
import "../../interfaces/ISushiSwap.sol";
import "../../interfaces/IMasterChef.sol";
import "../../interfaces/IDynamicSubLPStrategy.sol";
import "../../interfaces/IBentoBoxMinimal.sol";
/// @notice Dynamic strategy that can have different farming strategy
/// For example, farming on Trader Joe then unwrap the jLP to
/// mint pLP and farm on Pengolin.
contract DynamicLPStrategy is IStrategy, Ownable {
using SafeTransferLib for ERC20;
address public immutable strategyToken;
address public immutable token0;
address public immutable token1;
address public immutable bentoBox;
address public feeCollector;
uint8 public feePercent;
uint256 public maxBentoBoxBalance; /// @dev Slippage protection when calling harvest
mapping(address => bool) public strategyExecutors; /// @dev EOAs that can execute safeHarvest
IDynamicSubLPStrategy[] public subStrategies;
IDynamicSubLPStrategy public currentSubStrategy;
bool public exited; /// @dev After bentobox 'exits' the strategy harvest, skim and withdraw functions can no loner be called
event LogSubStrategyAdded(address indexed subStrategy);
event LogSubStrategyChanged(
address indexed fromStrategy,
address indexed toStrategy,
uint256 amountOut,
uint256 amountOutPrice,
uint256 amountIn,
uint256 amountInPrice
);
event LogSetStrategyExecutor(address indexed executor, bool allowed);
/** @param _strategyToken Address of the underlying LP token the strategy invests.
@param _bentoBox BentoBox address.
@param _strategyExecutor an EOA that will execute the safeHarvest function.
*/
constructor(
address _strategyToken,
address _bentoBox,
address _strategyExecutor
) {
strategyToken = _strategyToken;
token0 = ISushiSwap(_strategyToken).token0();
token1 = ISushiSwap(_strategyToken).token1();
bentoBox = _bentoBox;
if (_strategyExecutor != address(0)) {
strategyExecutors[_strategyExecutor] = true;
emit LogSetStrategyExecutor(_strategyExecutor, true);
}
}
modifier isActive() {
require(!exited, "BentoBox Strategy: exited");
_;
}
modifier onlyBentoBox() {
require(msg.sender == bentoBox, "BentoBox Strategy: only BentoBox");
_;
}
/// @notice Ensure the current strategy is handling _strategyToken token so that skim,
/// withdraw and exit can report correctly back to bentobox.
modifier onlyValidStrategy() {
require(address(currentSubStrategy) != address(0), "zero address");
require(currentSubStrategy.strategyTokenIn() == strategyToken, "not handling strategyToken");
_;
}
modifier onlyExecutor() {
require(strategyExecutors[msg.sender], "BentoBox Strategy: only Executors");
_;
}
function addSubStrategy(IDynamicSubLPStrategy subStrategy) public onlyOwner {
require(address(subStrategy) != address(0), "zero address");
require(subStrategy.dynamicStrategy() == address(this), "dynamicStrategy mismatch");
/// @dev make sure the strategy pair token is using the same token0 and token1
ISushiSwap sushiPair = ISushiSwap(subStrategy.strategyTokenIn());
require(sushiPair.token0() == token0 && sushiPair.token1() == token1, "incompatible tokens");
subStrategies.push(subStrategy);
emit LogSubStrategyAdded(address(subStrategy));
if (address(currentSubStrategy) == address(0)) {
require(subStrategy.strategyTokenIn() == strategyToken, "not strategyTokenIn");
currentSubStrategy = subStrategy;
emit LogSubStrategyChanged(address(0), address(currentSubStrategy), 0, 0, 0, 0);
}
}
/// @param index the index of the next strategy to use
/// @param maxSlippageBps maximum tolerated amount of basis points of the total migrated
/// 5 = 0.05%
/// 10_000 = 100%
/// @param minDustAmount0 when the new strategy needs to wrap the token0 and token1 from previousSubStrategy
/// unwrapped token0 and token1, after initial addLiquidity, what minimum remaining
/// amount left in the contract (from new pair imbalance),
/// should be considered to swap again for more liquidity. Set to 0 to ignore.
/// @param minDustAmount1 same as minDustAmount0 but for token1
function changeStrategy(
uint256 index,
uint256 maxSlippageBps,
uint256 minDustAmount0,
uint256 minDustAmount1
) public onlyExecutor {
require(index < subStrategies.length, "invalid index");
IDynamicSubLPStrategy previousSubStrategy = currentSubStrategy;
currentSubStrategy = subStrategies[index];
require(previousSubStrategy != currentSubStrategy, "already current");
/// @dev the next sub strategy is not using the same strategy token
/// and requires a convertion
if (previousSubStrategy.strategyTokenIn() != currentSubStrategy.strategyTokenIn()) {
/// @dev unwrap needs send the token0 and token1 to the next strategy directly
(uint256 amountFrom, uint256 priceAmountFrom) = previousSubStrategy.withdrawAndUnwrapTo(currentSubStrategy);
/// @dev wrap from the tokens sent from the previous strategy
(uint256 amountTo, uint256 priceAmountTo) = currentSubStrategy.wrapAndDeposit(minDustAmount0, minDustAmount1);
uint256 minToteraledPrice = priceAmountFrom - ((priceAmountFrom * maxSlippageBps) / 10_000);
require(priceAmountTo >= minToteraledPrice, "maximumBps exceeded");
emit LogSubStrategyChanged(
address(previousSubStrategy),
address(currentSubStrategy),
amountFrom,
priceAmountFrom,
amountTo,
priceAmountTo
);
}
}
/// @inheritdoc IStrategy
function skim(uint256 amount) external override onlyValidStrategy {
/// @dev bentobox transfers the token in this strategy so we need to
/// forward them to the sub strategy so that the specific skim can work.
ERC20(strategyToken).transfer(address(currentSubStrategy), amount);
currentSubStrategy.skim(amount);
}
/// @inheritdoc IStrategy
function withdraw(uint256 amount) external override isActive onlyBentoBox onlyValidStrategy returns (uint256 actualAmount) {
return currentSubStrategy.withdraw(amount);
}
/// @notice Harvest profits while preventing a sandwich attack exploit.
/// @param maxBalance The maximum balance of the underlying token that is allowed to be in BentoBox.
/// @param rebalance Whether BentoBox should rebalance the strategy assets to acheive it's target allocation.
/// @param maxChangeAmount When rebalancing - the maximum amount that will be deposited to or withdrawn from a strategy to BentoBox.
/// @dev maxBalance can be set to 0 to keep the previous value.
/// @dev maxChangeAmount can be set to 0 to allow for full rebalancing.
function safeHarvest(
uint256 maxBalance,
bool rebalance,
uint256 maxChangeAmount
) external onlyExecutor {
if (maxBalance > 0) {
maxBentoBoxBalance = maxBalance;
}
IBentoBoxMinimal(bentoBox).harvest(strategyToken, rebalance, maxChangeAmount);
}
/// @inheritdoc IStrategy
/// @dev Only BentoBox can call harvest on this strategy.
/// @dev Ensures that (1) the caller was this contract (called through the safeHarvest function)
/// and (2) that we are not being frontrun by a large BentoBox deposit when harvesting profits.
/// @dev Beware that calling harvest can result in a subsequent skim or withdraw call if it's rebalancing.
function harvest(uint256 balance, address sender) external override isActive onlyBentoBox returns (int256) {
require(address(currentSubStrategy) != address(0), "zero address");
/// @dev Don't revert if conditions aren't met in order to allow
/// BentoBox to continue execution as it might need to do a rebalance.
if (sender == address(this) && IBentoBoxMinimal(bentoBox).totals(strategyToken).elastic <= maxBentoBoxBalance && balance > 0) {
return int256(currentSubStrategy.harvest());
}
return int256(0);
}
/// @inheritdoc IStrategy
/// @dev do not use isActive modifier here; allow bentobox to call strategy.exit() multiple times
function exit(uint256 balance) external override onlyBentoBox onlyValidStrategy returns (int256 amountAdded) {
uint256 actualBalance = currentSubStrategy.exit();
/// @dev Calculate tokens added (or lost).
amountAdded = int256(actualBalance) - int256(balance);
exited = true;
}
function swapToLP(uint256 amountOutMin) external onlyExecutor returns (uint256) {
return currentSubStrategy.swapToLP(amountOutMin, feePercent, feeCollector);
}
function setStrategyExecutor(address executor, bool value) external onlyOwner {
strategyExecutors[executor] = value;
emit LogSetStrategyExecutor(executor, value);
}
function setFeeParameters(address _feeCollector, uint8 _feePercent) external onlyOwner {
require(feePercent <= 100, "invalid feePercent");
feeCollector = _feeCollector;
feePercent = _feePercent;
}
}
|
@dev make sure the strategy pair token is using the same token0 and token1
|
function addSubStrategy(IDynamicSubLPStrategy subStrategy) public onlyOwner {
require(address(subStrategy) != address(0), "zero address");
require(subStrategy.dynamicStrategy() == address(this), "dynamicStrategy mismatch");
ISushiSwap sushiPair = ISushiSwap(subStrategy.strategyTokenIn());
require(sushiPair.token0() == token0 && sushiPair.token1() == token1, "incompatible tokens");
subStrategies.push(subStrategy);
emit LogSubStrategyAdded(address(subStrategy));
if (address(currentSubStrategy) == address(0)) {
require(subStrategy.strategyTokenIn() == strategyToken, "not strategyTokenIn");
currentSubStrategy = subStrategy;
emit LogSubStrategyChanged(address(0), address(currentSubStrategy), 0, 0, 0, 0);
}
}
| 5,432,254 |
[
1,
6540,
3071,
326,
6252,
3082,
1147,
353,
1450,
326,
1967,
1147,
20,
471,
1147,
21,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
25716,
4525,
12,
734,
3920,
1676,
14461,
4525,
720,
4525,
13,
1071,
1338,
5541,
288,
203,
3639,
2583,
12,
2867,
12,
1717,
4525,
13,
480,
1758,
12,
20,
3631,
315,
7124,
1758,
8863,
203,
3639,
2583,
12,
1717,
4525,
18,
14507,
4525,
1435,
422,
1758,
12,
2211,
3631,
315,
14507,
4525,
13484,
8863,
203,
203,
3639,
4437,
1218,
77,
12521,
272,
1218,
77,
4154,
273,
4437,
1218,
77,
12521,
12,
1717,
4525,
18,
14914,
1345,
382,
10663,
203,
3639,
2583,
12,
87,
1218,
77,
4154,
18,
2316,
20,
1435,
422,
1147,
20,
597,
272,
1218,
77,
4154,
18,
2316,
21,
1435,
422,
1147,
21,
16,
315,
267,
10943,
2430,
8863,
203,
203,
3639,
720,
1585,
15127,
18,
6206,
12,
1717,
4525,
1769,
203,
3639,
3626,
1827,
1676,
4525,
8602,
12,
2867,
12,
1717,
4525,
10019,
203,
203,
3639,
309,
261,
2867,
12,
2972,
1676,
4525,
13,
422,
1758,
12,
20,
3719,
288,
203,
5411,
2583,
12,
1717,
4525,
18,
14914,
1345,
382,
1435,
422,
6252,
1345,
16,
315,
902,
6252,
1345,
382,
8863,
203,
5411,
783,
1676,
4525,
273,
720,
4525,
31,
203,
203,
5411,
3626,
1827,
1676,
4525,
5033,
12,
2867,
12,
20,
3631,
1758,
12,
2972,
1676,
4525,
3631,
374,
16,
374,
16,
374,
16,
374,
1769,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
// Created By: LoMel
contract DemiGodsUniverse is ERC721Enumerable, Ownable, ReentrancyGuard {
using ECDSA for bytes32;
using SafeMath for uint256;
using Counters for Counters.Counter;
Counters.Counter private _tokenIdCounter;
Counters.Counter private _numAirdroped;
Counters.Counter private _numMinted;
enum ContractState { PAUSED, PRESALE_ONE, PRESALE_TWO, PUBLIC }
ContractState public currentState = ContractState.PAUSED;
// Total supply 10,000
uint256 public maxTotalMint = 2000; // increments based on contract state
uint256 public constant AIRDROP_RESERVE = 50; // used to help market the project
mapping(address => uint256) public addressMinted;
uint256 public pricePerDemiGod = .07 ether;
uint256 public MAX_PER_TRANSACTION = 10;
string private baseURI;
string private signVersion;
address private signer;
constructor(
string memory name,
string memory symbol,
string memory _uri, string memory _signVersion) ERC721(name, symbol) {
baseURI = _uri;
signVersion = _signVersion;
signer = msg.sender;
}
function updateSignVersion(string calldata _signVersion) external onlyOwner {
signVersion = _signVersion;
}
function updateSigner(address _signer) external onlyOwner {
signer = _signer;
}
function _verify(address sender, uint256 maxMintAmount, bytes memory signature) internal view returns (bool) {
return keccak256(abi.encodePacked(sender, signVersion, maxMintAmount))
.toEthSignedMessageHash()
.recover(signature) == signer;
}
function changeContractState(ContractState _state) external onlyOwner {
currentState = _state;
if(currentState == ContractState.PRESALE_ONE) {
pricePerDemiGod = .07 ether;
maxTotalMint = 2000;
}
else if(currentState == ContractState.PRESALE_TWO) {
pricePerDemiGod = .1 ether;
maxTotalMint = 6000;
}
else if(currentState == ContractState.PUBLIC) {
pricePerDemiGod = .15 ether;
maxTotalMint = 9950;
}
}
function claimDemiGods(uint256 _numberOfDemiGods, uint256 _maxMintAmount, bytes memory _signature) external payable nonReentrant{
require(
(currentState == ContractState.PRESALE_ONE ||
currentState == ContractState.PRESALE_TWO), "The whitelist is not active yet. Stay tuned.");
require(_numberOfDemiGods > 0, "You cannot mint 0 Demi Gods.");
require(SafeMath.add(_numMinted.current(), _numberOfDemiGods) <= maxTotalMint, "The entire presale has been sold. Check back for public mint.");
require(getNFTPrice(_numberOfDemiGods) <= msg.value, "Amount of Ether sent is not correct.");
require(_verify(msg.sender, _maxMintAmount, _signature), "This signature is not verified. You are not on the whitelist.");
require(SafeMath.add(addressMinted[msg.sender], _numberOfDemiGods) <= _maxMintAmount, "This amount exceeds the quantity you are allowed to mint during presale.");
for(uint i = 0; i < _numberOfDemiGods; i++){
uint256 tokenIndex = _tokenIdCounter.current();
_numMinted.increment();
_tokenIdCounter.increment();
addressMinted[msg.sender]++;
_safeMint(msg.sender, tokenIndex);
}
}
function mintDemiGods(uint256 _numberOfDemiGods) external payable nonReentrant{
require(currentState == ContractState.PUBLIC, "The public sale is not active yet. Stay Tuned.");
require(_numberOfDemiGods > 0, "You cannot mint 0 Demi Gods.");
require(_numberOfDemiGods <= MAX_PER_TRANSACTION, "You can only mint 15 Demi Gods per transaction.");
require(SafeMath.add(_numMinted.current(), _numberOfDemiGods) <= maxTotalMint, "Exceeds maximum supply.");
require(getNFTPrice(_numberOfDemiGods) <= msg.value, "Amount of Ether sent is not correct.");
for(uint i = 0; i < _numberOfDemiGods; i++){
uint256 tokenIndex = _tokenIdCounter.current();
_numMinted.increment();
_tokenIdCounter.increment();
_safeMint(msg.sender, tokenIndex);
}
}
function airdropDemiGod(uint256 _numberOfDemiGods) external onlyOwner {
require(_numberOfDemiGods > 0, "You cannot mint 0 Demi Gods.");
require(SafeMath.add(_numAirdroped.current(), _numberOfDemiGods) <= AIRDROP_RESERVE, "Exceeds maximum airdrop reserve.");
for(uint i = 0; i < _numberOfDemiGods; i++){
uint256 tokenId = _tokenIdCounter.current();
_tokenIdCounter.increment();
_numAirdroped.increment();
_safeMint(msg.sender, tokenId);
}
}
function getNFTPrice(uint256 _amount) public view returns (uint256) {
return SafeMath.mul(_amount, pricePerDemiGod);
}
function withdraw() external onlyOwner {
uint256 balance = address(this).balance;
Address.sendValue(payable(msg.sender), balance);
}
function setBaseURI(string memory uri) external onlyOwner {
baseURI = uri;
}
function _baseURI() internal view override returns (string memory) {
return baseURI;
}
}
// 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 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 Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
|
Created By: LoMel Total supply 10,000
|
contract DemiGodsUniverse is ERC721Enumerable, Ownable, ReentrancyGuard {
using ECDSA for bytes32;
using SafeMath for uint256;
using Counters for Counters.Counter;
Counters.Counter private _tokenIdCounter;
Counters.Counter private _numAirdroped;
Counters.Counter private _numMinted;
ContractState public currentState = ContractState.PAUSED;
mapping(address => uint256) public addressMinted;
uint256 public pricePerDemiGod = .07 ether;
uint256 public MAX_PER_TRANSACTION = 10;
string private baseURI;
string private signVersion;
address private signer;
constructor(
string memory name,
string memory symbol,
pragma solidity ^0.8.2;
enum ContractState { PAUSED, PRESALE_ONE, PRESALE_TWO, PUBLIC }
string memory _uri, string memory _signVersion) ERC721(name, symbol) {
baseURI = _uri;
signVersion = _signVersion;
signer = msg.sender;
}
function updateSignVersion(string calldata _signVersion) external onlyOwner {
signVersion = _signVersion;
}
function updateSigner(address _signer) external onlyOwner {
signer = _signer;
}
function _verify(address sender, uint256 maxMintAmount, bytes memory signature) internal view returns (bool) {
return keccak256(abi.encodePacked(sender, signVersion, maxMintAmount))
.toEthSignedMessageHash()
.recover(signature) == signer;
}
function changeContractState(ContractState _state) external onlyOwner {
currentState = _state;
if(currentState == ContractState.PRESALE_ONE) {
pricePerDemiGod = .07 ether;
maxTotalMint = 2000;
}
else if(currentState == ContractState.PRESALE_TWO) {
pricePerDemiGod = .1 ether;
maxTotalMint = 6000;
}
else if(currentState == ContractState.PUBLIC) {
pricePerDemiGod = .15 ether;
maxTotalMint = 9950;
}
}
function changeContractState(ContractState _state) external onlyOwner {
currentState = _state;
if(currentState == ContractState.PRESALE_ONE) {
pricePerDemiGod = .07 ether;
maxTotalMint = 2000;
}
else if(currentState == ContractState.PRESALE_TWO) {
pricePerDemiGod = .1 ether;
maxTotalMint = 6000;
}
else if(currentState == ContractState.PUBLIC) {
pricePerDemiGod = .15 ether;
maxTotalMint = 9950;
}
}
function changeContractState(ContractState _state) external onlyOwner {
currentState = _state;
if(currentState == ContractState.PRESALE_ONE) {
pricePerDemiGod = .07 ether;
maxTotalMint = 2000;
}
else if(currentState == ContractState.PRESALE_TWO) {
pricePerDemiGod = .1 ether;
maxTotalMint = 6000;
}
else if(currentState == ContractState.PUBLIC) {
pricePerDemiGod = .15 ether;
maxTotalMint = 9950;
}
}
function changeContractState(ContractState _state) external onlyOwner {
currentState = _state;
if(currentState == ContractState.PRESALE_ONE) {
pricePerDemiGod = .07 ether;
maxTotalMint = 2000;
}
else if(currentState == ContractState.PRESALE_TWO) {
pricePerDemiGod = .1 ether;
maxTotalMint = 6000;
}
else if(currentState == ContractState.PUBLIC) {
pricePerDemiGod = .15 ether;
maxTotalMint = 9950;
}
}
function claimDemiGods(uint256 _numberOfDemiGods, uint256 _maxMintAmount, bytes memory _signature) external payable nonReentrant{
require(
(currentState == ContractState.PRESALE_ONE ||
currentState == ContractState.PRESALE_TWO), "The whitelist is not active yet. Stay tuned.");
require(_numberOfDemiGods > 0, "You cannot mint 0 Demi Gods.");
require(SafeMath.add(_numMinted.current(), _numberOfDemiGods) <= maxTotalMint, "The entire presale has been sold. Check back for public mint.");
require(getNFTPrice(_numberOfDemiGods) <= msg.value, "Amount of Ether sent is not correct.");
require(_verify(msg.sender, _maxMintAmount, _signature), "This signature is not verified. You are not on the whitelist.");
require(SafeMath.add(addressMinted[msg.sender], _numberOfDemiGods) <= _maxMintAmount, "This amount exceeds the quantity you are allowed to mint during presale.");
for(uint i = 0; i < _numberOfDemiGods; i++){
uint256 tokenIndex = _tokenIdCounter.current();
_numMinted.increment();
_tokenIdCounter.increment();
addressMinted[msg.sender]++;
_safeMint(msg.sender, tokenIndex);
}
}
function claimDemiGods(uint256 _numberOfDemiGods, uint256 _maxMintAmount, bytes memory _signature) external payable nonReentrant{
require(
(currentState == ContractState.PRESALE_ONE ||
currentState == ContractState.PRESALE_TWO), "The whitelist is not active yet. Stay tuned.");
require(_numberOfDemiGods > 0, "You cannot mint 0 Demi Gods.");
require(SafeMath.add(_numMinted.current(), _numberOfDemiGods) <= maxTotalMint, "The entire presale has been sold. Check back for public mint.");
require(getNFTPrice(_numberOfDemiGods) <= msg.value, "Amount of Ether sent is not correct.");
require(_verify(msg.sender, _maxMintAmount, _signature), "This signature is not verified. You are not on the whitelist.");
require(SafeMath.add(addressMinted[msg.sender], _numberOfDemiGods) <= _maxMintAmount, "This amount exceeds the quantity you are allowed to mint during presale.");
for(uint i = 0; i < _numberOfDemiGods; i++){
uint256 tokenIndex = _tokenIdCounter.current();
_numMinted.increment();
_tokenIdCounter.increment();
addressMinted[msg.sender]++;
_safeMint(msg.sender, tokenIndex);
}
}
function mintDemiGods(uint256 _numberOfDemiGods) external payable nonReentrant{
require(currentState == ContractState.PUBLIC, "The public sale is not active yet. Stay Tuned.");
require(_numberOfDemiGods > 0, "You cannot mint 0 Demi Gods.");
require(_numberOfDemiGods <= MAX_PER_TRANSACTION, "You can only mint 15 Demi Gods per transaction.");
require(SafeMath.add(_numMinted.current(), _numberOfDemiGods) <= maxTotalMint, "Exceeds maximum supply.");
require(getNFTPrice(_numberOfDemiGods) <= msg.value, "Amount of Ether sent is not correct.");
for(uint i = 0; i < _numberOfDemiGods; i++){
uint256 tokenIndex = _tokenIdCounter.current();
_numMinted.increment();
_tokenIdCounter.increment();
_safeMint(msg.sender, tokenIndex);
}
}
function mintDemiGods(uint256 _numberOfDemiGods) external payable nonReentrant{
require(currentState == ContractState.PUBLIC, "The public sale is not active yet. Stay Tuned.");
require(_numberOfDemiGods > 0, "You cannot mint 0 Demi Gods.");
require(_numberOfDemiGods <= MAX_PER_TRANSACTION, "You can only mint 15 Demi Gods per transaction.");
require(SafeMath.add(_numMinted.current(), _numberOfDemiGods) <= maxTotalMint, "Exceeds maximum supply.");
require(getNFTPrice(_numberOfDemiGods) <= msg.value, "Amount of Ether sent is not correct.");
for(uint i = 0; i < _numberOfDemiGods; i++){
uint256 tokenIndex = _tokenIdCounter.current();
_numMinted.increment();
_tokenIdCounter.increment();
_safeMint(msg.sender, tokenIndex);
}
}
function airdropDemiGod(uint256 _numberOfDemiGods) external onlyOwner {
require(_numberOfDemiGods > 0, "You cannot mint 0 Demi Gods.");
require(SafeMath.add(_numAirdroped.current(), _numberOfDemiGods) <= AIRDROP_RESERVE, "Exceeds maximum airdrop reserve.");
for(uint i = 0; i < _numberOfDemiGods; i++){
uint256 tokenId = _tokenIdCounter.current();
_tokenIdCounter.increment();
_numAirdroped.increment();
_safeMint(msg.sender, tokenId);
}
}
function airdropDemiGod(uint256 _numberOfDemiGods) external onlyOwner {
require(_numberOfDemiGods > 0, "You cannot mint 0 Demi Gods.");
require(SafeMath.add(_numAirdroped.current(), _numberOfDemiGods) <= AIRDROP_RESERVE, "Exceeds maximum airdrop reserve.");
for(uint i = 0; i < _numberOfDemiGods; i++){
uint256 tokenId = _tokenIdCounter.current();
_tokenIdCounter.increment();
_numAirdroped.increment();
_safeMint(msg.sender, tokenId);
}
}
function getNFTPrice(uint256 _amount) public view returns (uint256) {
return SafeMath.mul(_amount, pricePerDemiGod);
}
function withdraw() external onlyOwner {
uint256 balance = address(this).balance;
Address.sendValue(payable(msg.sender), balance);
}
function setBaseURI(string memory uri) external onlyOwner {
baseURI = uri;
}
function _baseURI() internal view override returns (string memory) {
return baseURI;
}
}
| 13,538,482 |
[
1,
6119,
2525,
30,
3176,
49,
292,
10710,
14467,
1728,
16,
3784,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
27744,
77,
43,
369,
87,
984,
17488,
353,
4232,
39,
27,
5340,
3572,
25121,
16,
14223,
6914,
16,
868,
8230,
12514,
16709,
288,
203,
565,
1450,
7773,
19748,
364,
1731,
1578,
31,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
9354,
87,
364,
9354,
87,
18,
4789,
31,
203,
203,
565,
9354,
87,
18,
4789,
3238,
389,
2316,
548,
4789,
31,
203,
565,
9354,
87,
18,
4789,
3238,
389,
2107,
37,
6909,
1764,
329,
31,
203,
565,
9354,
87,
18,
4789,
3238,
389,
2107,
49,
474,
329,
31,
203,
377,
203,
565,
13456,
1119,
1071,
17773,
273,
13456,
1119,
18,
4066,
20093,
31,
203,
203,
377,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
1071,
1758,
49,
474,
329,
31,
7010,
203,
565,
2254,
5034,
1071,
6205,
2173,
15058,
77,
43,
369,
273,
263,
8642,
225,
2437,
31,
203,
565,
2254,
5034,
1071,
4552,
67,
3194,
67,
22364,
273,
1728,
31,
203,
203,
565,
533,
3238,
1026,
3098,
31,
203,
565,
533,
3238,
1573,
1444,
31,
203,
565,
1758,
3238,
10363,
31,
203,
203,
565,
3885,
12,
203,
3639,
533,
3778,
508,
16,
203,
3639,
533,
3778,
3273,
16,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
22,
31,
203,
565,
2792,
13456,
1119,
288,
15662,
20093,
16,
7071,
5233,
900,
67,
5998,
16,
7071,
5233,
900,
67,
18869,
51,
16,
17187,
289,
203,
3639,
533,
3778,
389,
1650,
16,
533,
3778,
389,
2977,
1444,
13,
4232,
39,
27,
5340,
12,
529,
16,
3273,
13,
288,
2
] |
./full_match/3/0xD6fF89773F9BBA1EbF80d621B1A7509Ad9773245/sources/contracts/bankofether.sol
|
20*24*60*60 = 30 days
|
panel_2[msg.sender].exp_time = now + 30 days;
| 8,168,154 |
[
1,
18212,
24,
4848,
4848,
225,
273,
5196,
4681,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
5411,
6594,
67,
22,
63,
3576,
18,
15330,
8009,
2749,
67,
957,
273,
2037,
397,
5196,
4681,
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
] |
/**
*Submitted for verification at Etherscan.io on 2021-09-06
*/
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: 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-FLATTEN-SUPPRESS-WARNING: MIT
pragma solidity ^0.8.0;
////import "./IERC20.sol";
////import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overloaded;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
pragma solidity ^0.8.0;
////import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
pragma solidity ^0.8.0;
interface IMinerV1{
function accountStoked(address addr) external view returns (uint256);
function totalStoke() external view returns (uint256);
function userTimes(address) external view returns (uint256);
function totalMineds( address ) external view returns (uint256);
// function current() external view returns (uint256);//private,don't call
function earnedBalance( address ) external view returns (uint256);
}
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
pragma solidity ^0.8.0;
////import '@openzeppelin/contracts/token/ERC20/ERC20.sol';
contract DEBIToken is ERC20 {
constructor() ERC20("DeerBit Token","DEBI") {
_mint(msg.sender, 100000000000 * 1e8);
}
function decimals() public pure override returns (uint8){
return 8;
}
}
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
pragma solidity ^0.8.0;
////import '@openzeppelin/contracts/token/ERC20/ERC20.sol';
////import "@openzeppelin/contracts/access/Ownable.sol";
// ////import './libraries/Strings.sol';
contract DBLendToken is ERC20,Ownable {
// using Strings for *;
/// @notice A record of each accounts delegate
mapping (address => address) public delegates;
address public miner;
address public timelock;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint256 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint256) 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);
constructor() ERC20("DBLend Line","DBL"){
_mint(msg.sender, 2100000*1e8);//Total 2100000 DBL
// timelock = _timelock;
//_delegate(address(this), address(this));
//numCheckpoints[address(this)] = 2100000*1e8;
}
function decimals() public pure override returns (uint8) {
return 8;
}
function totalSupply() public view override returns (uint256) {
return 2100000*1e8 - balanceOf(address(this));
}
///@dev init miner and approve miner transfer dbl
function initMiner(address _minerAddress) external onlyOwner returns (uint256){
require(miner == address(0), "DBL: INIT ONLY ONCE");
require(_minerAddress != address(0), "DBL: NOT VALID MINER");
return approveMiner(_minerAddress);
}
///@dev update timelock,if timelock has been set, only timelock can be call. Otherwise the owner can call.
function updateTimelock(address _timelock) external {
require((timelock == address(0) && msg.sender == owner()) || msg.sender == timelock, "NO PERMISSION");
require(_timelock != address(0),"INVALID ADDRESS");
timelock = _timelock;
}
///@dev replace miner through governance voting,if timelock is not set, the owner can operate.
function _setMiner(address _minerAddress) external {
require(msg.sender == timelock || (timelock == address(0) && msg.sender == owner()), "DBL: NEED TIMELOCK OR OWNER");
approveMiner(_minerAddress);
}
///@dev DBLToken contract approve Miner Contract to spend all dbl
function approveMiner(address _minerAddress) internal returns (uint256){
//////importance,prevent delegatecall attack
if(!isContract(_minerAddress)) return 0;
uint256 balance = balanceOf(address(this));
_approve(address(this), _minerAddress, 2100000 * 1e8);
miner = _minerAddress;
return balance;
}
///@dev Miner mint,actually transfer from address(this) to _account
function mint(address _account, uint256 _amount) public returns (bool){
require(msg.sender == miner, "DEL:ONLY MINER");
return transferFrom(address(this), _account, _amount);
}
///@dev DBL token can be transferred through governance voting
// function govTransfer(address _receipt, uint256 _amount) public returns (bool){
// require(msg.sender == timelock, "DBL:ONLY TIMELOCK");
// uint256 balance = balanceOf(address(this));
// if(_amount > balance) _amount = balance;
// return transferFrom(address(this), _account, _amount);
// }
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;
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
if(recipient == address(this)){
recipient = address(0);
}
_moveDelegates(delegates[_msgSender()], delegates[recipient], amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = allowance(sender,_msgSender());
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
//如果是挖矿铸币,则src为0,不需要记录本地的投票数据
if(sender == address(this)){
sender = address(0);
}
_moveDelegates(delegates[sender], delegates[recipient], amount);
return true;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public returns (address){
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), "DBL::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "DBL::delegateBySig: invalid nonce");
require(block.timestamp <= expiry, "DBL::delegateBySig: signature expired");
_delegate(signatory, delegatee);
return signatory;
}
/**
* @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 (uint256) {
uint256 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 (uint256) {
require(blockNumber < block.number, "DBL::getPriorVotes: not yet determined");
uint256 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;
}
uint256 lower = 0;
uint256 upper = nCheckpoints - 1;
while (upper > lower) {
uint256 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];
uint256 delegatorBalance = balanceOf(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), "DBL::_transferTokens: cannot transfer from the zero address");
// require(dst != address(0), "DBL::_transferTokens: cannot transfer to the zero address");
// balances[src] = sub96(balances[src], amount, "DBL::_transferTokens: transfer amount exceeds balance");
// balances[dst] = add96(balances[dst], amount, "DBL::_transferTokens: transfer amount overflows");
// emit Transfer(src, dst, amount);
// _moveDelegates(delegates[src], delegates[dst], amount);
// }
//转移投票权,减少原代理地址的票数,增加到新代理地址的票数,票数跟balance相关
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint256 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld - amount;
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint256 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld + amount;
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee, uint256 nCheckpoints, uint256 oldVotes, uint256 newVotes) internal {
uint32 blockNumber = safe32(block.number, "DBL::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal view returns (uint256) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
pragma solidity ^0.8.0;
////import './DBLendToken.sol';
////import './DEBIToken.sol';
////import './interfaces/IMinerV1.sol';
// ////import './libraries/Strings.sol';
contract Miner is Ownable{
// using Strings for *;
address public immutable DBL; // DBL地址,部署时传入,不可修改
address public immutable DIBI; // DIBI地址,部署时传入,不可修改
uint256 public constant FIREST_YEAR_DBL = 1050000 * 1e8 * 1e18; // 首年产出DBL,逐年减半(1e18:为了避免分配到每区块时dibi时出现的小数)
uint256 public immutable DEPLOY_BLOCK;// = 10957872;// 合约发布时间
uint public constant blocksPerYear = 2102400;//按照平均15秒/区块,每年区块数
//指定timelock为admin,timelock执行投票通过的业务,修改Miner相关数据
address public admin;
address public pendingAdmin;
//用户质押DIBI每币能够收获的DBL数目perDibiSharedDbl。该数据从0开始,累加所有区块区间的每DIBI能生产的DBL数量
//同一区块,质押数第一次产生变化前,要更新当前每币产出perDibiSharedDbl
//用户收获铸币时,需要提前更新每币产出perDibiSharedDbl,收获完成后,更新用户债务:harvestDebt
//用户收获数目 = block.number- STAKER.lastHarvestBlock
uint256 public perDibiSharedDbl = 0;
uint256 public latestCalTime = 0; //最近一次计算perDibiSharedDbl区块时间,第一次质押时初始化
uint256 public latestBlockNum = 0;
uint256 public totalStaked = 0; // 所有质押的DIBI数量
//The Pause Guardian can pause certain actions as a safety mechanism.
bool public rewardGuardianPaused = false;
bool public stakeGuardianPaused = false;
struct STAKER{
uint256 stakeBalance; // 用户当前质押余额
uint256 lastHarvestBlock; // 最后一次收获时间
uint256 harvestDebt; // 收获时需要扣减的债务
uint256 rewardPending; // 等待收获的数量
}
mapping(address=>STAKER) public stakers; // 所有质押者
event Stake(address indexed staker,uint256 amounts, uint256 earned);
event Harvest(address indexed harver,uint256 earned);
/// @notice Emitted when an action is paused globally
event ActionPaused(string action, bool pauseState);
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
event NewAdmin(address oldAdmin, address newAdmin);
constructor(address _dbl, address _dibi, uint256 _deploy_block){
require(_dbl != address(0) && _dibi != address(0),"INVALID ADDRESS");
DBL = _dbl;
DIBI = _dibi;
DEPLOY_BLOCK = _deploy_block;
admin = msg.sender;
}
///@dev 质押前,计算最新每币产出,并对当前用户进行收获,
function stake(uint256 _amount) external {
// Pausing is a very serious situation - we revert to sound the alarms
require(!rewardGuardianPaused && !stakeGuardianPaused, "STAKE_OR_REWARD IS PAUSED");
require(_amount > 0,"AMOUNT MUST > 0");
require(DEBIToken(DIBI).balanceOf(msg.sender) >= _amount, "INSUFFICIENT DIBI");
STAKER storage staker = stakers[msg.sender];
//因为质押总数会改变,所以要计算出之前这段时间的每币产出
_calPerDibiSharedDbl();
uint256 earned = 0;
//质押的用户stake需要先收获一次
if(staker.stakeBalance>0){
earned = ( perDibiSharedDbl * (staker.stakeBalance) - staker.harvestDebt ) / 1e18;
if(earned>0 && earned!=2**256-1){
staker.rewardPending = staker.rewardPending + earned;
// DBLendToken(DBL).mint(msg.sender,earned);
}
staker.lastHarvestBlock = block.number;
}
// require(1==2,"1222222");
//收获完成后,首先转账dibi,再修改数据状态
DEBIToken(DIBI).transferFrom(msg.sender,address(this),_amount);
if(totalStaked==0) latestBlockNum=block.number;
totalStaked += _amount;
//更新用户质押状态
staker.stakeBalance += _amount;
staker.harvestDebt = perDibiSharedDbl * staker.stakeBalance;
emit Stake(msg.sender, _amount,earned);
}
///@dev 取出DIBI
function withdraw(uint256 _amount) public {
require(stakers[msg.sender].stakeBalance >= _amount,"DBL: INSUFFICIENT DIBI");
STAKER storage staker = stakers[msg.sender];
//如果有区块间隔,先计算收获
if(block.number > staker.lastHarvestBlock){
// harvest();
//更新每质押DIBI产出数
_calPerDibiSharedDbl();
uint256 earned = ( perDibiSharedDbl * (staker.stakeBalance) - staker.harvestDebt ) / 1e18;
if(earned>0 && earned!=2**256-1){
staker.rewardPending = staker.rewardPending + earned;
}
staker.lastHarvestBlock = block.number;
}
//先改变状态,再转账
staker.stakeBalance -= _amount;
staker.harvestDebt = staker.stakeBalance * perDibiSharedDbl;
totalStaked -= _amount;
DEBIToken(DIBI).transfer(msg.sender, _amount);
}
///@dev 退出质押。先收获,再退出DIBI
function unStake() external {
require(stakers[msg.sender].stakeBalance>0,"DBL: INSUFFICIENT DIBI STAKE");
harvest();
withdraw(stakers[msg.sender].stakeBalance);
}
//主动用户收获,铸币,在stake、unstake、harvest时发生
function harvest() public returns(uint256 earned){
require(stakers[msg.sender].stakeBalance > 0 || stakers[msg.sender].rewardPending > 0, "DBL: INSUFFICIENT STAKE OR REWARD");
require(block.number > stakers[msg.sender].lastHarvestBlock,"DBL: REPEAT HARVEST");
//更新每质押DIBI产出数
_calPerDibiSharedDbl();
STAKER storage staker = stakers[msg.sender];
//收获数量 = 质押代币 * 每币收获 / DIBI精度 - 用户扣减数
earned = ( staker.stakeBalance * perDibiSharedDbl - staker.harvestDebt ) / 1e18;
//铸币
if(staker.rewardPending >0 || earned>0){
//首先更改状态,避免铸币后状态未修改的攻击
staker.lastHarvestBlock = block.number;
staker.harvestDebt = staker.stakeBalance * perDibiSharedDbl;
earned = staker.rewardPending + earned;
staker.rewardPending = 0;
DBLendToken(DBL).mint(msg.sender,earned);
emit Harvest(msg.sender, earned);
}
}
///@dev 计算当前时间段DIBI每币产出,并把当前时间段的每币产出累加。并更新最近计算时间
function _calPerDibiSharedDbl() internal{
uint256 incDblPerDIBI = _calPerDibiIncDbl();
if(incDblPerDIBI > 0){
//如果被禁止产出,则关闭产量增加的逻辑。恢复后,所有产量正常恢复
if(!rewardGuardianPaused){
perDibiSharedDbl += incDblPerDIBI;
latestBlockNum = block.number;
}
}
}
///@dev 时间区段新增的每币产出
function _calPerDibiIncDbl() internal view returns (uint256 incDblPerDIBI){
incDblPerDIBI = 0;
//如果被暂停,则不再增加区块产出
if(rewardGuardianPaused) return incDblPerDIBI;
//只要时间变化了,也就是区块增加了,就不能跳过计算;如果质押变化,但区块没有改变,也不需要计算
//if(block.timestamp > latestCalTime && totalStaked>0){
if(block.number > latestBlockNum && totalStaked>0){
uint256 current = currentYearDibi();//当年产量总和
//新增产量 = 间隔时间段 * (当前年产/365天总秒数)
uint256 increaseDbl = ( block.number - latestBlockNum ) * current / blocksPerYear ;
//每币新增产量 = 新增总量 / 总质押DIBI数
incDblPerDIBI = increaseDbl / totalStaked;
}
return incDblPerDIBI;
}
///@dev 计算当前年度的DIBI产出。第一年=FIREST_YEAR_DBL,以后逐年减半
function currentYearDibi() public view returns (uint256 current){
current = FIREST_YEAR_DBL;
// if(block.timestamp > START_TIME){
if(block.number > DEPLOY_BLOCK){
uint256 severalYears = (block.number - DEPLOY_BLOCK) / blocksPerYear; // 过几年 = 发布时间长/365
if (severalYears > 0) {
current = FIREST_YEAR_DBL / (2 * severalYears); // 当年总产量 = 首年总产量 / (2*几年)
}
}
}
///@dev 查看指定用户可以收获的数量
///@param user 指定用户
function earnedBalance(address user) external view returns(uint256){
//首先计算当前未更新perDibiSharedDbl时间段的产出,但不更新状态,因而无需gas
uint256 _perDibiIncDbl = _calPerDibiIncDbl();
return stakers[user].rewardPending + ( ( perDibiSharedDbl + _perDibiIncDbl ) * stakers[user].stakeBalance - stakers[user].harvestDebt ) / 1e18;
}
///@dev 查看指定用户质押DIBI数量
///@param user 指定用户
function getAmountStakedByAddr(address user) external view returns(uint256){
return stakers[user].stakeBalance;
}
///old methods
function accountStoked(address addr) external view returns (uint256) {
return stakers[addr].stakeBalance;
}
function balanceOf(address _account) external view returns (uint256){
return DBLendToken(DBL).balanceOf(_account);
}
function setRewardPaused(bool state) external onlyOwner returns (bool) {
if(state){
_calPerDibiSharedDbl();
}
rewardGuardianPaused = state;
emit ActionPaused("Reward", state);
return state;
}
function setStakePaused(bool state) external onlyOwner returns (bool) {
stakeGuardianPaused = state;
emit ActionPaused("Stake", state);
return state;
}
function _setPendingAdmin(address _pendingAdming) external {
require(msg.sender == admin && _pendingAdming != address(0),"Miner::Only Admin Allown");
address oldPendingAdmin = pendingAdmin;
pendingAdmin = _pendingAdming;
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
}
function _acceptAdmin() external {
require(msg.sender == pendingAdmin, "Miner::Must PendingAdmin");
address oldAdmin = admin;
admin = pendingAdmin;
pendingAdmin=address(0);
emit NewAdmin(oldAdmin,admin);
}
}
|
@dev 计算当前时间段DIBI每币产出,并把当前时间段的每币产出累加。并更新最近计算时间如果被禁止产出,则关闭产量增加的逻辑。恢复后,所有产量正常恢复
|
function _calPerDibiSharedDbl() internal{
uint256 incDblPerDIBI = _calPerDibiIncDbl();
if(incDblPerDIBI > 0){
if(!rewardGuardianPaused){
perDibiSharedDbl += incDblPerDIBI;
latestBlockNum = block.number;
}
}
}
| 6,545,972 |
[
1,
169,
111,
99,
168,
111,
250,
166,
126,
246,
166,
236,
240,
167,
250,
119,
170,
250,
117,
167,
111,
118,
2565,
31558,
167,
112,
242,
166,
121,
228,
165,
123,
105,
166,
234,
123,
16,
166,
122,
119,
167,
237,
237,
166,
126,
246,
166,
236,
240,
167,
250,
119,
170,
250,
117,
167,
111,
118,
168,
253,
231,
167,
112,
242,
166,
121,
228,
165,
123,
105,
166,
234,
123,
168,
117,
112,
166,
237,
259,
164,
227,
229,
166,
122,
119,
167,
254,
117,
167,
249,
113,
167,
255,
227,
169,
128,
244,
169,
111,
99,
168,
111,
250,
167,
250,
119,
170,
250,
117,
166,
104,
229,
167,
257,
255,
169,
100,
109,
168,
104,
228,
167,
260,
100,
165,
123,
105,
166,
234,
123,
176,
125,
239,
166,
235,
252,
166,
232,
116,
170,
250,
260,
165,
123,
105,
170,
234,
242,
166,
2
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
[
1,
565,
445,
389,
771,
2173,
40,
495,
77,
7887,
40,
3083,
1435,
2713,
95,
203,
3639,
2254,
5034,
7290,
40,
3083,
2173,
2565,
31558,
273,
389,
771,
2173,
40,
495,
77,
14559,
40,
3083,
5621,
203,
3639,
309,
12,
9523,
40,
3083,
2173,
2565,
31558,
405,
374,
15329,
203,
5411,
309,
12,
5,
266,
2913,
16709,
2779,
28590,
15329,
203,
7734,
1534,
40,
495,
77,
7887,
40,
3083,
1011,
7290,
40,
3083,
2173,
2565,
31558,
31,
203,
7734,
4891,
1768,
2578,
273,
1203,
18,
2696,
31,
203,
5411,
289,
203,
2398,
203,
3639,
289,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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 Owned {
address public owner;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner returns (address account) {
owner = newOwner;
return owner;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
function sub(uint a, uint b) internal pure returns (uint c) {
require(b <= a);
c = a - b;
}
function mul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function div(uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
contract ERC20 {
function totalSupply() public constant returns (uint256);
function balanceOf(address tokenOwner) public constant returns (uint256 balance);
function allowance(address tokenOwner, address spender) public constant returns (uint256 remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint256 tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens);
}
contract CSTKDropToken is ERC20, Owned {
using SafeMath for uint256;
string public symbol;
string public name;
uint256 public decimals;
uint256 _totalSupply;
bool public started;
address public token;
struct Level {
uint256 price;
uint256 available;
}
Level[] levels;
mapping(address => uint256) balances;
mapping(address => mapping(string => uint256)) orders;
event TransferETH(address indexed from, address indexed to, uint256 eth);
event Sell(address indexed to, uint256 tokens, uint256 eth);
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor(string _symbol, string _name, uint256 _supply, uint256 _decimals, address _token) public {
symbol = _symbol;
name = _name;
decimals = _decimals;
token = _token;
_totalSupply = _supply;
balances[owner] = _totalSupply;
started = false;
emit Transfer(address(0), owner, _totalSupply);
}
function destruct() public onlyOwner {
ERC20 tokenInstance = ERC20(token);
uint256 balance = tokenInstance.balanceOf(this);
if (balance > 0) {
tokenInstance.transfer(owner, balance);
}
selfdestruct(owner);
}
// ------------------------------------------------------------------------
// Changes the address of the supported token
// ------------------------------------------------------------------------
function setToken(address newTokenAddress) public onlyOwner returns (bool success) {
token = newTokenAddress;
return true;
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public view returns (uint256) {
return _totalSupply.sub(balances[address(0)]);
}
// ------------------------------------------------------------------------
// Changes the total supply value
//
// a new supply must be no less then the current supply
// or the owner must have enough amount to cover supply reduction
// ------------------------------------------------------------------------
function changeTotalSupply(uint256 newSupply) public onlyOwner returns (bool success) {
require(newSupply >= 0 && (
newSupply >= _totalSupply || _totalSupply - newSupply <= balances[owner]
));
uint256 diff = 0;
if (newSupply >= _totalSupply) {
diff = newSupply.sub(_totalSupply);
balances[owner] = balances[owner].add(diff);
emit Transfer(address(0), owner, diff);
} else {
diff = _totalSupply.sub(newSupply);
balances[owner] = balances[owner].sub(diff);
emit Transfer(owner, address(0), diff);
}
_totalSupply = newSupply;
return true;
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public view returns (uint256 balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Start accept orders
// ------------------------------------------------------------------------
function start() public onlyOwner {
started = true;
}
// ------------------------------------------------------------------------
// Start accept orders
// ------------------------------------------------------------------------
function stop() public onlyOwner {
started = false;
}
// ------------------------------------------------------------------------
// Adds new Level to the levels array
// ------------------------------------------------------------------------
function addLevel(uint256 price, uint256 available) public onlyOwner {
levels.push(Level(price, available));
}
// ------------------------------------------------------------------------
// Removes a level with specified price from the levels array
// ------------------------------------------------------------------------
function removeLevel(uint256 price) public onlyOwner {
if (levels.length < 1) {
return;
}
Level[] memory tmp = levels;
delete levels;
for (uint i = 0; i < tmp.length; i++) {
if (tmp[i].price != price) {
levels.push(tmp[i]);
}
}
}
// ------------------------------------------------------------------------
// Replaces a particular level index by a new Level values
// ------------------------------------------------------------------------
function replaceLevel(uint index, uint256 price, uint256 available) public onlyOwner {
levels[index] = Level(price, available);
}
// ------------------------------------------------------------------------
// Clears the levels array
// ------------------------------------------------------------------------
function clearLevels() public onlyOwner {
delete levels;
}
// ------------------------------------------------------------------------
// Finds a level with specified price and returns an amount of available tokens on the level
// ------------------------------------------------------------------------
function getLevelAmount(uint256 price) public view returns (uint256 available) {
if (levels.length < 1) {
return 0;
}
for (uint i = 0; i < levels.length; i++) {
if (levels[i].price == price) {
return levels[i].available;
}
}
}
// ------------------------------------------------------------------------
// Returns a Level by it's array index
// ------------------------------------------------------------------------
function getLevelByIndex(uint index) public view returns (uint256 price, uint256 available) {
price = levels[index].price;
available = levels[index].available;
}
// ------------------------------------------------------------------------
// Returns a count of levels
// ------------------------------------------------------------------------
function getLevelsCount() public view returns (uint) {
return levels.length;
}
// ------------------------------------------------------------------------
// Returns a Level by it's array index
// ------------------------------------------------------------------------
function getCurrentLevel() public view returns (uint256 price, uint256 available) {
if (levels.length < 1) {
return;
}
for (uint i = 0; i < levels.length; i++) {
if (levels[i].available > 0) {
price = levels[i].price;
available = levels[i].available;
break;
}
}
}
// ------------------------------------------------------------------------
// Get the order's balance of tokens for account `customer`
// ------------------------------------------------------------------------
function orderTokensOf(address customer) public view returns (uint256 balance) {
return orders[customer]['tokens'];
}
// ------------------------------------------------------------------------
// Get the order's balance of ETH for account `customer`
// ------------------------------------------------------------------------
function orderEthOf(address customer) public view returns (uint256 balance) {
return orders[customer]['eth'];
}
// ------------------------------------------------------------------------
// Delete customer's order
// ------------------------------------------------------------------------
function cancelOrder(address customer) public onlyOwner returns (bool success) {
orders[customer]['eth'] = 0;
orders[customer]['tokens'] = 0;
return true;
}
// ------------------------------------------------------------------------
// Checks the order values by the customer's address and sends required
// promo tokens based on the received amount of `this` tokens and ETH
// ------------------------------------------------------------------------
function _checkOrder(address customer) private returns (uint256 tokens, uint256 eth) {
require(started);
eth = 0;
tokens = 0;
if (getLevelsCount() <= 0 || orders[customer]['tokens'] <= 0 || orders[customer]['eth'] <= 0) {
return;
}
ERC20 tokenInstance = ERC20(token);
uint256 balance = tokenInstance.balanceOf(this);
uint256 orderEth = orders[customer]['eth'];
uint256 orderTokens = orders[customer]['tokens'] > balance ? balance : orders[customer]['tokens'];
for (uint i = 0; i < levels.length; i++) {
if (levels[i].available <= 0) {
continue;
}
uint256 _tokens = (10**decimals) * orderEth / levels[i].price;
// check if there enough tokens on the level
if (_tokens > levels[i].available) {
_tokens = levels[i].available;
}
// check the order tokens limit
if (_tokens > orderTokens) {
_tokens = orderTokens;
}
uint256 _eth = _tokens * levels[i].price / (10**decimals);
levels[i].available -= _tokens;
// accumulate total price and tokens
eth += _eth;
tokens += _tokens;
// reduce remaining limits
orderEth -= _eth;
orderTokens -= _tokens;
if (orderEth <= 0 || orderTokens <= 0 || levels[i].available > 0) {
// order is calculated
break;
}
}
// charge required amount of the tokens and ETHs
orders[customer]['tokens'] = orders[customer]['tokens'].sub(tokens);
orders[customer]['eth'] = orders[customer]['eth'].sub(eth);
tokenInstance.transfer(customer, tokens);
emit Sell(customer, tokens, eth);
}
// ------------------------------------------------------------------------
// public entry point for the `_checkOrder` function
// ------------------------------------------------------------------------
function checkOrder(address customer) public onlyOwner returns (uint256 tokens, uint256 eth) {
return _checkOrder(customer);
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// - only owner is allowed to send tokens to any address
// - not owners can transfer the balance only to owner's address
// ------------------------------------------------------------------------
function transfer(address to, uint256 tokens) public returns (bool success) {
require(msg.sender == owner || to == owner || to == address(this));
address receiver = msg.sender == owner ? to : owner;
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[receiver] = balances[receiver].add(tokens);
emit Transfer(msg.sender, receiver, tokens);
if (receiver == owner) {
orders[msg.sender]['tokens'] = orders[msg.sender]['tokens'].add(tokens);
_checkOrder(msg.sender);
}
return true;
}
// ------------------------------------------------------------------------
// `allowance` is not allowed
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint256 remaining) {
tokenOwner;
spender;
return uint256(0);
}
// ------------------------------------------------------------------------
// `approve` is not allowed
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
spender;
tokens;
return true;
}
// ------------------------------------------------------------------------
// `transferFrom` is not allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint256 tokens) public returns (bool success) {
from;
to;
tokens;
return true;
}
// ------------------------------------------------------------------------
// Accept ETH
// ------------------------------------------------------------------------
function () public payable {
owner.transfer(msg.value);
emit TransferETH(msg.sender, address(this), msg.value);
orders[msg.sender]['eth'] = orders[msg.sender]['eth'].add(msg.value);
_checkOrder(msg.sender);
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint256 tokens) public onlyOwner returns (bool success) {
return ERC20(tokenAddress).transfer(owner, tokens);
}
// ------------------------------------------------------------------------
// Owner can transfer out promo token
// ------------------------------------------------------------------------
function transferToken(uint256 tokens) public onlyOwner returns (bool success) {
return transferAnyERC20Token(token, tokens);
}
// ------------------------------------------------------------------------
// Owner can return specified amount from `tokenOwner`
// ------------------------------------------------------------------------
function returnFrom(address tokenOwner, uint256 tokens) public onlyOwner returns (bool success) {
balances[tokenOwner] = balances[tokenOwner].sub(tokens);
balances[owner] = balances[owner].add(tokens);
emit Transfer(tokenOwner, owner, tokens);
return true;
}
// ------------------------------------------------------------------------
// Owner can return all tokens from `tokenOwner`
// ------------------------------------------------------------------------
function nullifyFrom(address tokenOwner) public onlyOwner returns (bool success) {
return returnFrom(tokenOwner, balances[tokenOwner]);
}
}
contract CSTK_CLT is CSTKDropToken('CSTK_CLT', 'CryptoStock CLT Promo Token', 100000 * 10**8, 8, 0x2001f2A0Cf801EcFda622f6C28fb6E10d803D969) {
}
|
------------------------------------------------------------------------ Total supply ------------------------------------------------------------------------
|
function totalSupply() public view returns (uint256) {
return _totalSupply.sub(balances[address(0)]);
}
| 1,430,030 |
[
1,
29461,
10710,
14467,
8879,
17082,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
445,
2078,
3088,
1283,
1435,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
565,
327,
389,
4963,
3088,
1283,
18,
1717,
12,
70,
26488,
63,
2867,
12,
20,
13,
19226,
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
] |
pragma solidity ^0.4.24;
/*
ETHEREUM WORLD CUP : 14th June - 15th July 2018 [Russia]
- designed and implemented by Norsefire.
- thanks to Etherguy and oguzhanox for debugging and front-end respectively.
Rules are as follows:
* Entry to the game costs 0.2018 Ether. Use the register function when sending this.
- Any larger or smaller amount of Ether, will be rejected.
* 90% of the entry fee will go towards the prize fund, with 10% forming a fee.
Of this fee, half goes to the developer, and half goes directly to Giveth (giveth.io/donate).
The entry fee is the only Ether you will need to send for the duration of the
tournament, barring the gas you spend for placing predictions.
* Buying an entry allows the sender to place predictions on each game in the World Cup,
barring those which have already kicked off prior to the time a participant enters.
* Predictions can be made (or changed!) at any point up until the indicated kick-off time.
* Selecting the correct result for any given game awards the player one point.
In the first stage, a participant can also select a draw. This is not available from the RO16 onwards.
* If a participant reaches a streak of three or more correct predictions in a row, they receive two points
for every correct prediction from the third game until the streak is broken.
* If a participant reaches a streak of *five* or more correct predictions in a row, they receive four points
for every correct prediction from the fifth game until the streak is broken.
* In the event of a tie, the following algorithm is used to decide rankings:
- Compare the sum totals of the scores over the last 32 games.
- If this produces a draw as well, compare results of the last 16 games.
- This repeats until comparing the results of the final.
- If it's a dead heat throughout, a coin-flip (or some equivalent method) will be used to determine the winner.
Prizes:
FIRST PLACE: 40% of Ether contained within the pot.
SECOND PLACE: 30% of Ether contained within the pot.
THIRD PLACE: 20% of Ether contained within the pot.
FOURTH PLACE: 10% of Ether contained within the pot.
Participant Teams and Groups:
[Group D] AR - Argentina
[Group C] AU - Australia
[Group G] BE - Belgium
[Group E] BR - Brazil
[Group E] CH - Switzerland
[Group H] CO - Colombia
[Group E] CR - Costa Rica
[Group E] CS - Serbia
[Group F] DE - Germany
[Group C] DK - Denmark
[Group A] EG - Egypt
[Group G] EN - England
[Group B] ES - Spain
[Group C] FR - France
[Group D] HR - Croatia
[Group B] IR - Iran
[Group D] IS - Iceland
[Group H] JP - Japan
[Group F] KR - Republic of Korea
[Group B] MA - Morocco
[Group F] MX - Mexico
[Group D] NG - Nigeria
[Group G] PA - Panama
[Group C] PE - Peru
[Group H] PL - Poland
[Group B] PT - Portugal
[Group A] RU - Russia
[Group A] SA - Saudi Arabia
[Group F] SE - Sweden
[Group H] SN - Senegal
[Group G] TN - Tunisia
[Group A] UY - Uruguay
*/
contract EtherWorldCup {
using SafeMath for uint;
/* CONSTANTS */
address internal constant administrator = 0x4F4eBF556CFDc21c3424F85ff6572C77c514Fcae;
address internal constant givethAddress = 0x5ADF43DD006c6C36506e2b2DFA352E60002d22Dc;
string name = "EtherWorldCup";
string symbol = "EWC";
/* VARIABLES */
mapping (string => int8) worldCupGameID;
mapping (int8 => bool) gameFinished;
// Is a game no longer available for predictions to be made?
mapping (int8 => uint) gameLocked;
// A result is either the two digit code of a country, or the word "DRAW".
// Country codes are listed above.
mapping (int8 => string) gameResult;
int8 internal latestGameFinished;
uint internal prizePool;
uint internal givethPool;
int registeredPlayers;
mapping (address => bool) playerRegistered;
mapping (address => mapping (int8 => bool)) playerMadePrediction;
mapping (address => mapping (int8 => string)) playerPredictions;
mapping (address => int8[64]) playerPointArray;
mapping (address => int8) playerGamesScored;
mapping (address => uint) playerStreak;
address[] playerList;
/* DEBUG EVENTS */
event Registration(
address _player
);
event PlayerLoggedPrediction(
address _player,
int _gameID,
string _prediction
);
event PlayerUpdatedScore(
address _player,
int _lastGamePlayed
);
event Comparison(
address _player,
uint _gameID,
string _myGuess,
string _result,
bool _correct
);
event PlayerPointGain(
address _player,
uint _gameID,
uint _streak,
uint _points
);
event StartAutoScoring(
address _player
);
event StartScoring(
address _player,
uint _gameID
);
event DidNotPredict(
address _player,
uint _gameID
);
event RipcordRefund(
address _player
);
/* CONSTRUCTOR */
constructor ()
public
{
// First stage games: these are known in advance.
// Thursday 14th June, 2018
worldCupGameID["RU-SA"] = 1; // Russia vs Saudi Arabia
gameLocked[1] = 1528988400;
// Friday 15th June, 2018
worldCupGameID["EG-UY"] = 2; // Egypt vs Uruguay
worldCupGameID["MA-IR"] = 3; // Morocco vs Iran
worldCupGameID["PT-ES"] = 4; // Portugal vs Spain
gameLocked[2] = 1529064000;
gameLocked[3] = 1529074800;
gameLocked[4] = 1529085600;
// Saturday 16th June, 2018
worldCupGameID["FR-AU"] = 5; // France vs Australia
worldCupGameID["AR-IS"] = 6; // Argentina vs Iceland
worldCupGameID["PE-DK"] = 7; // Peru vs Denmark
worldCupGameID["HR-NG"] = 8; // Croatia vs Nigeria
gameLocked[5] = 1529143200;
gameLocked[6] = 1529154000;
gameLocked[7] = 1529164800;
gameLocked[8] = 1529175600;
// Sunday 17th June, 2018
worldCupGameID["CR-CS"] = 9; // Costa Rica vs Serbia
worldCupGameID["DE-MX"] = 10; // Germany vs Mexico
worldCupGameID["BR-CH"] = 11; // Brazil vs Switzerland
gameLocked[9] = 1529236800;
gameLocked[10] = 1529247600;
gameLocked[11] = 1529258400;
// Monday 18th June, 2018
worldCupGameID["SE-KR"] = 12; // Sweden vs Korea
worldCupGameID["BE-PA"] = 13; // Belgium vs Panama
worldCupGameID["TN-EN"] = 14; // Tunisia vs England
gameLocked[12] = 1529323200;
gameLocked[13] = 1529334000;
gameLocked[14] = 1529344800;
// Tuesday 19th June, 2018
worldCupGameID["CO-JP"] = 15; // Colombia vs Japan
worldCupGameID["PL-SN"] = 16; // Poland vs Senegal
worldCupGameID["RU-EG"] = 17; // Russia vs Egypt
gameLocked[15] = 1529409600;
gameLocked[16] = 1529420400;
gameLocked[17] = 1529431200;
// Wednesday 20th June, 2018
worldCupGameID["PT-MA"] = 18; // Portugal vs Morocco
worldCupGameID["UR-SA"] = 19; // Uruguay vs Saudi Arabia
worldCupGameID["IR-ES"] = 20; // Iran vs Spain
gameLocked[18] = 1529496000;
gameLocked[19] = 1529506800;
gameLocked[20] = 1529517600;
// Thursday 21st June, 2018
worldCupGameID["DK-AU"] = 21; // Denmark vs Australia
worldCupGameID["FR-PE"] = 22; // France vs Peru
worldCupGameID["AR-HR"] = 23; // Argentina vs Croatia
gameLocked[21] = 1529582400;
gameLocked[22] = 1529593200;
gameLocked[23] = 1529604000;
// Friday 22nd June, 2018
worldCupGameID["BR-CR"] = 24; // Brazil vs Costa Rica
worldCupGameID["NG-IS"] = 25; // Nigeria vs Iceland
worldCupGameID["CS-CH"] = 26; // Serbia vs Switzerland
gameLocked[24] = 1529668800;
gameLocked[25] = 1529679600;
gameLocked[26] = 1529690400;
// Saturday 23rd June, 2018
worldCupGameID["BE-TN"] = 27; // Belgium vs Tunisia
worldCupGameID["KR-MX"] = 28; // Korea vs Mexico
worldCupGameID["DE-SE"] = 29; // Germany vs Sweden
gameLocked[27] = 1529755200;
gameLocked[28] = 1529766000;
gameLocked[29] = 1529776800;
// Sunday 24th June, 2018
worldCupGameID["EN-PA"] = 30; // England vs Panama
worldCupGameID["JP-SN"] = 31; // Japan vs Senegal
worldCupGameID["PL-CO"] = 32; // Poland vs Colombia
gameLocked[30] = 1529841600;
gameLocked[31] = 1529852400;
gameLocked[32] = 1529863200;
// Monday 25th June, 2018
worldCupGameID["UR-RU"] = 33; // Uruguay vs Russia
worldCupGameID["SA-EG"] = 34; // Saudi Arabia vs Egypt
worldCupGameID["ES-MA"] = 35; // Spain vs Morocco
worldCupGameID["IR-PT"] = 36; // Iran vs Portugal
gameLocked[33] = 1529935200;
gameLocked[34] = 1529935200;
gameLocked[35] = 1529949600;
gameLocked[36] = 1529949600;
// Tuesday 26th June, 2018
worldCupGameID["AU-PE"] = 37; // Australia vs Peru
worldCupGameID["DK-FR"] = 38; // Denmark vs France
worldCupGameID["NG-AR"] = 39; // Nigeria vs Argentina
worldCupGameID["IS-HR"] = 40; // Iceland vs Croatia
gameLocked[37] = 1530021600;
gameLocked[38] = 1530021600;
gameLocked[39] = 1530036000;
gameLocked[40] = 1530036000;
// Wednesday 27th June, 2018
worldCupGameID["KR-DE"] = 41; // Korea vs Germany
worldCupGameID["MX-SE"] = 42; // Mexico vs Sweden
worldCupGameID["CS-BR"] = 43; // Serbia vs Brazil
worldCupGameID["CH-CR"] = 44; // Switzerland vs Costa Rica
gameLocked[41] = 1530108000;
gameLocked[42] = 1530108000;
gameLocked[43] = 1530122400;
gameLocked[44] = 1530122400;
// Thursday 28th June, 2018
worldCupGameID["JP-PL"] = 45; // Japan vs Poland
worldCupGameID["SN-CO"] = 46; // Senegal vs Colombia
worldCupGameID["PA-TN"] = 47; // Panama vs Tunisia
worldCupGameID["EN-BE"] = 48; // England vs Belgium
gameLocked[45] = 1530194400;
gameLocked[46] = 1530194400;
gameLocked[47] = 1530208800;
gameLocked[48] = 1530208800;
// Second stage games and onwards. The string values for these will be overwritten
// as the tournament progresses. This is the order that will be followed for the
// purposes of calculating winning streaks, as per the World Cup website.
// Round of 16
// Saturday 30th June, 2018
worldCupGameID["1C-2D"] = 49; // 1C vs 2D
worldCupGameID["1A-2B"] = 50; // 1A vs 2B
gameLocked[49] = 1530367200;
gameLocked[50] = 1530381600;
// Sunday 1st July, 2018
worldCupGameID["1B-2A"] = 51; // 1B vs 2A
worldCupGameID["1D-2C"] = 52; // 1D vs 2C
gameLocked[51] = 1530453600;
gameLocked[52] = 1530468000;
// Monday 2nd July, 2018
worldCupGameID["1E-2F"] = 53; // 1E vs 2F
worldCupGameID["1G-2H"] = 54; // 1G vs 2H
gameLocked[53] = 1530540000;
gameLocked[54] = 1530554400;
// Tuesday 3rd July, 2018
worldCupGameID["1F-2E"] = 55; // 1F vs 2E
worldCupGameID["1H-2G"] = 56; // 1H vs 2G
gameLocked[55] = 1530626400;
gameLocked[56] = 1530640800;
// Quarter Finals
// Friday 6th July, 2018
worldCupGameID["W49-W50"] = 57; // W49 vs W50
worldCupGameID["W53-W54"] = 58; // W53 vs W54
gameLocked[57] = 1530885600;
gameLocked[58] = 1530900000;
// Saturday 7th July, 2018
worldCupGameID["W55-W56"] = 59; // W55 vs W56
worldCupGameID["W51-W52"] = 60; // W51 vs W52
gameLocked[59] = 1530972000;
gameLocked[60] = 1530986400;
// Semi Finals
// Tuesday 10th July, 2018
worldCupGameID["W57-W58"] = 61; // W57 vs W58
gameLocked[61] = 1531245600;
// Wednesday 11th July, 2018
worldCupGameID["W59-W60"] = 62; // W59 vs W60
gameLocked[62] = 1531332000;
// Third Place Playoff
// Saturday 14th July, 2018
worldCupGameID["L61-L62"] = 63; // L61 vs L62
gameLocked[63] = 1531576800;
// Grand Final
// Sunday 15th July, 2018
worldCupGameID["W61-W62"] = 64; // W61 vs W62
gameLocked[64] = 1531666800;
// Set initial variables.
latestGameFinished = 0;
}
/* PUBLIC-FACING COMPETITION INTERACTIONS */
// Register to participate in the competition. Apart from gas costs from
// making predictions and updating your score if necessary, this is the
// only Ether you will need to spend throughout the tournament.
function register()
public
payable
{
address _customerAddress = msg.sender;
require( tx.origin == _customerAddress
&& !playerRegistered[_customerAddress]
&& _isCorrectBuyin (msg.value));
registeredPlayers = SafeMath.addint256(registeredPlayers, 1);
playerRegistered[_customerAddress] = true;
playerGamesScored[_customerAddress] = 0;
playerList.push(_customerAddress);
uint fivePercent = 0.01009 ether;
uint tenPercent = 0.02018 ether;
uint prizeEth = (msg.value).sub(tenPercent);
require(playerRegistered[_customerAddress]);
prizePool = prizePool.add(prizeEth);
givethPool = givethPool.add(fivePercent);
administrator.send(fivePercent);
emit Registration(_customerAddress);
}
// Make a prediction for a game. An example would be makePrediction(1, "DRAW")
// if you anticipate a draw in the game between Russia and Saudi Arabia,
// or makePrediction(2, "UY") if you expect Uruguay to beat Egypt.
// The "DRAW" option becomes invalid after the group stage games have been played.
function makePrediction(int8 _gameID, string _prediction)
public {
address _customerAddress = msg.sender;
uint predictionTime = now;
require(playerRegistered[_customerAddress]
&& !gameFinished[_gameID]
&& predictionTime < gameLocked[_gameID]);
// No draws allowed after the qualification stage.
if (_gameID > 48 && equalStrings(_prediction, "DRAW")) {
revert();
} else {
playerPredictions[_customerAddress][_gameID] = _prediction;
playerMadePrediction[_customerAddress][_gameID] = true;
emit PlayerLoggedPrediction(_customerAddress, _gameID, _prediction);
}
}
// What is the current score of a given tournament participant?
function showPlayerScores(address _participant)
view
public
returns (int8[64])
{
return playerPointArray[_participant];
}
// What was the last game ID that has had an official score registered for it?
function gameResultsLogged()
view
public
returns (int)
{
return latestGameFinished;
}
// Sum up the individual scores throughout the tournament and produce a final result.
function calculateScore(address _participant)
view
public
returns (int16)
{
int16 finalScore = 0;
for (int8 i = 0; i < latestGameFinished; i++) {
uint j = uint(i);
int16 gameScore = playerPointArray[_participant][j];
finalScore = SafeMath.addint16(finalScore, gameScore);
}
return finalScore;
}
// How many people are taking part in the tournament?
function countParticipants()
public
view
returns (int)
{
return registeredPlayers;
}
// Keeping this open for anyone to update anyone else so that at the end of
// the tournament we can force a score update for everyone using a script.
function updateScore(address _participant)
public
{
int8 lastPlayed = latestGameFinished;
require(lastPlayed > 0);
// Most recent game scored for this participant.
int8 lastScored = playerGamesScored[_participant];
// Most recent game played in the tournament (sets bounds for scoring iteration).
mapping (int8 => bool) madePrediction = playerMadePrediction[_participant];
mapping (int8 => string) playerGuesses = playerPredictions[_participant];
for (int8 i = lastScored; i < lastPlayed; i++) {
uint j = uint(i);
uint k = j.add(1);
uint streak = playerStreak[_participant];
emit StartScoring(_participant, k);
if (!madePrediction[int8(k)]) {
playerPointArray[_participant][j] = 0;
playerStreak[_participant] = 0;
emit DidNotPredict(_participant, k);
emit PlayerPointGain(_participant, k, 0, 0);
} else {
string storage playerResult = playerGuesses[int8(k)];
string storage actualResult = gameResult[int8(k)];
bool correctGuess = equalStrings(playerResult, actualResult);
emit Comparison(_participant, k, playerResult, actualResult, correctGuess);
if (!correctGuess) {
// The guess was wrong.
playerPointArray[_participant][j] = 0;
playerStreak[_participant] = 0;
emit PlayerPointGain(_participant, k, 0, 0);
} else {
// The guess was right.
streak = streak.add(1);
playerStreak[_participant] = streak;
if (streak >= 5) {
// On a long streak - four points.
playerPointArray[_participant][j] = 4;
emit PlayerPointGain(_participant, k, streak, 4);
} else {
if (streak >= 3) {
// On a short streak - two points.
playerPointArray[_participant][j] = 2;
emit PlayerPointGain(_participant, k, streak, 2);
}
// Not yet at a streak - standard one point.
else { playerPointArray[_participant][j] = 1;
emit PlayerPointGain(_participant, k, streak, 1);
}
}
}
}
}
playerGamesScored[_participant] = lastPlayed;
}
// Invoke this function to get *everyone* up to date score-wise.
// This is probably best used at the end of the tournament, to ensure
// that prizes are awarded to the correct addresses.
// Note: this is going to be VERY gas-intensive. Use it if you're desperate
// to see how you square up against everyone else if they're slow to
// update their own scores. Alternatively, if there's just one or two
// stragglers, you can just call updateScore for them alone.
function updateAllScores()
public
{
uint allPlayers = playerList.length;
for (uint i = 0; i < allPlayers; i++) {
address _toScore = playerList[i];
emit StartAutoScoring(_toScore);
updateScore(_toScore);
}
}
// Which game ID has a player last computed their score up to
// using the updateScore function?
function playerLastScoredGame(address _player)
public
view
returns (int8)
{
return playerGamesScored[_player];
}
// Is a player registered?
function playerIsRegistered(address _player)
public
view
returns (bool)
{
return playerRegistered[_player];
}
// What was the official result of a game?
function correctResult(int8 _gameID)
public
view
returns (string)
{
return gameResult[_gameID];
}
// What was the caller's prediction for a given game?
function playerGuess(int8 _gameID)
public
view
returns (string)
{
return playerPredictions[msg.sender][_gameID];
}
/* ADMINISTRATOR FUNCTIONS FOR COMPETITION MAINTENANCE */
modifier isAdministrator() {
address _sender = msg.sender;
if (_sender == administrator) {
_;
} else {
revert();
}
}
// As new fixtures become known through progression or elimination, they're added here.
function addNewGame(string _opponents, int8 _gameID)
isAdministrator
public {
worldCupGameID[_opponents] = _gameID;
}
// When the result of a game is known, enter the result.
function logResult(int8 _gameID, string _winner)
isAdministrator
public {
require((int8(0) < _gameID) && (_gameID <= 64)
&& _gameID == latestGameFinished + 1);
// No draws allowed after the qualification stage.
if (_gameID > 48 && equalStrings(_winner, "DRAW")) {
revert();
} else {
require(!gameFinished[_gameID]);
gameFinished [_gameID] = true;
gameResult [_gameID] = _winner;
latestGameFinished = _gameID;
assert(gameFinished[_gameID]);
}
}
// Concludes the tournament and issues the prizes, then self-destructs.
function concludeTournament(address _first // 40% Ether.
, address _second // 30% Ether.
, address _third // 20% Ether.
, address _fourth) // 10% Ether.
isAdministrator
public
{
// Don't hand out prizes until the final's... actually been played.
require(gameFinished[64]
&& playerIsRegistered(_first)
&& playerIsRegistered(_second)
&& playerIsRegistered(_third)
&& playerIsRegistered(_fourth));
// Send the money raised for Giveth.
givethAddress.send(givethPool);
// Determine 10% of the prize pool to distribute to winners.
uint tenth = prizePool.div(10);
_first.send (tenth.mul(4));
_second.send(tenth.mul(3));
_third.send (tenth.mul(2));
// Since there might be rounding errors, fourth place gets everything else.
_fourth.send(address(this).balance);
// Thanks for playing, everyone.
selfdestruct(administrator);
}
// The emergency escape hatch in case something has gone wrong. Refunds 95% of purchase Ether
// to all registered addresses: the other 0.01009 has been sent directly to the developer who can
// handle sending that back to everyone using a script.
// Let's hope this one doesn't have to get pulled, eh?
function pullRipCord()
isAdministrator
public
{
uint players = playerList.length;
for (uint i = 0; i < players; i++) {
address _toRefund = playerList[i];
_toRefund.send(0.19171 ether);
emit RipcordRefund(_toRefund);
}
selfdestruct(administrator);
}
/* INTERNAL FUNCTIONS */
// Gateway check - did you send exactly the right amount?
function _isCorrectBuyin(uint _buyin)
private
pure
returns (bool) {
return _buyin == 0.2018 ether;
}
// Internal comparison between strings, returning 0 if equal, 1 otherwise.
function compare(string _a, string _b)
private
pure
returns (int)
{
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) minLength = b.length;
for (uint i = 0; i < minLength; i ++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
if (a.length < b.length)
return -1;
else if (a.length > b.length)
return 1;
else
return 0;
}
/// Compares two strings and returns true if and only if they are equal.
function equalStrings(string _a, string _b) pure private returns (bool) {
return compare(_a, _b) == 0;
}
}
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;
}
function addint16(int16 a, int16 b) internal pure returns (int16) {
int16 c = a + b;
assert(c >= a);
return c;
}
function addint256(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
assert(c >= a);
return c;
}
}
|
* @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;
}
| 2,278,748 |
[
1,
3655,
2795,
5600,
16,
1216,
603,
9391,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
527,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2254,
5034,
276,
273,
279,
397,
324,
31,
203,
3639,
1815,
12,
71,
1545,
279,
1769,
203,
3639,
327,
276,
31,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0xc2166567dbCC8Bc35ce79Ed429D75451AfC14985/sources/localhost/contracts/GatebridgeV2LPToken.sol
|
liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY); liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
|
function mintOther(uint chainId, uint amount) external lock override returns (uint liquidity) {
if (_allChainsTotalSupply == 0) {
liquidity = 1;
liquidity = 2;
}
require(liquidity > 0, 'GatebridgeV2: INSUFFICIENT_LIQUIDITY_MINTED');
allChainsTotalSupply = allChainsTotalSupply.add(liquidity);
chainIdToTotalLiquidity[chainId] = chainIdToTotalLiquidity[chainId].add(liquidity);
chainIdToReserve[chainId] = chainIdToReserve[chainId] + uint112(amount);
}
| 1,852,285 |
[
1,
549,
372,
24237,
273,
2361,
18,
24492,
12,
8949,
20,
18,
16411,
12,
8949,
21,
13,
2934,
1717,
12,
6236,
18605,
67,
2053,
53,
3060,
4107,
1769,
5411,
4501,
372,
24237,
273,
2361,
18,
1154,
12,
8949,
20,
18,
16411,
24899,
4963,
3088,
1283,
13,
342,
389,
455,
6527,
20,
16,
3844,
21,
18,
16411,
24899,
4963,
3088,
1283,
13,
342,
389,
455,
6527,
21,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
565,
445,
312,
474,
8290,
12,
11890,
2687,
548,
16,
2254,
3844,
13,
3903,
2176,
3849,
1135,
261,
11890,
4501,
372,
24237,
13,
288,
203,
203,
3639,
309,
261,
67,
454,
15945,
5269,
3088,
1283,
422,
374,
13,
288,
203,
5411,
4501,
372,
24237,
273,
404,
31,
203,
5411,
4501,
372,
24237,
273,
576,
31,
203,
3639,
289,
203,
3639,
2583,
12,
549,
372,
24237,
405,
374,
16,
296,
13215,
18337,
58,
22,
30,
2120,
6639,
42,
1653,
7266,
2222,
67,
2053,
53,
3060,
4107,
67,
6236,
6404,
8284,
203,
3639,
777,
15945,
5269,
3088,
1283,
273,
777,
15945,
5269,
3088,
1283,
18,
1289,
12,
549,
372,
24237,
1769,
203,
3639,
2687,
28803,
5269,
48,
18988,
24237,
63,
5639,
548,
65,
273,
2687,
28803,
5269,
48,
18988,
24237,
63,
5639,
548,
8009,
1289,
12,
549,
372,
24237,
1769,
203,
3639,
2687,
28803,
607,
6527,
63,
5639,
548,
65,
273,
2687,
28803,
607,
6527,
63,
5639,
548,
65,
397,
2254,
17666,
12,
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
] |
/**
* @title ArbitrableTokenList
* @author Matheus Alencar - <[email protected]>
* This code hasn't undertaken bug bounty programs yet.
*/
pragma solidity ^0.4.24;
import "../arbitration/composed-arbitrable/composed/MultiPartyInsurableArbitrableAgreementsBase.sol";
/**
* @title ArbitrableTokenList
* This is a T2CL for tokens. Tokens can be submitted and cleared with a time out for challenging.
*/
contract ArbitrableTokenList is MultiPartyInsurableArbitrableAgreementsBase {
/* Enums */
enum ItemStatus {
Absent, // The item has never been submitted.
Cleared, // The item has been submitted and the dispute resolution process determined it should not be added or a clearing request has been submitted and the dispute resolution process determined it should be cleared or the clearing was never contested.
Resubmitted, // The item has been cleared but someone has resubmitted it.
Registered, // The item has been submitted and the dispute resolution process determined it should be added or the submission was never contested.
Submitted, // The item has been submitted.
ClearingRequested, // The item is registered, but someone has requested to remove it.
PreventiveClearingRequested // The item has never been registered, but someone asked to clear it preemptively to avoid it being shown as not registered during the dispute resolution process.
}
enum RulingOption {
OTHER, // Arbitrator did not rule of refused to rule.
ACCEPT, // Execute request. Rule in favor of requester.
REFUSE // Refuse request. Rule in favor of challenger.
}
enum Party {
Requester,
Challenger,
None
}
/* Structs */
struct Item {
ItemStatus status; // Status of the item.
uint lastAction; // Time of the last action.
uint balance; // The amount of funds placed at stake for this item. Does not include arbitrationFees.
uint challengeReward; // The challengeReward of the item for the round.
bytes32 latestAgreementID; // The ID of the latest agreement for the item.
}
/* Modifiers */
modifier onlyT2CLGovernor {require(msg.sender == t2clGovernor, "The caller is not the t2cl governor."); _;}
/* Events */
/**
* @dev Called when the item's status changes or when it is challenged/resolved.
* @param requester Address of the requester.
* @param challenger Address of the challenger, if any.
* @param tokenID The tokenID of the item.
* @param status The status of the item.
* @param disputed Wether the item is being disputed.
*/
event ItemStatusChange(
address indexed requester,
address indexed challenger,
bytes32 indexed tokenID,
ItemStatus status,
bool disputed
);
/* Storage */
// Settings
uint public challengeReward; // The stake deposit required in addition to arbitration fees for challenging a request.
uint public timeToChallenge; // The time before a request becomes executable if not challenged.
uint public arbitrationFeesWaitingTime; // The maximum time to wait for arbitration fees if the dispute is raised.
address public t2clGovernor; // The address that can update t2clGovernor, arbitrationFeesWaitingTime and challengeReward.
// Items
mapping(bytes32 => Item) public items;
bytes32[] public itemsList;
// Agreement and Item Extension
mapping(bytes32 => bytes32) public agreementIDToItemID;
/* Constructor */
/**
* @dev Constructs the arbitrable token list.
* @param _arbitrator The chosen arbitrator.
* @param _arbitratorExtraData Extra data for the arbitrator contract.
* @param _feeGovernor The fee governor of this contract.
* @param _stake The stake parameter for sharing fees.
* @param _t2clGovernor The t2clGovernor address. This address can update t2clGovernor, arbitrationFeesWaitingTime and challengeReward.
* @param _arbitrationFeesWaitingTime The maximum time to wait for arbitration fees if the dispute is raised.
* @param _challengeReward The amount in Weis of deposit required for a submission or a challenge in addition to the arbitration fees.
* @param _timeToChallenge The time in seconds, parties have to challenge.
*/
constructor(
Arbitrator _arbitrator,
bytes _arbitratorExtraData,
address _feeGovernor,
uint _stake,
address _t2clGovernor,
uint _arbitrationFeesWaitingTime,
uint _challengeReward,
uint _timeToChallenge
) public MultiPartyInsurableArbitrableAgreementsBase(_arbitrator, _arbitratorExtraData, _feeGovernor, _stake){
challengeReward = _challengeReward;
timeToChallenge = _timeToChallenge;
t2clGovernor = _t2clGovernor;
arbitrationFeesWaitingTime = _arbitrationFeesWaitingTime;
}
/* Public */
// ************************ //
// * Requests * //
// ************************ //
/** @dev Request for an item to be registered.
* @param _tokenID The keccak hash of a JSON object with all of the token's properties and no insignificant whitespaces.
* @param _metaEvidence The meta evidence for the potential dispute.
*/
function requestRegistration(
bytes32 _tokenID,
string _metaEvidence
) external payable {
Item storage item = items[_tokenID];
Agreement storage prevAgreement = agreements[item.latestAgreementID];
if(item.latestAgreementID != 0x0) // Not the first request for this tokenID.
require(prevAgreement.executed, "There is a pending request in place.");
else
itemsList.push(_tokenID);
require(msg.value >= challengeReward, "Not enough ETH.");
if (item.status == ItemStatus.Absent)
item.status = ItemStatus.Submitted;
else if (item.status == ItemStatus.Cleared)
item.status = ItemStatus.Resubmitted;
else
revert("Item in wrong status for registration."); // If the item is neither Absent nor Cleared, it is not possible to request registering it.
item.balance = challengeReward;
item.lastAction = now;
item.challengeReward = challengeReward; // Update challengeReward.
address[] memory _parties = new address[](2);
_parties[0] = msg.sender;
_createAgreement(
_metaEvidence,
_parties,
2,
new bytes(0),
arbitrationFeesWaitingTime,
arbitrator,
_tokenID
);
if(msg.value > challengeReward) msg.sender.transfer(msg.value - challengeReward); // Refund any extra ETH.
Agreement storage agreement = agreements[item.latestAgreementID];
emit ItemStatusChange(agreement.parties[0], address(0), _tokenID, item.status, agreement.disputed);
}
/** @dev Request an item to be cleared.
* @param _tokenID The keccak hash of a JSON object with all of the token's properties and no insignificant whitespaces.
* @param _metaEvidence The meta evidence for the potential dispute.
*/
function requestClearing(
bytes32 _tokenID,
string _metaEvidence
) external payable {
Item storage item = items[_tokenID];
Agreement storage prevAgreement = agreements[item.latestAgreementID];
if(item.latestAgreementID != 0x0) // Not the first request for this tokenID.
require(prevAgreement.executed, "There is already a request in place.");
else
itemsList.push(_tokenID);
require(msg.value >= challengeReward, "Not enough ETH.");
if (item.status == ItemStatus.Registered)
item.status = ItemStatus.ClearingRequested;
else if (item.status == ItemStatus.Absent)
item.status = ItemStatus.PreventiveClearingRequested;
else
revert("Item in wrong status for clearing."); // If the item is neither Registered nor Absent, it is not possible to request clearing it.
item.balance = challengeReward; // Update challengeReward.
item.lastAction = now;
item.challengeReward = challengeReward;
address[] memory _parties = new address[](2);
_parties[0] = msg.sender;
_createAgreement(
_metaEvidence,
_parties,
2,
new bytes(0),
arbitrationFeesWaitingTime,
arbitrator,
_tokenID
);
if(msg.value > challengeReward) msg.sender.transfer(msg.value - challengeReward); // Refund any extra eth.
Agreement storage agreement = agreements[item.latestAgreementID];
emit ItemStatusChange(agreement.parties[0], address(0), _tokenID, item.status, agreement.disputed);
}
/** @dev Overrides parent to use information specific to Arbitrable Token List in math:
* - Parent's fundDispute doesn't take into account `challengeReward` when calculating ETH.
* - For calls that initiate a dispute, msg.value must also include `challengeReward`.
* @param _agreementID The ID of the agreement.
* @param _side The side with respect to paidFees. 0 for the side that lost the previous round, if any, and 1 for the one that won.
*/
function fundDispute(bytes32 _agreementID, uint _side) public payable {
Agreement storage agreement = agreements[_agreementID];
PaidFees storage _paidFees = paidFees[_agreementID];
Item storage item = items[agreementIDToItemID[_agreementID]];
require(agreement.creator != address(0), "The specified agreement does not exist.");
require(!agreement.executed, "You cannot fund disputes for executed agreements.");
require(
!agreement.disputed || agreement.arbitrator.disputeStatus(agreement.disputeID) == Arbitrator.DisputeStatus.Appealable,
"The agreement is already disputed and is not appealable."
);
require(_side <= 1, "There are only two sides.");
// Prepare storage for first call.
if (_paidFees.firstContributionTime == 0) {
_paidFees.firstContributionTime = now;
_paidFees.ruling.push(0);
_paidFees.stake.push(stake);
_paidFees.totalValue.push(0);
_paidFees.totalContributedPerSide.push([0, 0]);
_paidFees.loserFullyFunded.push(false);
_paidFees.contributions.length++;
}
// Reset cache.
fundDisputeCache.cost = 0;
fundDisputeCache.appealing = false;
(fundDisputeCache.appealPeriodStart, fundDisputeCache.appealPeriodEnd) = (0, 0);
fundDisputeCache.appealPeriodSupported = false;
fundDisputeCache.requiredValueForSide = 0;
fundDisputeCache.expectedValue = 0;
fundDisputeCache.stillRequiredValueForSide = 0;
fundDisputeCache.keptValue = 0;
fundDisputeCache.refundedValue = 0;
// Check time outs and requirements.
if (_paidFees.stake.length == 1) { // First round.
fundDisputeCache.cost = agreement.arbitrator.arbitrationCost(agreement.extraData);
// Arbitration fees time out.
if (now - _paidFees.firstContributionTime > agreement.arbitrationFeesWaitingTime) {
executeAgreementRuling(_agreementID, 0);
return;
}
} else { // Appeal.
fundDisputeCache.cost = agreement.arbitrator.appealCost(agreement.disputeID, agreement.extraData);
fundDisputeCache.appealing = true;
(fundDisputeCache.appealPeriodStart, fundDisputeCache.appealPeriodEnd) = agreement.arbitrator.appealPeriod(agreement.disputeID);
fundDisputeCache.appealPeriodSupported = fundDisputeCache.appealPeriodStart != 0 && fundDisputeCache.appealPeriodEnd != 0;
if (fundDisputeCache.appealPeriodSupported) {
if (now < fundDisputeCache.appealPeriodStart + ((fundDisputeCache.appealPeriodEnd - fundDisputeCache.appealPeriodStart) / 2)) // In the first half of the appeal period.
require(_side == 0, "It is the losing side's turn to fund the appeal.");
else // In the second half of the appeal period.
require(
_side == 1 && _paidFees.loserFullyFunded[_paidFees.loserFullyFunded.length - 1],
"It is the winning side's turn to fund the appeal, only if the losing side already fully funded it."
);
} else require(msg.value >= fundDisputeCache.cost, "Fees must be paid in full if the arbitrator does not support `appealPeriod`.");
}
require(msg.value > 0, "The value of the contribution cannot be zero.");
// Compute required value.
if (!fundDisputeCache.appealing) { // First round.
fundDisputeCache.requiredValueForSide = fundDisputeCache.cost / 2;
} else { // Appeal.
if (!fundDisputeCache.appealPeriodSupported)
fundDisputeCache.requiredValueForSide = fundDisputeCache.cost;
else if (_side == 0) // Losing side.
fundDisputeCache.requiredValueForSide = fundDisputeCache.cost + (2 * _paidFees.stake[_paidFees.stake.length - 1]);
else { // Winning side.
fundDisputeCache.expectedValue = _paidFees.totalContributedPerSide[_paidFees.totalContributedPerSide.length - 1][0] - _paidFees.stake[_paidFees.stake.length - 1];
fundDisputeCache.requiredValueForSide = fundDisputeCache.cost > _paidFees.totalContributedPerSide[_paidFees.totalContributedPerSide.length - 1][0] + fundDisputeCache.expectedValue ? fundDisputeCache.cost - _paidFees.totalContributedPerSide[_paidFees.totalContributedPerSide.length - 1][0] : fundDisputeCache.expectedValue;
}
}
// Calculate value still required.
if (_paidFees.totalContributedPerSide[_paidFees.totalContributedPerSide.length - 1][_side] >= fundDisputeCache.requiredValueForSide)
fundDisputeCache.stillRequiredValueForSide = 0;
else
fundDisputeCache.stillRequiredValueForSide = fundDisputeCache.requiredValueForSide - _paidFees.totalContributedPerSide[_paidFees.totalContributedPerSide.length - 1][_side];
if(item.balance == item.challengeReward) {
// Party is attempting to start a dispute.
require(msg.value >= item.challengeReward, "Party challenging agreement must place value at stake");
fundDisputeCache.keptValue = fundDisputeCache.stillRequiredValueForSide >= msg.value - item.challengeReward
? msg.value - item.challengeReward
: fundDisputeCache.stillRequiredValueForSide;
item.balance += item.challengeReward;
fundDisputeCache.refundedValue = msg.value - fundDisputeCache.keptValue - item.challengeReward;
agreement.parties[1] = msg.sender;
} else {
// Party that started dispute already placed value at stake, in other words: item.balance == item.challengeReward * 2.
// This means the caller is contributing to fees crowdfunding.
fundDisputeCache.keptValue = fundDisputeCache.stillRequiredValueForSide >= msg.value
? msg.value
: fundDisputeCache.stillRequiredValueForSide;
fundDisputeCache.refundedValue = msg.value - fundDisputeCache.keptValue;
}
// Take the contribution
if (fundDisputeCache.keptValue > 0) {
_paidFees.totalValue[_paidFees.totalValue.length - 1] += fundDisputeCache.keptValue;
_paidFees.totalContributedPerSide[_paidFees.totalContributedPerSide.length - 1][_side] += fundDisputeCache.keptValue;
_paidFees.contributions[_paidFees.contributions.length - 1][msg.sender][_side] += fundDisputeCache.keptValue;
}
if (fundDisputeCache.refundedValue > 0) msg.sender.transfer(fundDisputeCache.refundedValue);
emit Contribution(_agreementID, _paidFees.stake.length - 1, msg.sender, fundDisputeCache.keptValue);
// Check if enough funds have been gathered and act accordingly.
if (
_paidFees.totalContributedPerSide[_paidFees.totalContributedPerSide.length - 1][_side] >= fundDisputeCache.requiredValueForSide ||
(fundDisputeCache.appealing && !fundDisputeCache.appealPeriodSupported)
) {
if (_side == 0 && (fundDisputeCache.appealing ? fundDisputeCache.appealPeriodSupported : _paidFees.totalContributedPerSide[_paidFees.totalContributedPerSide.length - 1][1] < fundDisputeCache.requiredValueForSide)) { // Losing side and not direct appeal or dispute raise.
if (!_paidFees.loserFullyFunded[_paidFees.loserFullyFunded.length - 1])
_paidFees.loserFullyFunded[_paidFees.loserFullyFunded.length - 1] = true;
} else { // Winning side or direct appeal.
if (!fundDisputeCache.appealing) { // First round.
if (_paidFees.totalContributedPerSide[_paidFees.totalContributedPerSide.length - 1][_side == 0 ? 1 : 0] < fundDisputeCache.requiredValueForSide) return;
agreement.disputeID = agreement.arbitrator.createDispute.value(fundDisputeCache.cost)(agreement.numberOfChoices, agreement.extraData);
agreement.disputed = true;
arbitratorAndDisputeIDToAgreementID[agreement.arbitrator][agreement.disputeID] = _agreementID;
emit Dispute(agreement.arbitrator, agreement.disputeID, uint(_agreementID));
} else { // Appeal.
_paidFees.ruling[_paidFees.ruling.length - 1] = agreement.arbitrator.currentRuling(agreement.disputeID);
agreement.arbitrator.appeal.value(fundDisputeCache.cost)(agreement.disputeID, agreement.extraData);
if (!agreement.appealed) agreement.appealed = true;
}
// Update the total value.
_paidFees.totalValue[_paidFees.totalValue.length - 1] -= fundDisputeCache.cost;
// Prepare for the next round.
_paidFees.ruling.push(0);
_paidFees.stake.push(stake);
_paidFees.totalValue.push(0);
_paidFees.totalContributedPerSide.push([0, 0]);
_paidFees.loserFullyFunded.push(false);
_paidFees.contributions.length++;
}
}
}
/** @dev Execute a request after the time for challenging it has passed. Can be called by anyone.
* @param _tokenID The tokenID of the item with the request to execute.
*/
function executeRequest(bytes32 _tokenID) external {
Item storage item = items[_tokenID];
bytes32 agreementID = item.latestAgreementID;
Agreement storage agreement = agreements[agreementID];
require(now - item.lastAction > timeToChallenge, "The time to challenge has not passed yet.");
require(agreement.creator != address(0), "The specified agreement does not exist.");
require(!agreement.executed, "The specified agreement has already been executed.");
require(!agreement.disputed, "The specified agreement is disputed.");
if (item.status == ItemStatus.Resubmitted || item.status == ItemStatus.Submitted)
item.status = ItemStatus.Registered;
else if (item.status == ItemStatus.ClearingRequested || item.status == ItemStatus.PreventiveClearingRequested)
item.status = ItemStatus.Cleared;
else
revert("Item in wrong status for executing request.");
agreement.parties[0].send(item.balance); // Deliberate use of send in order to not block the contract in case of reverting fallback.
agreement.executed = true;
item.lastAction = now;
item.challengeReward = 0; // Clear challengeReward once a request has been executed.
item.balance = 0;
emit ItemStatusChange(agreement.parties[0], address(0), _tokenID, item.status, agreement.disputed);
}
// ************************ //
// * Governance * //
// ************************ //
/** @dev Changes the `timeToChallenge` storage variable.
* @param _timeToChallenge The new `timeToChallenge` storage variable.
*/
function changeTimeToChallenge(uint _timeToChallenge) external onlyT2CLGovernor {
timeToChallenge = _timeToChallenge;
}
/** @dev Changes the `challengeReward` storage variable.
* @param _challengeReward The new `challengeReward` storage variable.
*/
function changeChallengeReward(uint _challengeReward) external onlyT2CLGovernor {
challengeReward = _challengeReward;
}
/** @dev Changes the `t2clGovernor` storage variable.
* @param _t2clGovernor The new `t2clGovernor` storage variable.
*/
function changeT2CLGovernor(address _t2clGovernor) external onlyT2CLGovernor {
t2clGovernor = _t2clGovernor;
}
/** @dev Changes the `arbitrationFeesWaitingTime` storage variable.
* @param _arbitrationFeesWaitingTime The new `_arbitrationFeesWaitingTime` storage variable.
*/
function changeArbitrationFeesWaitingTime(uint _arbitrationFeesWaitingTime) external onlyT2CLGovernor {
arbitrationFeesWaitingTime = _arbitrationFeesWaitingTime;
}
/* Public Views */
/** @dev Return true if the item is allowed. We consider the item to be in the list if its status is contested and it has not won a dispute previously.
* @param _tokenID The tokenID of the item to check.
* @return allowed True if the item is allowed, false otherwise.
*/
function isPermitted(bytes32 _tokenID) public view returns (bool allowed) {
Item storage item = items[_tokenID];
return item.status == ItemStatus.Registered || item.status == ItemStatus.ClearingRequested;
}
/* Internal */
/** @dev Extends parent to use counter identify agreements.
* @param _metaEvidence The meta evidence of the agreement.
* @param _parties The `parties` value of the agreement.
* @param _numberOfChoices The `numberOfChoices` value of the agreement.
* @param _extraData The `extraData` value of the agreement.
* @param _arbitrationFeesWaitingTime The `arbitrationFeesWaitingTime` value of the agreement.
* @param _arbitrator The `arbitrator` value of the agreement.
* @param _tokenID The item id.
*/
function _createAgreement(
string _metaEvidence,
address[] _parties,
uint _numberOfChoices,
bytes _extraData,
uint _arbitrationFeesWaitingTime,
Arbitrator _arbitrator,
bytes32 _tokenID
) internal {
Item storage item = items[_tokenID];
bytes32 agreementID;
if(item.latestAgreementID == 0x0)
agreementID = keccak256(abi.encodePacked(_tokenID));
else
agreementID = keccak256(abi.encodePacked(item.latestAgreementID));
item.latestAgreementID = agreementID;
agreementIDToItemID[agreementID] = _tokenID;
super._createAgreement(
agreementID,
_metaEvidence,
_parties,
_numberOfChoices,
_extraData,
_arbitrationFeesWaitingTime,
_arbitrator
);
}
/** @dev Executes the ruling on the specified agreement.
* @param _agreementID The ID of the agreement.
* @param _ruling The ruling.
*/
function executeAgreementRuling(bytes32 _agreementID, uint _ruling) internal {
super.executeAgreementRuling(_agreementID, _ruling);
Agreement storage agreement = agreements[_agreementID];
PaidFees storage _paidFees = paidFees[_agreementID];
Item storage item = items[agreementIDToItemID[_agreementID]];
Party winner = Party.None;
if (_paidFees.stake.length == 1) // Failed to fund first round.
// Rule in favor of whoever paid more.
if (_paidFees.totalContributedPerSide[0][0] >= _paidFees.totalContributedPerSide[0][1])
winner = Party.Requester;
else
winner = Party.Challenger;
else
// Respect the ruling unless the losing side funded the appeal and the winning side paid less than expected.
if (
_paidFees.loserFullyFunded[_paidFees.loserFullyFunded.length - 1] &&
_paidFees.totalContributedPerSide[_paidFees.totalContributedPerSide.length - 1][0] - _paidFees.stake[_paidFees.stake.length - 1] > _paidFees.totalContributedPerSide[_paidFees.totalContributedPerSide.length - 1][1]
)
// Rule in favor of the losing party.
// If an arbitrator ruled to execute a request, the losing party is the challenger. If
// The arbitrator ruled to refuse a request, the losing party is the requester.
// Ruling in favor of the losing party means inverting the decision of the arbitrator.
if (_ruling == uint(RulingOption.ACCEPT))
winner = Party.Challenger;
else
winner = Party.Requester;
else
// Respect the ruling.
if (_ruling == uint(RulingOption.ACCEPT))
winner = Party.Requester;
else if (_ruling == uint(RulingOption.REFUSE))
winner = Party.Challenger;
// Update item state
if(winner == Party.Requester)
// Execute Request
if (item.status == ItemStatus.Resubmitted || item.status == ItemStatus.Submitted)
item.status = ItemStatus.Registered;
else
item.status = ItemStatus.Cleared;
else
// Revert to previous state.
if (item.status == ItemStatus.Resubmitted)
item.status = ItemStatus.Cleared;
else if (item.status == ItemStatus.ClearingRequested)
item.status = ItemStatus.Registered;
else
item.status = ItemStatus.Absent;
// Send item balance
if(winner == Party.None) {
// Split the balance 50-50 and give the item the initial status.
agreement.parties[uint(Party.Requester)].send(item.balance / 2); // Deliberate use of send in order to not block the contract in case of reverting fallback.
agreement.parties[uint(Party.Challenger)].send(item.balance / 2); // Deliberate use of send in order to not block the contract in case of reverting fallback.
} else
agreement.parties[uint(winner)].send(item.balance); // Deliberate use of send in order to not block the contract in case of reverting fallback.
agreement.executed = true;
item.lastAction = now;
item.balance = 0;
item.challengeReward = 0; // Clear challengeReward once a dispute is resolved.
emit ItemStatusChange(agreement.parties[0], address(0), agreementIDToItemID[_agreementID], item.status, agreement.disputed);
}
/* Interface Views */
/** @dev Return the numbers of items in the list per status.
* @return The numbers of items in the list per status.
*/
function itemsCounts()
external
view
returns (
uint disputed,
uint absent,
uint cleared,
uint resubmitted,
uint submitted,
uint clearingRequested,
uint preventiveClearingRequested
)
{
for (uint i = 0; i < itemsList.length; i++) {
Item storage item = items[itemsList[i]];
Agreement storage latestAgreement = agreements[item.latestAgreementID];
if (latestAgreement.disputed) disputed++;
if (item.status == ItemStatus.Absent) absent++;
else if (item.status == ItemStatus.Cleared) cleared++;
else if (item.status == ItemStatus.Submitted) submitted++;
else if (item.status == ItemStatus.Resubmitted) resubmitted++;
else if (item.status == ItemStatus.ClearingRequested) clearingRequested++;
else if (item.status == ItemStatus.PreventiveClearingRequested) preventiveClearingRequested++;
}
}
/** @dev Return the values of the items the query finds. This function is O(n) at worst, where n is the number of items. This could exceed the gas limit, therefore this function should only be used for interface display and not by other contracts.
* @param _cursor The pagination cursor.
* @param _count The number of items to return.
* @param _filter The filter to use.
* @param _sort The sort order to use.
* @return The values of the items found and wether there are more items for the current filter and sort.
*/
function queryItems(bytes32 _cursor, uint _count, bool[9] _filter, bool _sort) external view returns (bytes32[] values, bool hasMore) {
uint _cursorIndex;
values = new bytes32[](_count);
uint _index = 0;
if (_cursor == 0)
_cursorIndex = 0;
else {
for (uint j = 0; j < itemsList.length; j++) {
if (itemsList[j] == _cursor) {
_cursorIndex = j;
break;
}
}
require(_cursorIndex != 0, "The cursor is invalid.");
}
for (
uint i = _cursorIndex == 0 ? (_sort ? 0 : 1) : (_sort ? _cursorIndex + 1 : itemsList.length - _cursorIndex + 1);
_sort ? i < itemsList.length : i <= itemsList.length;
i++
) { // Oldest or newest first.
bytes32 itemID = itemsList[_sort ? i : itemsList.length - i];
Item storage item = items[itemID];
Agreement storage agreement = agreements[item.latestAgreementID];
if (
/* solium-disable operator-whitespace */
(_filter[0] && agreement.disputed) ||
(_filter[1] && item.status == ItemStatus.Absent) ||
(_filter[2] && item.status == ItemStatus.Cleared) ||
(_filter[3] && item.status == ItemStatus.Submitted) ||
(_filter[4] && item.status == ItemStatus.Resubmitted) ||
(_filter[5] && item.status == ItemStatus.ClearingRequested) ||
(_filter[6] && item.status == ItemStatus.PreventiveClearingRequested) ||
(_filter[7] && agreement.parties[0] == msg.sender) || // My Submissions.
(_filter[8] && agreement.parties[1] == msg.sender) // My Challenges.
/* solium-enable operator-whitespace */
) {
if (_index < _count) {
values[_index] = itemsList[_sort ? i : itemsList.length - i];
_index++;
} else {
hasMore = true;
break;
}
}
}
}
}
|
* @dev Extends parent to use counter identify agreements. @param _metaEvidence The meta evidence of the agreement. @param _parties The `parties` value of the agreement. @param _numberOfChoices The `numberOfChoices` value of the agreement. @param _extraData The `extraData` value of the agreement. @param _arbitrationFeesWaitingTime The `arbitrationFeesWaitingTime` value of the agreement. @param _arbitrator The `arbitrator` value of the agreement. @param _tokenID The item id./
|
) internal {
Item storage item = items[_tokenID];
bytes32 agreementID;
if(item.latestAgreementID == 0x0)
agreementID = keccak256(abi.encodePacked(_tokenID));
else
agreementID = keccak256(abi.encodePacked(item.latestAgreementID));
item.latestAgreementID = agreementID;
agreementIDToItemID[agreementID] = _tokenID;
super._createAgreement(
agreementID,
_metaEvidence,
_parties,
_numberOfChoices,
_extraData,
_arbitrationFeesWaitingTime,
_arbitrator
);
}
| 12,535,328 |
[
1,
19581,
982,
358,
999,
3895,
9786,
19602,
87,
18,
282,
389,
3901,
30465,
1021,
2191,
14481,
434,
326,
19602,
18,
282,
389,
2680,
606,
1021,
1375,
2680,
606,
68,
460,
434,
326,
19602,
18,
282,
389,
2696,
951,
17442,
1021,
1375,
2696,
951,
17442,
68,
460,
434,
326,
19602,
18,
282,
389,
7763,
751,
1021,
1375,
7763,
751,
68,
460,
434,
326,
19602,
18,
282,
389,
297,
3682,
7034,
2954,
281,
15946,
950,
1021,
1375,
297,
3682,
7034,
2954,
281,
15946,
950,
68,
460,
434,
326,
19602,
18,
282,
389,
297,
3682,
86,
639,
1021,
1375,
297,
3682,
86,
639,
68,
460,
434,
326,
19602,
18,
282,
389,
2316,
734,
1021,
761,
612,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
565,
262,
2713,
288,
203,
3639,
4342,
2502,
761,
273,
1516,
63,
67,
2316,
734,
15533,
203,
3639,
1731,
1578,
19602,
734,
31,
203,
3639,
309,
12,
1726,
18,
13550,
17420,
734,
422,
374,
92,
20,
13,
203,
5411,
19602,
734,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
24899,
2316,
734,
10019,
203,
3639,
469,
203,
5411,
19602,
734,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
1726,
18,
13550,
17420,
734,
10019,
203,
203,
3639,
761,
18,
13550,
17420,
734,
273,
19602,
734,
31,
203,
3639,
19602,
734,
774,
1180,
734,
63,
31135,
734,
65,
273,
389,
2316,
734,
31,
203,
203,
3639,
2240,
6315,
2640,
17420,
12,
203,
5411,
19602,
734,
16,
203,
5411,
389,
3901,
30465,
16,
203,
5411,
389,
2680,
606,
16,
203,
5411,
389,
2696,
951,
17442,
16,
203,
5411,
389,
7763,
751,
16,
203,
5411,
389,
297,
3682,
7034,
2954,
281,
15946,
950,
16,
203,
5411,
389,
297,
3682,
86,
639,
203,
3639,
11272,
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
] |
/**
*Submitted for verification at Etherscan.io on 2021-06-03
*/
pragma solidity ^0.4.24;
// ----------------------------------------------------------------------------
// 'COCCO' token contract
//
// Deployed to : 0x0c859633811986f7bD06244352131F6139E7aB87
// Symbol : COCCO
// Name : COCCO
// Total supply: 1000000000000
// Decimals : 5
//
// Enjoy.
//
// (c) by Moritz Neto with BokkyPooBah / Bok Consulting Pty Ltd Au 2017. The MIT Licence.
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// Safe maths
// ----------------------------------------------------------------------------
contract SafeMath {
function safeAdd(uint a, uint b) public pure returns (uint c) {
c = a + b;
require(c >= a);
}
function safeSub(uint a, uint b) public pure returns (uint c) {
require(b <= a);
c = a - b;
}
function safeMul(uint a, uint b) public pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function safeDiv(uint a, uint b) public pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// ----------------------------------------------------------------------------
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
// ----------------------------------------------------------------------------
// Contract function to receive approval and execute function in one call
//
// Borrowed from MiniMeToken
// ----------------------------------------------------------------------------
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ----------------------------------------------------------------------------
contract COCCO is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "COCCO";
name = "COCCO";
decimals = 5;
_totalSupply = 1000000000000;
balances[0x0c859633811986f7bD06244352131F6139E7aB87] = _totalSupply;
emit Transfer(address(0), 0x0c859633811986f7bD06244352131F6139E7aB87, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
}
|
---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and assisted token transfers ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------
|
contract COCCO is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
constructor() public {
symbol = "COCCO";
name = "COCCO";
decimals = 5;
_totalSupply = 1000000000000;
balances[0x0c859633811986f7bD06244352131F6139E7aB87] = _totalSupply;
emit Transfer(address(0), 0x0c859633811986f7bD06244352131F6139E7aB87, _totalSupply);
}
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
function () public payable {
revert();
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
}
| 2,357,688 |
[
1,
5802,
7620,
4232,
39,
3462,
3155,
16,
598,
326,
2719,
434,
3273,
16,
508,
471,
15105,
471,
1551,
25444,
1147,
29375,
8879,
13849,
8879,
17082,
11417,
8879,
17082,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
7910,
39,
3865,
353,
4232,
39,
3462,
1358,
16,
14223,
11748,
16,
14060,
10477,
288,
203,
565,
533,
1071,
3273,
31,
203,
565,
533,
1071,
225,
508,
31,
203,
565,
2254,
28,
1071,
15105,
31,
203,
565,
2254,
1071,
389,
4963,
3088,
1283,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
13,
324,
26488,
31,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
3719,
2935,
31,
203,
203,
203,
565,
3885,
1435,
1071,
288,
203,
3639,
3273,
273,
315,
3865,
39,
3865,
14432,
203,
3639,
508,
273,
315,
3865,
39,
3865,
14432,
203,
3639,
15105,
273,
1381,
31,
203,
3639,
389,
4963,
3088,
1283,
273,
15088,
9449,
31,
203,
3639,
324,
26488,
63,
20,
92,
20,
71,
28,
6162,
26,
3707,
28,
23635,
5292,
74,
27,
70,
40,
7677,
3247,
24,
4763,
22,
29315,
42,
26,
24347,
41,
27,
69,
38,
11035,
65,
273,
389,
4963,
3088,
1283,
31,
203,
3639,
3626,
12279,
12,
2867,
12,
20,
3631,
374,
92,
20,
71,
28,
6162,
26,
3707,
28,
23635,
5292,
74,
27,
70,
40,
7677,
3247,
24,
4763,
22,
29315,
42,
26,
24347,
41,
27,
69,
38,
11035,
16,
389,
4963,
3088,
1283,
1769,
203,
565,
289,
203,
203,
203,
565,
445,
2078,
3088,
1283,
1435,
1071,
5381,
1135,
261,
11890,
13,
288,
203,
3639,
327,
389,
4963,
3088,
1283,
225,
300,
324,
26488,
63,
2867,
12,
20,
13,
15533,
203,
565,
289,
203,
203,
203,
565,
445,
11013,
951,
12,
2867,
1147,
5541,
13,
1071,
5381,
1135,
261,
11890,
2
] |
pragma solidity ^0.4.17;
contract EtherTransferTo {
function () public payable {
}
function getBalance() public returns (uint) {
return address(this).balance;
}
}
contract EtherTransferFrom {
EtherTransferTo private _instance;
function EtherTransferFrom() public {
// _instamce = EtherTransferTo(address(this));
_instance = new EtherTransferTo();
}
function getBalance() public returns (uint) {
return address(this).balance;
}
function getBalanceOfInstance() public returns (uint) {
// return address(_instance).balance;
return _instance.getBalance();
}
function () public payable {
// msg.sender.send(msg.value)
address(_instance).send(msg.value);
}
}
|
return address(_instance).balance;
|
function getBalanceOfInstance() public returns (uint) {
return _instance.getBalance();
}
| 12,675,182 |
[
1,
2463,
1758,
24899,
1336,
2934,
12296,
31,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2882,
6112,
951,
1442,
1435,
1071,
1135,
261,
11890,
13,
288,
203,
3639,
327,
389,
1336,
18,
588,
13937,
5621,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
// File: contracts/ERC20-token.sol
/**
* @title ERC20 interface
*
*/
contract ERC20 {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
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);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: contracts/OwnableMintable.sol
/**
* @title OwnableMintable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* @dev Added mintOwner address how controls the minting
* functions, this simplifies the implementation of "user permissions".
*/
contract OwnableMintable {
address public owner;
address public mintOwner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event MintOwnershipTransferred(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;
mintOwner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyMintOwner() {
require(msg.sender == mintOwner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
/**
* @dev Allows the current owner to transfer mint control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferMintOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit MintOwnershipTransferred(mintOwner, newOwner);
mintOwner = newOwner;
}
}
// File: contracts/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;
}
function uint2str(uint i) internal pure returns (string){
if (i == 0) return "0";
uint j = i;
uint length;
while (j != 0){
length++;
j /= 10;
}
bytes memory bstr = new bytes(length);
uint k = length - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
}
// File: contracts/BYTM/BYTMToken.sol
/**
*
* @title BYTMToken
* @notice An ERC-20 token designed specifically for crowdsales with investor protection and further development path.
*
*
*/
contract BYTMToken is ERC20, OwnableMintable {
using SafeMath for uint256;
string public constant name = "Bytemine"; // The Token's name
string public constant symbol = "BYTM"; // Identifier
uint8 public constant decimals = 18; // Number of decimals
//Hardcap is 1,000,000,000 + 18 decimals
uint256 hardCap_ = 1000000000 * (10**uint256(18));
//Balances
mapping(address => uint256) balances;
mapping(address => mapping (address => uint256)) internal allowed;
//Minting
event Mint(address indexed to, uint256 amount);
event PauseMinting();
event UnPauseMinting();
//If token is mintable
bool public pauseMinting = false;
//Total supply of tokens
uint256 totalSupply_ = 0;
//Constructor
constructor() public {
}
//Fix for the ERC20 short address attack.
modifier onlyPayloadSize(uint size) {
assert(msg.data.length >= size + 4);
_;
}
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev allowed total number of tokens
*/
function hardCap() public view returns (uint256) {
return hardCap_;
}
/**
* @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 onlyPayloadSize(2 * 32) returns (bool) {
return _transfer(msg.sender, _to, _value);
}
/**
* @dev Internal transfer, only can be called by this contract
* @param _from is msg.sender The address to transfer from.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function _transfer(address _from, address _to, uint _value) internal returns (bool){
require(_to != address(0)); // Prevent transfer to 0x0 address.
require(_value <= balances[msg.sender]); // Check if the sender has enough
// SafeMath.sub will throw if there is not enough balance.
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(_from, _to, _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
*/
function transferFrom(address _from, address _to, uint256 _value) public onlyPayloadSize(3 * 32) returns (bool) {
require(_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead
require(_value <= balances[_from]); // Check if the sender has enough
require(_value <= allowed[_from][msg.sender]); // Check if the sender is allowed to send
// SafeMath.sub will throw if there is not enough balance.
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 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];
}
/**
* @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 spend.
*
* 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;
}
/**
* MintableToken functionality
*/
modifier canMint() {
require(!pauseMinting);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyMintOwner canMint public returns (bool) {
require(_to != address(0)); // Prevent transfer to 0x0 address.
require(totalSupply_.add(_amount) <= hardCap_);
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to pause minting new tokens.
* @notice Pause minting
*/
function toggleMinting() onlyOwner public {
if(pauseMinting){
pauseMinting = false;
emit UnPauseMinting();
}else{
pauseMinting = true;
emit PauseMinting();
}
}
/**
* @dev Owner can transfer other tokens that are sent here by mistake
*
*/
function refundOtherTokens(address _recipient, ERC20 _token) onlyOwner public {
require(_token != this);
uint256 balance = _token.balanceOf(this);
require(_token.transfer(_recipient, balance));
}
}
|
* @dev Owner can transfer other tokens that are sent here by mistake/
|
function refundOtherTokens(address _recipient, ERC20 _token) onlyOwner public {
require(_token != this);
uint256 balance = _token.balanceOf(this);
require(_token.transfer(_recipient, balance));
}
| 5,830,073 |
[
1,
5541,
848,
7412,
1308,
2430,
716,
854,
3271,
2674,
635,
27228,
911,
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,
225,
445,
16255,
8290,
5157,
12,
2867,
389,
20367,
16,
4232,
39,
3462,
389,
2316,
13,
225,
1338,
5541,
1071,
288,
203,
565,
2583,
24899,
2316,
480,
333,
1769,
203,
565,
2254,
5034,
11013,
273,
389,
2316,
18,
12296,
951,
12,
2211,
1769,
203,
565,
2583,
24899,
2316,
18,
13866,
24899,
20367,
16,
11013,
10019,
203,
225,
289,
203,
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,
-100,
-100,
-100,
-100,
-100,
-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
/**
:. .
-==*#%*+=-.
+=+#@*++*##%%#+=:. .:-.
.%*%%**+++++++*@@= .+=: *.+%
++++#%#*******#=#==*+*#%#%%+-
:*=+++*%%#*#***%#@#*****###%#+...
.-+= :#-=+++++*%@%*##[email protected]#**%#[email protected]*++##-
.=##= .+-===++++++*#%#[email protected]#*-::=*@***+=+#+.
.:+= -+-++=.-*-====+++++++++*#*+=++----+#%*****+==##-
.-*% #..:-+*+======+++++++++++====---=+%##*******%@##-
.:*%++====-*=.:::-=======+++++++++++=====--++%@#******#**==##.
.*+:--:--: .:::-=======+++++++++++====--++#%###********[email protected]*:..
-*::::::...::-=======+++++++++++====+*##%@%%##**###****+=%%=:.
.**@*-:: .:::-======++++++++=++*##%%#**##*%%%%%#*******+=%#
[email protected]@@=::..::-=======+**%@@%###*++++#+#*#*#**%%##*******+=%#
. +*#@=:.::-=******#@@%#**===%====+++*===+#*#%@%##******[email protected]+
*:.#[email protected]#***++====+##*+===++**#*======+===+***#*#@%%###***=#@.
#=**+=-+*=========++===+**+===**======+==+++*+####@##****#**@+
*+=-*##+=============**++*%=-=#*=========+*+*+*##*#@##***#*+:
.%+ *@+##+=========***#@= %:==%+============++=****%%#*****+%#
=**+:@++%#=======+#+- %@*[email protected]*#+=============++=+*#%#@%#*****@*
*=:[email protected]@+=*=====**: #@@@*+*+==========++=====+*##*@#*****%@.
*-:-===+:.=====++:....:*#*++=++++++====*+#===+#++***@#****#@=
+=:-========================+*+###*+=+**##====+++*#%@#***#@-
:#:===========================#@@#**+++*%+====*****%%*#*%%=-
*-=========================*%@@@#++++**+====+%####%#*%@+
-*=====================+*%@@@@@#+==+++=====+*######*#%.
*+=================+*#%@@@@@@@@#+==========++***%####**:
++=========++**##%@@@@@@@@@@@%*+==========+***#@%%##**+#
.:: .:--++-=*#%%%@@@@@@@@@@*=---=#%#++========++***#%%%@%*##**+-
=+- .:+=::-#***:::-+#%@%@@*-:=-:::-+**+=========++***#%%%%+-#****++-
=+= ++==#+:::#**%***###%@=:=*****##**+==========++**#%%%%#= ******=#
:*+ -*+++#====###%***####%+-===================++*#%%%%%+=: ******+
:+*--=**= -**+*%%%%%%%%#+::*-=================+*#%@@%*=. ...=++=:
.::. .-=++: .. %:==============++##*+=:: ..==++++++*+++=:.
+=-===========+*%*:=--=.*+++#=++****#****@%+
#:=========+*%*. #==+#+++******###*****#-
-*-=======+*%: .#*****%*****#%#*****#+
++-======+%- -#***#%*#**%%###**#*.
++-=====+%: :=+**%##%#%%%#*=.
=*-====+*%. :=**@%*=-:
.#+=====+#*-:.:-=+*++*=.
-#*======+***++=+*#.
:+##*+====++*#*:
:-=====-:
* Date: March 17th, 2022
*
* ☘️Happy Saint Patrick's Day!
*
* The Aimless Fish Dynasty is dedicated to my ever beautiful Wife, Stephanie, and our three amazing children. Hi Steph! I love you with all my heart.
* ❤️ LHK FOREVER
*
* As I move on from a family business which I personally experienced as toxic to my mental health (ultimately affecting my wife and kids), I want to make all who
* may see this aware, that Stephanie has helped me climb out of the darkness with her energy, resilience, motivation, and get-it-done attitude.
* She has shown me strength in all areas of life, and taught me to see beyond the darkness that had surrounded me in my professional life.
* I am forever grateful to her for this and can't express it enough. I believe everyone needs a Stephanie!
*
* Life is mainly about creating yourself. Who are you going to be? How will others think of you? Have you perhaps lost the plot?
* Surround yourself with inspiring, joyful people, like my Wife, and learn from them. I think this is how you live your best life.
*
* Finally, within this contract I have tried to share and be as open as possible with where we are going with the Aimless Fish Dynasty project.
* I hard coded as much as my current knowledge allowed. Where my knowledge was lacking, I tried to leave fingerprints so you could make sure things occur as they should.
* I hope you join on me and my family on this exciting new journey!
* This is just the beginning.
*
* Founded, developed, and art by: @kenleybrowne
*
* AFD Dynasty DAO: 0x4c5260637C9D39919347C961fAb0fE4CEB79bCdf
* AFD Genesis Fund: 0x23d5041C65151E80E13380f9266EA65FA6E37a8f
* AFD Charity Fund: 0xE88d4a2c86094197036B3D7B7e22275a3A7C0b28
*
*/
pragma solidity ^0.8.7;
import './ERC721Enumerable.sol';
import '@openzeppelin/contracts/access/Ownable.sol';
contract AimlessFishDynasty is ERC721Enumerable, Ownable {
string public AFD_PROVENANCE;
using Address for address;
// This will help the starting and stopping of the sale and presale.
bool public saleActive = false;
bool public presaleActive = false;
// This is the amount of tokens reserved for Free-minting, the team, giveaways, collabs and so forth.
uint256 public reserved = 225;
uint256 public tgcReserved = 30;
// This is the price of each Aimless Fish Dynasty token.
// Up to 28 Aimless Fish Dynasty tokens or 1% of all tokens may be minted at a time.
uint256 public price = 0.035 ether;
uint256 public freePrice = 0.0 ether;
// Max Supply limits the maximum supply of Aimless Fish Dynasty tokens that can exist.
// Free Max Supply allows up to 220 free mints to the community & public.
uint256 constant max_SUPPLY = 2750;
uint256 constant freeMAX_SUPPLY = 255; // Up to 220 for Free Mint + 30 Reserved + 5 tokens for the Founder, his wife, and their three little kiddos.
// This is the base link that leads to the images of the Aimless Fish tokens.
// This will be transitioned to IPFS after minting is complete.
string public baseURI;
// Allows us to set the provenance for the entire collection.
function setProvenance(string memory provenance) public onlyOwner {
AFD_PROVENANCE = provenance;
}
// This allows for gasless Opensea Listing.
address public proxyRegistryAddress;
// The following are the addresses for withdrawals.
address public a1_DAO = 0x4c5260637C9D39919347C961fAb0fE4CEB79bCdf; // Aimless Fish Dynasty DAO
address public a2_OMM = 0x3097617CbA85A26AdC214A1F87B680bE4b275cD0; // OMM&S Consulting and Marketing Team
address public a3_DTC = 0xE88d4a2c86094197036B3D7B7e22275a3A7C0b28; // The AFD Charity Fund to Be Donated
address public a4_ADT = 0xf770C9AC6bE46FF9D02e59945Ae54030A8A92d3F; // Founder @kenleybrowne
// Additionally, the AFD Genesis Fund:0x23d5041C65151E80E13380f9266EA65FA6E37a8f will be set to receive secondary sales royalities on OS & LR.
// 60% of the Genesis Fund will be forwarded to the DAO, while the final 40% will be used to further the project’s growth and development.
// This is for reserved presale tokens.
mapping (address => uint256) public presaleReserved;
// This makes sure if someone already did a FREE mint, then they can no longer do so. We would love if you purchased one as well :)
mapping(address => uint256) private _claimed;
// This allows for gasless Opensea Listing.
mapping(address => bool) public projectProxy;
// This allows for gas(less) future collection approval for cross-collection interaction.
mapping(address => bool) public proxyToApproved;
// This initializes The Aimless Fish Dynasty contract and designates the name and symbol.
constructor (string memory _baseURI, address _proxyRegistryAddress) ERC721("Aimless Fish Dynasty", "AFD") {
baseURI = _baseURI;
proxyRegistryAddress = _proxyRegistryAddress;
// Kenley, the founder is gifting his Wife & three young kiddos the first four fish, plus retaining one for his continued access to the Dynasty.
// These will be held in the his wallet and transfered to them in the future so they may access the Dynasty.
_safeMint( a4_ADT, 0);
_safeMint( a4_ADT, 1);
_safeMint( a4_ADT, 2);
_safeMint( a4_ADT, 3);
_safeMint( a4_ADT, 4);
}
// To update the tokenURI.
// All metadata & images will be on IPFS once mint is complete.
function setBaseURI(string memory _baseURI) public onlyOwner {
baseURI = _baseURI;
}
//
function tokenURI(uint256 _tokenId) public view override returns (string memory) {
require(_exists(_tokenId), "Token does not exist.");
return string(abi.encodePacked(baseURI, Strings.toString(_tokenId)));
}
// This helps see which address owns which tokens.
function tokensOfOwner(address addr) public view returns(uint256[] memory) {
uint256 tokenCount = balanceOf(addr);
uint256[] memory tokensId = new uint256[](tokenCount);
for(uint256 i; i < tokenCount; i++){
tokensId[i] = tokenOfOwnerByIndex(addr, i);
}
return tokensId;
}
// This allows for gasless Opensea Listing.
function setProxyRegistryAddress(address _proxyRegistryAddress) external onlyOwner {
proxyRegistryAddress = _proxyRegistryAddress;
}
// This allows for gas(less) future collection approval for cross-collection interaction.
function flipProxyState(address proxyAddress) public onlyOwner {
projectProxy[proxyAddress] = !projectProxy[proxyAddress];
}
// This is for the exclusive FREE-sale/Reserved presale minting ability.
function mintPresale(uint256 _amount) public payable {
uint256 supply = totalSupply();
uint256 reservedAmt = presaleReserved[msg.sender];
require( presaleActive, "The AFD presale isn't active yet." );
require( reservedAmt > 0, "There are no tokens reserved for your address." );
require( _amount <= reservedAmt, "You are not able to mint more than what is reserved to you." );
require( supply + _amount <= freeMAX_SUPPLY, "You are not able to mint more than the max supply of FREE Aimless Fish." );
require( msg.value == freePrice * _amount, "Opps! You sent the wrong amount of ETH." );
presaleReserved[msg.sender] = reservedAmt - _amount;
for(uint256 i; i < _amount; i++){
_safeMint( msg.sender, supply + i );
}
}
// This is for the Public minting ability.
function mintToken(uint256 _amount) public payable {
uint256 supply = totalSupply();
require( saleActive, "The AFD public sale isn't active." );
require( supply + _amount <= max_SUPPLY, "You are not able to mint more than max supply of total Aimless Fish." );
require( _amount > 0 && _amount < 29, "You are able to mint between 1-28 AFD tokens at the same time." );
require( supply + _amount <= max_SUPPLY, "You are not able to mint more than max supply of total Aimless Fish." );
require( msg.value == price * _amount, "Opps! You sent the wrong amount of ETH." );
for(uint256 i; i < _amount; i++){
_safeMint( msg.sender, supply + i );
}
}
// This is for the FREE minting ability during public sale.
// Important: The fish will no longer be free when the total fish minted, including paid mints, passes 255. Don't try or you risk losing your gas!
function mintFREEToken(uint256 _amount) public payable {
uint256 supply = totalSupply();
require( saleActive, "The AFD public sale isn't active." );
require( _claimed[msg.sender] == 0, "Your Free token is already claimed.");
require( _amount > 0 && _amount < 2, "You are able to mint one (1) Free AFD token." );
require( supply + _amount <= freeMAX_SUPPLY, "You are not able to mint more than max supply of FREE Aimless Fish." );
require( msg.value == freePrice * _amount, "Opps! You sent the wrong amount of ETH." );
for(uint256 i; i < _amount; i++){
_claimed[msg.sender] += 1;
_safeMint( msg.sender, supply + i );
}
}
// Admin minting function to reserve tokens for the team, collabs, customs and giveaways.
function mintReserved(uint256 _amount) public onlyOwner {
// Limited to a publicly set amount as shown above.
require( _amount <= tgcReserved, "You are not able to reserve more than the set amount." );
tgcReserved -= _amount;
uint256 supply = totalSupply();
for(uint256 i; i < _amount; i++){
_safeMint( msg.sender, supply + i );
}
}
// This lets us add to and edit reserved presale spots.
function editPresaleReserved(address[] memory _a, uint256[] memory _amount) public onlyOwner {
for(uint256 i; i < _a.length; i++){
presaleReserved[_a[i]] = _amount[i];
}
}
// This allows us to start and stop the AFD presale.
function setPresaleActive(bool val) public onlyOwner {
presaleActive = val;
}
// This allows us to start and stop the AFD Public sale.
function setSaleActive(bool val) public onlyOwner {
saleActive = val;
}
// This allows us to set a different selling price in case ETH changes drastically.
function setPrice(uint256 newPrice) public onlyOwner {
price = newPrice;
}
// Withdraw funds from inital sales for the team, DAO, Charity and founder.
function withdrawTeam(uint256 amount) public payable onlyOwner {
uint256 percent = amount / 100;
require(payable(a1_DAO).send(percent * 33)); // 33% for the community-lead Aimless Fish Dynasty DAO.
require(payable(a2_OMM).send(percent * 25)); // 25% for the OMM&S Consulting and Marketing Team.
require(payable(a3_DTC).send(percent * 5)); // 5% to be Distributed to Charities that support Earth and Ocean conservation.
require(payable(a4_ADT).send(percent * 38)); // 38% to further the project’s growth & development plus initial founders dev & marketing expenses.
}
// Allows gasless listing on Opensea and LooksRare.
// Sumitted during Deployment of contract OS Mainnet: 0xa5409ec958c83c3f309868babaca7c86dcb077c1
// NOT CODED (added after contract is deployed) LooksRare Mainnet: 0xf42aa99F011A1fA7CDA90E5E98b277E306BcA83e
// Also allows gas(less) future collection approval for cross-collection interaction including LooksRare.
function isApprovedForAll(address _owner, address operator) public view override returns (bool) {
OpenSeaProxyRegistry proxyRegistry = OpenSeaProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(_owner)) == operator || projectProxy[operator]) return true;
return super.isApprovedForAll(_owner, operator);
}
}
contract OwnableDelegateProxy { }
contract OpenSeaProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
/**
*
* Wherever you happen to be in the world, together, greater collective enlightenment is what we must strive for.
* Thank you for joining me and my family on this journey.
* Let's raise each other up.
*
* Cheers,
* Kenley
*
*/
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import "./ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account but rips out the core of the gas-wasting processing that comes from OpenZeppelin.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _owners.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < _owners.length, "ERC721Enumerable: global index out of bounds");
return index;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256 tokenId) {
require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
uint count;
for(uint i; i < _owners.length; i++){
if(owner == _owners[i]){
if(count == index) return i;
else count++;
}
}
revert("ERC721Enumerable: owner index out of bounds");
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "./Address.sol";
abstract contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
string private _name;
string private _symbol;
// Mapping from token ID to owner address
address[] internal _owners;
mapping(uint256 => address) private _tokenApprovals;
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165, IERC165)
returns (bool)
{
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner)
public
view
virtual
override
returns (uint)
{
require(owner != address(0), "ERC721: balance query for the zero address");
uint count;
for( uint i; i < _owners.length; ++i ){
if( owner == _owners[i] )
++count;
}
return count;
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId)
public
view
virtual
override
returns (address)
{
address owner = _owners[tokenId];
require(
owner != address(0),
"ERC721: owner query for nonexistent token"
);
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId)
public
view
virtual
override
returns (address)
{
require(
_exists(tokenId),
"ERC721: approved query for nonexistent token"
);
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved)
public
virtual
override
{
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return tokenId < _owners.length && _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId)
internal
view
virtual
returns (bool)
{
require(
_exists(tokenId),
"ERC721: operator query for nonexistent token"
);
address owner = ERC721.ownerOf(tokenId);
return (spender == owner ||
getApproved(tokenId) == spender ||
isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_owners.push(to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_owners[tokenId] = address(0);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(
ERC721.ownerOf(tokenId) == from,
"ERC721: transfer of token that is not own"
);
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try
IERC721Receiver(to).onERC721Received(
_msgSender(),
from,
tokenId,
_data
)
returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert(
"ERC721: transfer to non ERC721Receiver implementer"
);
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;
library Address {
function isContract(address account) internal view returns (bool) {
uint size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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);
}
|
The AFD Charity Fund to Be Donated
|
address public a3_DTC = 0xE88d4a2c86094197036B3D7B7e22275a3A7C0b28;
| 13,477,682 |
[
1,
1986,
10888,
40,
3703,
560,
478,
1074,
358,
4823,
7615,
690,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1758,
1071,
279,
23,
67,
9081,
39,
273,
374,
17432,
5482,
72,
24,
69,
22,
71,
28,
4848,
11290,
31728,
4630,
26,
38,
23,
40,
27,
38,
27,
73,
3787,
5324,
25,
69,
23,
37,
27,
39,
20,
70,
6030,
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
] |
./full_match/42220/0x0AbcaDdc3F22131b467F3f4E5cef6007e4a53268/sources/contracts/Factory.sol
|
* @notice produces new instance with defined name and symbol @param _info The new instance's info @return The new instance's address/
|
function produce(
InstanceInfo memory _info
) external returns (address) {
require(
_verifySignature(
_info.name,
_info.symbol,
_info.contractURI,
_info.feeNumerator,
_info.feeReceiver,
_info.signature
),
"Invalid signature"
);
_createInstanceValidate(_info.name, _info.symbol);
address instanceCreated = _createInstance(_info.name, _info.symbol);
require(
instanceCreated != address(0),
"Factory: INSTANCE_CREATION_FAILED"
);
NFT.Parameters memory params = NFT.Parameters(
storageContract,
_info.payingToken,
_info.mintPrice,
_info.whitelistMintPrice,
_info.contractURI,
_info.name,
_info.symbol,
_info.transferable,
_info.maxTotalSupply,
_info.feeReceiver,
_info.feeNumerator,
_info.collectionExpire,
_msgSender()
);
NFT(payable(instanceCreated)).initialize(params);
return instanceCreated;
}
| 16,360,342 |
[
1,
11776,
764,
394,
791,
598,
2553,
508,
471,
3273,
225,
389,
1376,
1021,
394,
791,
1807,
1123,
327,
1021,
394,
791,
1807,
1758,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
11402,
12,
203,
3639,
5180,
966,
3778,
389,
1376,
203,
565,
262,
3903,
1135,
261,
2867,
13,
288,
203,
3639,
2583,
12,
203,
5411,
389,
8705,
5374,
12,
203,
7734,
389,
1376,
18,
529,
16,
7010,
7734,
389,
1376,
18,
7175,
16,
7010,
7734,
389,
1376,
18,
16351,
3098,
16,
203,
7734,
389,
1376,
18,
21386,
2578,
7385,
16,
7010,
7734,
389,
1376,
18,
21386,
12952,
16,
7010,
7734,
389,
1376,
18,
8195,
203,
5411,
262,
16,
203,
5411,
315,
1941,
3372,
6,
203,
3639,
11272,
203,
3639,
389,
2640,
1442,
4270,
24899,
1376,
18,
529,
16,
389,
1376,
18,
7175,
1769,
203,
3639,
1758,
791,
6119,
273,
389,
2640,
1442,
24899,
1376,
18,
529,
16,
389,
1376,
18,
7175,
1769,
203,
3639,
2583,
12,
203,
5411,
791,
6119,
480,
1758,
12,
20,
3631,
203,
5411,
315,
1733,
30,
6937,
67,
5458,
2689,
67,
11965,
6,
203,
3639,
11272,
203,
3639,
423,
4464,
18,
2402,
3778,
859,
273,
423,
4464,
18,
2402,
12,
203,
5411,
2502,
8924,
16,
203,
5411,
389,
1376,
18,
10239,
310,
1345,
16,
203,
5411,
389,
1376,
18,
81,
474,
5147,
16,
203,
5411,
389,
1376,
18,
20409,
49,
474,
5147,
16,
203,
5411,
389,
1376,
18,
16351,
3098,
16,
203,
5411,
389,
1376,
18,
529,
16,
203,
5411,
389,
1376,
18,
7175,
16,
203,
5411,
389,
1376,
18,
13866,
429,
16,
203,
5411,
389,
1376,
18,
1896,
5269,
3088,
1283,
16,
203,
5411,
389,
1376,
18,
21386,
12952,
16,
203,
5411,
389,
1376,
18,
21386,
2578,
7385,
2
] |
pragma solidity 0.4.23;
import 'mixbytes-solidity/contracts/security/ArgumentsChecker.sol';
import 'zeppelin-solidity/contracts/ReentrancyGuard.sol';
import './EthPriceDependentForICO.sol';
import './crowdsale/FundsRegistry.sol';
import './IBoomstarterToken.sol';
import '../minter-service/contracts/IICOInfo.sol';
import '../minter-service/contracts/IMintableToken.sol';
/// @title Boomstarter ICO contract
contract BoomstarterICO is ArgumentsChecker, ReentrancyGuard, EthPriceDependentForICO, IICOInfo, IMintableToken {
enum IcoState { INIT, ACTIVE, PAUSED, FAILED, SUCCEEDED }
event StateChanged(IcoState _state);
event FundTransfer(address backer, uint amount, bool isContribution);
modifier requiresState(IcoState _state) {
require(m_state == _state);
_;
}
/// @dev triggers some state changes based on current time
/// @param client optional refund parameter
/// @param payment optional refund parameter
/// @param refundable - if false, payment is made off-chain and shouldn't be refunded
/// note: function body could be skipped!
modifier timedStateChange(address client, uint payment, bool refundable) {
if (IcoState.INIT == m_state && getTime() >= getStartTime())
changeState(IcoState.ACTIVE);
if (IcoState.ACTIVE == m_state && getTime() >= getFinishTime()) {
finishICO();
if (refundable && payment > 0)
client.transfer(payment);
// note that execution of further (but not preceding!) modifiers and functions ends here
} else {
_;
}
}
/// @dev automatic check for unaccounted withdrawals
/// @param client optional refund parameter
/// @param payment optional refund parameter
/// @param refundable - if false, payment is made off-chain and shouldn't be refunded
modifier fundsChecker(address client, uint payment, bool refundable) {
uint atTheBeginning = m_funds.balance;
if (atTheBeginning < m_lastFundsAmount) {
changeState(IcoState.PAUSED);
if (refundable && payment > 0)
client.transfer(payment); // we cant throw (have to save state), so refunding this way
// note that execution of further (but not preceding!) modifiers and functions ends here
} else {
_;
if (m_funds.balance < atTheBeginning) {
changeState(IcoState.PAUSED);
} else {
m_lastFundsAmount = m_funds.balance;
}
}
}
function estimate(uint256 _wei) public view returns (uint tokens) {
uint amount;
(amount, ) = estimateTokensWithActualPayment(_wei);
return amount;
}
function isSaleActive() public view returns (bool active) {
return m_state == IcoState.ACTIVE && !priceExpired();
}
function purchasedTokenBalanceOf(address addr) public view returns (uint256 tokens) {
return m_token.balanceOf(addr);
}
function estimateTokensWithActualPayment(uint256 _payment) public view returns (uint amount, uint actualPayment) {
// amount of bought tokens
uint tokens = _payment.mul(m_ETHPriceInCents).div(getPrice());
if (tokens.add(m_currentTokensSold) > c_maximumTokensSold) {
tokens = c_maximumTokensSold.sub( m_currentTokensSold );
_payment = getPrice().mul(tokens).div(m_ETHPriceInCents);
}
// calculating a 20% bonus if the price of bought tokens is more than $50k
if (_payment.mul(m_ETHPriceInCents).div(1 ether) >= 5000000) {
tokens = tokens.add(tokens.div(5));
// for ICO, bonus cannot exceed hard cap
if (tokens.add(m_currentTokensSold) > c_maximumTokensSold) {
tokens = c_maximumTokensSold.sub(m_currentTokensSold);
}
}
return (tokens, _payment);
}
// PUBLIC interface
/**
* @dev constructor
* @param _owners addresses to do administrative actions
* @param _token address of token being sold
* @param _updateInterval time between oraclize price updates in seconds
* @param _production false if using testrpc/ganache, true otherwise
*/
function BoomstarterICO(
address[] _owners,
address _token,
uint _updateInterval,
bool _production
)
public
payable
EthPriceDependent(_owners, 2, _production)
validAddress(_token)
{
require(3 == _owners.length);
m_token = IBoomstarterToken(_token);
m_deployer = msg.sender;
m_ETHPriceUpdateInterval = _updateInterval;
oraclize_setCustomGasPrice(40000000);
}
/// @dev set addresses for ether and token storage
/// performed once by deployer
/// @param _funds FundsRegistry address
/// @param _tokenDistributor address to send remaining tokens to after ICO
/// @param _previouslySold how much sold in previous sales in cents
function init(address _funds, address _tokenDistributor, uint _previouslySold)
external
validAddress(_funds)
validAddress(_tokenDistributor)
onlymanyowners(keccak256(msg.data))
{
// can be set only once
require(m_funds == address(0));
m_funds = FundsRegistry(_funds);
// calculate remaining tokens and leave 25% for manual allocation
c_maximumTokensSold = m_token.balanceOf(this).sub( m_token.totalSupply().div(4) );
// manually set how much should be sold taking into account previously collected
if (_previouslySold < c_softCapUsd)
c_softCapUsd = c_softCapUsd.sub(_previouslySold);
else
c_softCapUsd = 0;
// set account that allocates the rest of tokens after ico succeeds
m_tokenDistributor = _tokenDistributor;
}
// PUBLIC interface: payments
// fallback function as a shortcut
function() payable {
require(0 == msg.data.length);
buy(); // only internal call here!
}
/// @notice ICO participation
function buy() public payable { // dont mark as external!
internalBuy(msg.sender, msg.value, true);
}
function mint(address client, uint256 ethers) public {
nonEtherBuy(client, ethers);
}
/// @notice register investments coming in different currencies
/// @dev can only be called by a special controller account
/// @param client Account to send tokens to
/// @param etherEquivalentAmount Amount of ether to use to calculate token amount
function nonEtherBuy(address client, uint etherEquivalentAmount)
public
{
require(msg.sender == m_nonEtherController);
// just to check for input errors
require(etherEquivalentAmount <= 70000 ether);
internalBuy(client, etherEquivalentAmount, false);
}
/// @dev common buy for ether and non-ether
/// @param client who invests
/// @param payment how much ether
/// @param refundable true if invested in ether - using buy()
function internalBuy(address client, uint payment, bool refundable)
internal
nonReentrant
timedStateChange(client, payment, refundable)
fundsChecker(client, payment, refundable)
{
// don't allow to buy anything if price change was too long ago
// effectively enforcing a sale pause
require( !priceExpired() );
require(m_state == IcoState.ACTIVE || m_state == IcoState.INIT && isOwner(client) /* for final test */);
require((payment.mul(m_ETHPriceInCents)).div(1 ether) >= c_MinInvestmentInCents);
uint actualPayment = payment;
uint amount;
(amount, actualPayment) = estimateTokensWithActualPayment(payment);
// change ICO investment stats
m_currentUsdAccepted = m_currentUsdAccepted.add( actualPayment.mul(m_ETHPriceInCents).div(1 ether) );
m_currentTokensSold = m_currentTokensSold.add( amount );
// send bought tokens to the client
m_token.transfer(client, amount);
assert(m_currentTokensSold <= c_maximumTokensSold);
if (refundable) {
// record payment if paid in ether
m_funds.invested.value(actualPayment)(client, amount);
FundTransfer(client, actualPayment, true);
}
// check if ICO must be closed early
if (payment.sub(actualPayment) > 0) {
assert(c_maximumTokensSold == m_currentTokensSold);
finishICO();
// send change
client.transfer(payment.sub(actualPayment));
} else if (c_maximumTokensSold == m_currentTokensSold) {
finishICO();
}
}
// PUBLIC interface: misc getters
/// @notice get token price in cents depending on the current date
function getPrice() public view returns (uint) {
// skip finish date, start from the date of maximum price
for (uint i = c_priceChangeDates.length - 2; i > 0; i--) {
if (getTime() >= c_priceChangeDates[i]) {
return c_tokenPrices[i];
}
}
// default price is the cheapest, used for the initial test as well
return c_tokenPrices[0];
}
/// @notice start time of the ICO
function getStartTime() public view returns (uint) {
return c_priceChangeDates[0];
}
/// @notice finish time of the ICO
function getFinishTime() public view returns (uint) {
return c_priceChangeDates[c_priceChangeDates.length - 1];
}
// PUBLIC interface: owners: maintenance
/// @notice pauses ICO
function pause()
external
timedStateChange(address(0), 0, true)
requiresState(IcoState.ACTIVE)
onlyowner
{
changeState(IcoState.PAUSED);
}
/// @notice resume paused ICO
function unpause()
external
timedStateChange(address(0), 0, true)
requiresState(IcoState.PAUSED)
onlymanyowners(keccak256(msg.data))
{
changeState(IcoState.ACTIVE);
checkTime();
}
/// @notice withdraw tokens if ico failed
/// @param _to address to send tokens to
/// @param _amount amount of tokens in token-wei
function withdrawTokens(address _to, uint _amount)
external
validAddress(_to)
requiresState(IcoState.FAILED)
onlymanyowners(keccak256(msg.data))
{
require((_amount > 0) && (m_token.balanceOf(this) >= _amount));
m_token.transfer(_to, _amount);
}
/// @notice In case we need to attach to existent funds
function setFundsRegistry(address _funds)
external
validAddress(_funds)
timedStateChange(address(0), 0, true)
requiresState(IcoState.PAUSED)
onlymanyowners(keccak256(msg.data))
{
m_funds = FundsRegistry(_funds);
}
/// @notice set non ether investment controller
function setNonEtherController(address _controller)
external
validAddress(_controller)
timedStateChange(address(0), 0, true)
onlymanyowners(keccak256(msg.data))
{
m_nonEtherController = _controller;
}
function getNonEtherController()
public
view
returns (address)
{
return m_nonEtherController;
}
/// @notice explicit trigger for timed state changes
function checkTime()
public
timedStateChange(address(0), 0, true)
onlyowner
{
}
/// @notice send everything to the new (fixed) ico smart contract
/// @param newICO address of the new smart contract
function applyHotFix(address newICO)
public
validAddress(newICO)
requiresState(IcoState.PAUSED)
onlymanyowners(keccak256(msg.data))
{
EthPriceDependent next = EthPriceDependent(newICO);
next.topUp.value(this.balance)();
m_token.transfer(newICO, m_token.balanceOf(this));
}
/// @notice withdraw all ether for oraclize payments
/// @param to Address to send ether to
function withdrawEther(address to)
public
validAddress(to)
onlymanyowners(keccak256(msg.data))
{
to.transfer(this.balance);
}
// INTERNAL functions
function finishICO() private {
if (m_currentUsdAccepted < c_softCapUsd) {
changeState(IcoState.FAILED);
} else {
changeState(IcoState.SUCCEEDED);
}
}
/// @dev performs only allowed state transitions
function changeState(IcoState _newState) private {
assert(m_state != _newState);
if (IcoState.INIT == m_state) {
assert(IcoState.ACTIVE == _newState);
} else if (IcoState.ACTIVE == m_state) {
assert(
IcoState.PAUSED == _newState ||
IcoState.FAILED == _newState ||
IcoState.SUCCEEDED == _newState
);
} else if (IcoState.PAUSED == m_state) {
assert(IcoState.ACTIVE == _newState || IcoState.FAILED == _newState);
} else {
assert(false);
}
m_state = _newState;
StateChanged(m_state);
// this should be tightly linked
if (IcoState.SUCCEEDED == m_state) {
onSuccess();
} else if (IcoState.FAILED == m_state) {
onFailure();
}
}
function onSuccess() private {
// allow owners to withdraw collected ether
m_funds.changeState(FundsRegistry.State.SUCCEEDED);
m_funds.detachController();
// send all remaining tokens to the address responsible for dividing them into pools
m_token.transfer(m_tokenDistributor, m_token.balanceOf(this));
}
function onFailure() private {
// allow clients to get their ether back
m_funds.changeState(FundsRegistry.State.REFUNDING);
m_funds.detachController();
}
// FIELDS
/// @notice points in time when token price grows
/// first one is the start time of sale
/// last one is the end of sale
uint[] public c_priceChangeDates = [
getTime(), // deployment date: $0.8
1534107600, // August 13th 2018, 00:00:00 (GMT +3): $1
1534712400, // August 20th 2018, 00:00:00 (GMT +3): $1.2
1535317200, // August 27th 2018, 00:00:00 (GMT +3): $1.4
1535922000, // September 3rd 2018, 00:00:00 (GMT +3): $1.6
1536526800, // September 10th 2018, 00:00:00 (GMT +3): $1.8
1537131600, // September 17th 2018, 00:00:00 (GMT +3): $2
1538341199 // finish: September 30th 2018, 23:59:59 (GMT +3)
];
/// @notice token prices in cents during different time periods
/// starts of the time periods described in c_priceChangeDates
uint[] public c_tokenPrices = [
80, // $0.8
100, // $1
120, // $1.2
140, // $1.4
160, // $1.6
180, // $1.8
200 // $2
];
/// @dev state of the ICO
IcoState public m_state = IcoState.INIT;
/// @dev contract responsible for token accounting
IBoomstarterToken public m_token;
/// @dev address responsile for allocation of the tokens left if ICO succeeds
address public m_tokenDistributor;
/// @dev contract responsible for investments accounting
FundsRegistry public m_funds;
/// @dev account handling investments in different currencies
address public m_nonEtherController;
/// @dev last recorded funds
uint public m_lastFundsAmount;
/// @notice minimum investment in cents
uint public c_MinInvestmentInCents = 500; // $5
/// @notice current amount of tokens sold
uint public m_currentTokensSold;
/// @dev limit of tokens to be sold during ICO, need to leave 25% for the team
/// calculated from the current balance and the total supply
uint public c_maximumTokensSold;
/// @dev current usd accepted during ICO, in cents
uint public m_currentUsdAccepted;
/// @dev limit of usd to be accepted during ICO, in cents
uint public c_softCapUsd = 300000000; // $3000000
/// @dev save deployer for easier initialization
address public m_deployer;
}
|
@notice send everything to the new (fixed) ico smart contract @param newICO address of the new smart contract
|
{
EthPriceDependent next = EthPriceDependent(newICO);
next.topUp.value(this.balance)();
m_token.transfer(newICO, m_token.balanceOf(this));
}
| 13,040,855 |
[
1,
4661,
7756,
358,
326,
394,
261,
12429,
13,
277,
2894,
13706,
6835,
225,
394,
2871,
51,
1758,
434,
326,
394,
13706,
6835,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
288,
203,
3639,
512,
451,
5147,
18571,
1024,
273,
512,
451,
5147,
18571,
12,
2704,
2871,
51,
1769,
203,
3639,
1024,
18,
3669,
1211,
18,
1132,
12,
2211,
18,
12296,
13,
5621,
203,
3639,
312,
67,
2316,
18,
13866,
12,
2704,
2871,
51,
16,
312,
67,
2316,
18,
12296,
951,
12,
2211,
10019,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.17;
library SafeMath {
/**
* Sub function asserts that b is less than or equal to a.
* */
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* Add function avoids overflow.
* */
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant public returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant public returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
//keeps a record of the total balances of each ETH address.
mapping (address => uint256) balances;
modifier onlyPayloadSize(uint size) {
if (msg.data.length < size + 4) {
revert();
}
_;
}
/**
* Transfer function makes it possible for users to transfer their Hire tokens to another
* ETH address.
*
* @param _to the address of the recipient.
* @param _amount the amount of Hire tokens to be sent.
* */
function transfer(address _to, uint256 _amount) public onlyPayloadSize(2 * 32) returns (bool) {
require(balances[msg.sender] >= _amount);
balances[msg.sender] = balances[msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
Transfer(msg.sender, _to, _amount);
return true;
}
/**
* BalanceOf function returns the total balance of the queried address.
*
* @param _addr the address which is being queried.
* */
function balanceOf(address _addr) public constant returns (uint256) {
return balances[_addr];
}
}
contract AdvancedToken is BasicToken, ERC20 {
//keeps a record of all the allowances from one ETH address to another.
mapping (address => mapping (address => uint256)) allowances;
/**
* TransferFrom function allows users to spend ETH on another's behalf, given that the _owner
* has allowed them to.
*
* @param _from the address of the owner.
* @param _to the address of the recipient.
* @param _amount the total amount of tokens to be sent. '
* */
function transferFrom(address _from, address _to, uint256 _amount) public onlyPayloadSize(3 * 32) returns (bool) {
require(allowances[_from][msg.sender] >= _amount && balances[_from] >= _amount);
allowances[_from][msg.sender] = allowances[_from][msg.sender].sub(_amount);
balances[_from] = balances[_from].sub(_amount);
balances[_to] = balances[_to].add(_amount);
Transfer(_from, _to, _amount);
return true;
}
/**
* Approve function allows users to allow others to spend a specified amount tokens on
* their behalf.
*
* @param _spender the address of the spended who is being granted permission to spend tokens.
* @param _amount the total amount of tokens the spender is allowed to spend.
* */
function approve(address _spender, uint256 _amount) public returns (bool) {
allowances[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
/**
* Allowance function returns the total allowance from one address to another.
*
* @param _owner the address of the owner of the token.
* @param _spender the address of the spender who has or has not been allowed to spend
* the owners tokens.
* */
function allowance(address _owner, address _spender) public constant returns (uint256) {
return allowances[_owner][_spender];
}
}
contract Hire is AdvancedToken {
uint8 public decimals;
string public name;
string public symbol;
address public owner;
/**
* Constructor initializes the total supply to 100,000,000, the token name to
* Hire, the token symbol to HIRE, sets the decimals to 18 and automatically
* sends all tokens to the owner of the contract upon deployment.
* */
function Hire() public {
totalSupply = 100000000e18;
decimals = 18;
name = "Hire";
symbol = "HIRE";
owner = 0xaAa34A22Bd3F496b3A8648367CeeA9c03B130A30;
balances[owner] = totalSupply;
}
}
|
keeps a record of the total balances of each ETH address.
|
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping (address => uint256) balances;
modifier onlyPayloadSize(uint size) {
if (msg.data.length < size + 4) {
revert();
}
_;
}
modifier onlyPayloadSize(uint size) {
if (msg.data.length < size + 4) {
revert();
}
_;
}
function transfer(address _to, uint256 _amount) public onlyPayloadSize(2 * 32) returns (bool) {
require(balances[msg.sender] >= _amount);
balances[msg.sender] = balances[msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
Transfer(msg.sender, _to, _amount);
return true;
}
function balanceOf(address _addr) public constant returns (uint256) {
return balances[_addr];
}
}
| 12,614,232 |
[
1,
10102,
87,
279,
1409,
434,
326,
2078,
324,
26488,
434,
1517,
512,
2455,
1758,
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,
16351,
7651,
1345,
353,
4232,
39,
3462,
8252,
288,
203,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
324,
26488,
31,
203,
203,
565,
9606,
1338,
6110,
1225,
12,
11890,
963,
13,
288,
203,
3639,
309,
261,
3576,
18,
892,
18,
2469,
411,
963,
397,
1059,
13,
288,
203,
3639,
15226,
5621,
203,
3639,
289,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
9606,
1338,
6110,
1225,
12,
11890,
963,
13,
288,
203,
3639,
309,
261,
3576,
18,
892,
18,
2469,
411,
963,
397,
1059,
13,
288,
203,
3639,
15226,
5621,
203,
3639,
289,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
445,
7412,
12,
2867,
389,
869,
16,
2254,
5034,
389,
8949,
13,
1071,
1338,
6110,
1225,
12,
22,
380,
3847,
13,
1135,
261,
6430,
13,
288,
203,
3639,
2583,
12,
70,
26488,
63,
3576,
18,
15330,
65,
1545,
389,
8949,
1769,
203,
3639,
324,
26488,
63,
3576,
18,
15330,
65,
273,
324,
26488,
63,
3576,
18,
15330,
8009,
1717,
24899,
8949,
1769,
203,
3639,
324,
26488,
63,
67,
869,
65,
273,
324,
26488,
63,
67,
869,
8009,
1289,
24899,
8949,
1769,
203,
3639,
12279,
12,
3576,
18,
15330,
16,
389,
869,
16,
389,
8949,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
565,
445,
11013,
951,
12,
2867,
389,
4793,
13,
1071,
5381,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
324,
26488,
63,
67,
4793,
15533,
203,
565,
289,
203,
97,
203,
2
] |
./partial_match/8453/0xAaF7457c6F32C67928eb6F31A02d6870629259e7/sources/EuphoriaMDMA.sol
|
sets presaleContract to give permission to send tokens
|
function setPresaleContract(address _presaleContract) external onlyOwner {
presaleContract = _presaleContract;
}
| 16,758,489 |
[
1,
4424,
4075,
5349,
8924,
358,
8492,
4132,
358,
1366,
2430,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
444,
12236,
5349,
8924,
12,
2867,
389,
12202,
5349,
8924,
13,
3903,
1338,
5541,
288,
203,
3639,
4075,
5349,
8924,
273,
389,
12202,
5349,
8924,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0xa3a9B86a85d8cB6388e8CF41E810334fE0B7a276/sources/access/AccessControlEnumerableUpgradeable.sol
|
* @dev Extension of {AccessControl} that allows enumerating the members of each role./
|
abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable {
function __AccessControlEnumerable_init() internal onlyInitializing {
}
function __AccessControlEnumerable_init_unchained() internal onlyInitializing {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers;
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
function getRoleMember(bytes32 role, uint256 index) public view virtual override returns (address) {
return _roleMembers[role].at(index);
}
function getRoleMemberCount(bytes32 role) public view virtual override returns (uint256) {
return _roleMembers[role].length();
}
function _grantRole(bytes32 role, address account) internal virtual override {
super._grantRole(role, account);
_roleMembers[role].add(account);
}
function _revokeRole(bytes32 role, address account) internal virtual override {
super._revokeRole(role, account);
_roleMembers[role].remove(account);
}
uint256[49] private __gap;
}
| 7,037,476 |
[
1,
3625,
434,
288,
16541,
97,
716,
5360,
3557,
1776,
326,
4833,
434,
1517,
2478,
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,
17801,
6835,
24349,
3572,
25121,
10784,
429,
353,
10188,
6934,
16,
467,
16541,
3572,
25121,
10784,
429,
16,
24349,
10784,
429,
288,
203,
203,
565,
445,
1001,
16541,
3572,
25121,
67,
2738,
1435,
2713,
1338,
29782,
288,
203,
565,
289,
203,
203,
565,
445,
1001,
16541,
3572,
25121,
67,
2738,
67,
4384,
8707,
1435,
2713,
1338,
29782,
288,
203,
565,
289,
203,
565,
1450,
6057,
25121,
694,
10784,
429,
364,
6057,
25121,
694,
10784,
429,
18,
1887,
694,
31,
203,
203,
565,
2874,
12,
3890,
1578,
516,
6057,
25121,
694,
10784,
429,
18,
1887,
694,
13,
3238,
389,
4615,
6918,
31,
203,
203,
565,
445,
6146,
1358,
12,
3890,
24,
1560,
548,
13,
1071,
1476,
5024,
3849,
1135,
261,
6430,
13,
288,
203,
3639,
327,
1560,
548,
422,
618,
12,
45,
16541,
3572,
25121,
10784,
429,
2934,
5831,
548,
747,
2240,
18,
28064,
1358,
12,
5831,
548,
1769,
203,
565,
289,
203,
203,
565,
445,
15673,
4419,
12,
3890,
1578,
2478,
16,
2254,
5034,
770,
13,
1071,
1476,
5024,
3849,
1135,
261,
2867,
13,
288,
203,
3639,
327,
389,
4615,
6918,
63,
4615,
8009,
270,
12,
1615,
1769,
203,
565,
289,
203,
203,
565,
445,
15673,
4419,
1380,
12,
3890,
1578,
2478,
13,
1071,
1476,
5024,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
389,
4615,
6918,
63,
4615,
8009,
2469,
5621,
203,
565,
289,
203,
203,
565,
445,
389,
16243,
2996,
12,
3890,
1578,
2478,
16,
1758,
2236,
13,
2713,
5024,
3849,
288,
203,
3639,
2240,
6315,
16243,
2996,
12,
4615,
2
] |
./full_match/1/0x7d512690D20EfA2d79e12C7659413b608Bb0eac5/sources/contracts/Multisig.sol
|
* @notice Create a new withdrawal for the payee. One must not already exist (no overwrite and no multiple withdrawals in parallel). @param payee The recipient of the withdrawal. @param amount The amount to withdraw, in wei. @param fee The Eth transaction cost (gas Gwei gas used) to create this withdrawal./
|
function createWithdrawal(address payee, uint256 amount, uint256 fee) external onlyUpstream {
require(withdrawals[payee].amount == 0, "One payment to a payee at a time.");
require(amount > 0, "Invalid amount.");
require(fee > 0, "Invalid fee.");
withdrawals[payee] = Withdrawal(amount, fee, address(0), address(0));
emit WithdrawalCreated(payee, amount, fee);
}
| 8,324,585 |
[
1,
1684,
279,
394,
598,
9446,
287,
364,
326,
8843,
1340,
18,
225,
6942,
1297,
486,
1818,
1005,
261,
2135,
6156,
540,
471,
1158,
3229,
598,
9446,
1031,
316,
7230,
2934,
225,
8843,
1340,
1021,
8027,
434,
326,
598,
9446,
287,
18,
225,
3844,
1021,
3844,
358,
598,
9446,
16,
316,
732,
77,
18,
225,
14036,
1021,
512,
451,
2492,
6991,
261,
31604,
611,
1814,
77,
225,
16189,
1399,
13,
358,
752,
333,
598,
9446,
287,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
225,
445,
752,
1190,
9446,
287,
12,
2867,
8843,
1340,
16,
2254,
5034,
3844,
16,
2254,
5034,
14036,
13,
3903,
1338,
1211,
3256,
288,
203,
565,
2583,
12,
1918,
9446,
1031,
63,
10239,
1340,
8009,
8949,
422,
374,
16,
315,
3335,
5184,
358,
279,
8843,
1340,
622,
279,
813,
1199,
1769,
203,
565,
2583,
12,
8949,
405,
374,
16,
315,
1941,
3844,
1199,
1769,
203,
565,
2583,
12,
21386,
405,
374,
16,
315,
1941,
14036,
1199,
1769,
203,
203,
565,
598,
9446,
1031,
63,
10239,
1340,
65,
273,
3423,
9446,
287,
12,
8949,
16,
14036,
16,
1758,
12,
20,
3631,
1758,
12,
20,
10019,
203,
203,
565,
3626,
3423,
9446,
287,
6119,
12,
10239,
1340,
16,
3844,
16,
14036,
1769,
203,
225,
289,
21281,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/8453/0x5Ba641A1Fa1E6A7D033c9f6A8108d52B92b78257/sources/contracts/HATVault.sol
|
solhint-disable-next-line not-rely-on-time
|
function challengeClaim(bytes32 _claimId) external isActiveClaim(_claimId) {
if (msg.sender != activeClaim.arbitrator && msg.sender != registry.owner())
revert OnlyArbitratorOrRegistryOwner();
if (block.timestamp >= activeClaim.createdAt + activeClaim.challengePeriod)
revert ChallengePeriodEnded();
if (activeClaim.challengedAt != 0) {
revert ClaimAlreadyChallenged();
}
emit ChallengeClaim(_claimId);
}
| 11,548,727 |
[
1,
18281,
11317,
17,
8394,
17,
4285,
17,
1369,
486,
17,
266,
715,
17,
265,
17,
957,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
12948,
9762,
12,
3890,
1578,
389,
14784,
548,
13,
3903,
15083,
9762,
24899,
14784,
548,
13,
288,
203,
3639,
309,
261,
3576,
18,
15330,
480,
2695,
9762,
18,
297,
3682,
86,
639,
597,
1234,
18,
15330,
480,
4023,
18,
8443,
10756,
203,
5411,
15226,
5098,
686,
3682,
86,
639,
1162,
4243,
5541,
5621,
203,
3639,
309,
261,
2629,
18,
5508,
1545,
2695,
9762,
18,
4824,
861,
397,
2695,
9762,
18,
25092,
5027,
13,
203,
5411,
15226,
1680,
8525,
5027,
28362,
5621,
203,
3639,
309,
261,
3535,
9762,
18,
343,
7862,
2423,
861,
480,
374,
13,
288,
203,
5411,
15226,
18381,
9430,
782,
7862,
2423,
5621,
203,
3639,
289,
7010,
3639,
3626,
1680,
8525,
9762,
24899,
14784,
548,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x17b1FF602d824eefFcdF6546FCb87A5C6BC69aDD/sources/RaiseFactory.sol
|
* @return the sold amount of the raise./
|
function getSold() public view returns (uint256) {
return sold;
}
| 2,859,441 |
[
1,
2463,
326,
272,
1673,
3844,
434,
326,
1002,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
1322,
1673,
1435,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
272,
1673,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2022-01-18
*/
pragma solidity 0.6.12;
// SPDX-License-Identifier: GPL-3.0-only
/**
* @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;
}
}
interface IStafiStorage {
// Getters
function getAddress(bytes32 _key) external view returns (address);
function getUint(bytes32 _key) external view returns (uint);
function getString(bytes32 _key) external view returns (string memory);
function getBytes(bytes32 _key) external view returns (bytes memory);
function getBool(bytes32 _key) external view returns (bool);
function getInt(bytes32 _key) external view returns (int);
function getBytes32(bytes32 _key) external view returns (bytes32);
// Setters
function setAddress(bytes32 _key, address _value) external;
function setUint(bytes32 _key, uint _value) external;
function setString(bytes32 _key, string calldata _value) external;
function setBytes(bytes32 _key, bytes calldata _value) external;
function setBool(bytes32 _key, bool _value) external;
function setInt(bytes32 _key, int _value) external;
function setBytes32(bytes32 _key, bytes32 _value) external;
// Deleters
function deleteAddress(bytes32 _key) external;
function deleteUint(bytes32 _key) external;
function deleteString(bytes32 _key) external;
function deleteBytes(bytes32 _key) external;
function deleteBool(bytes32 _key) external;
function deleteInt(bytes32 _key) external;
function deleteBytes32(bytes32 _key) external;
}
abstract contract StafiBase {
// Version of the contract
uint8 public version;
// The main storage contract where primary persistant storage is maintained
IStafiStorage stafiStorage = IStafiStorage(0);
/**
* @dev Throws if called by any sender that doesn't match a network contract
*/
modifier onlyLatestNetworkContract() {
require(getBool(keccak256(abi.encodePacked("contract.exists", msg.sender))), "Invalid or outdated network contract");
_;
}
/**
* @dev Throws if called by any sender that doesn't match one of the supplied contract or is the latest version of that contract
*/
modifier onlyLatestContract(string memory _contractName, address _contractAddress) {
require(_contractAddress == getAddress(keccak256(abi.encodePacked("contract.address", _contractName))), "Invalid or outdated contract");
_;
}
/**
* @dev Throws if called by any sender that isn't a trusted node
*/
modifier onlyTrustedNode(address _nodeAddress) {
require(getBool(keccak256(abi.encodePacked("node.trusted", _nodeAddress))), "Invalid trusted node");
_;
}
/**
* @dev Throws if called by any sender that isn't a registered staking pool
*/
modifier onlyRegisteredStakingPool(address _stakingPoolAddress) {
require(getBool(keccak256(abi.encodePacked("stakingpool.exists", _stakingPoolAddress))), "Invalid staking pool");
_;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(roleHas("owner", msg.sender), "Account is not the owner");
_;
}
/**
* @dev Modifier to scope access to admins
*/
modifier onlyAdmin() {
require(roleHas("admin", msg.sender), "Account is not an admin");
_;
}
/**
* @dev Modifier to scope access to admins
*/
modifier onlySuperUser() {
require(roleHas("owner", msg.sender) || roleHas("admin", msg.sender), "Account is not a super user");
_;
}
/**
* @dev Reverts if the address doesn't have this role
*/
modifier onlyRole(string memory _role) {
require(roleHas(_role, msg.sender), "Account does not match the specified role");
_;
}
/// @dev Set the main Storage address
constructor(address _stafiStorageAddress) public {
// Update the contract address
stafiStorage = IStafiStorage(_stafiStorageAddress);
}
/// @dev Get the address of a network contract by name
function getContractAddress(string memory _contractName) internal view returns (address) {
// Get the current contract address
address contractAddress = getAddress(keccak256(abi.encodePacked("contract.address", _contractName)));
// Check it
require(contractAddress != address(0x0), "Contract not found");
// Return
return contractAddress;
}
/// @dev Get the name of a network contract by address
function getContractName(address _contractAddress) internal view returns (string memory) {
// Get the contract name
string memory contractName = getString(keccak256(abi.encodePacked("contract.name", _contractAddress)));
// Check it
require(keccak256(abi.encodePacked(contractName)) != keccak256(abi.encodePacked("")), "Contract not found");
// Return
return contractName;
}
/// @dev Storage get methods
function getAddress(bytes32 _key) internal view returns (address) { return stafiStorage.getAddress(_key); }
function getUint(bytes32 _key) internal view returns (uint256) { return stafiStorage.getUint(_key); }
function getString(bytes32 _key) internal view returns (string memory) { return stafiStorage.getString(_key); }
function getBytes(bytes32 _key) internal view returns (bytes memory) { return stafiStorage.getBytes(_key); }
function getBool(bytes32 _key) internal view returns (bool) { return stafiStorage.getBool(_key); }
function getInt(bytes32 _key) internal view returns (int256) { return stafiStorage.getInt(_key); }
function getBytes32(bytes32 _key) internal view returns (bytes32) { return stafiStorage.getBytes32(_key); }
function getAddressS(string memory _key) internal view returns (address) { return stafiStorage.getAddress(keccak256(abi.encodePacked(_key))); }
function getUintS(string memory _key) internal view returns (uint256) { return stafiStorage.getUint(keccak256(abi.encodePacked(_key))); }
function getStringS(string memory _key) internal view returns (string memory) { return stafiStorage.getString(keccak256(abi.encodePacked(_key))); }
function getBytesS(string memory _key) internal view returns (bytes memory) { return stafiStorage.getBytes(keccak256(abi.encodePacked(_key))); }
function getBoolS(string memory _key) internal view returns (bool) { return stafiStorage.getBool(keccak256(abi.encodePacked(_key))); }
function getIntS(string memory _key) internal view returns (int256) { return stafiStorage.getInt(keccak256(abi.encodePacked(_key))); }
function getBytes32S(string memory _key) internal view returns (bytes32) { return stafiStorage.getBytes32(keccak256(abi.encodePacked(_key))); }
/// @dev Storage set methods
function setAddress(bytes32 _key, address _value) internal { stafiStorage.setAddress(_key, _value); }
function setUint(bytes32 _key, uint256 _value) internal { stafiStorage.setUint(_key, _value); }
function setString(bytes32 _key, string memory _value) internal { stafiStorage.setString(_key, _value); }
function setBytes(bytes32 _key, bytes memory _value) internal { stafiStorage.setBytes(_key, _value); }
function setBool(bytes32 _key, bool _value) internal { stafiStorage.setBool(_key, _value); }
function setInt(bytes32 _key, int256 _value) internal { stafiStorage.setInt(_key, _value); }
function setBytes32(bytes32 _key, bytes32 _value) internal { stafiStorage.setBytes32(_key, _value); }
function setAddressS(string memory _key, address _value) internal { stafiStorage.setAddress(keccak256(abi.encodePacked(_key)), _value); }
function setUintS(string memory _key, uint256 _value) internal { stafiStorage.setUint(keccak256(abi.encodePacked(_key)), _value); }
function setStringS(string memory _key, string memory _value) internal { stafiStorage.setString(keccak256(abi.encodePacked(_key)), _value); }
function setBytesS(string memory _key, bytes memory _value) internal { stafiStorage.setBytes(keccak256(abi.encodePacked(_key)), _value); }
function setBoolS(string memory _key, bool _value) internal { stafiStorage.setBool(keccak256(abi.encodePacked(_key)), _value); }
function setIntS(string memory _key, int256 _value) internal { stafiStorage.setInt(keccak256(abi.encodePacked(_key)), _value); }
function setBytes32S(string memory _key, bytes32 _value) internal { stafiStorage.setBytes32(keccak256(abi.encodePacked(_key)), _value); }
/// @dev Storage delete methods
function deleteAddress(bytes32 _key) internal { stafiStorage.deleteAddress(_key); }
function deleteUint(bytes32 _key) internal { stafiStorage.deleteUint(_key); }
function deleteString(bytes32 _key) internal { stafiStorage.deleteString(_key); }
function deleteBytes(bytes32 _key) internal { stafiStorage.deleteBytes(_key); }
function deleteBool(bytes32 _key) internal { stafiStorage.deleteBool(_key); }
function deleteInt(bytes32 _key) internal { stafiStorage.deleteInt(_key); }
function deleteBytes32(bytes32 _key) internal { stafiStorage.deleteBytes32(_key); }
function deleteAddressS(string memory _key) internal { stafiStorage.deleteAddress(keccak256(abi.encodePacked(_key))); }
function deleteUintS(string memory _key) internal { stafiStorage.deleteUint(keccak256(abi.encodePacked(_key))); }
function deleteStringS(string memory _key) internal { stafiStorage.deleteString(keccak256(abi.encodePacked(_key))); }
function deleteBytesS(string memory _key) internal { stafiStorage.deleteBytes(keccak256(abi.encodePacked(_key))); }
function deleteBoolS(string memory _key) internal { stafiStorage.deleteBool(keccak256(abi.encodePacked(_key))); }
function deleteIntS(string memory _key) internal { stafiStorage.deleteInt(keccak256(abi.encodePacked(_key))); }
function deleteBytes32S(string memory _key) internal { stafiStorage.deleteBytes32(keccak256(abi.encodePacked(_key))); }
/**
* @dev Check if an address has this role
*/
function roleHas(string memory _role, address _address) internal view returns (bool) {
return getBool(keccak256(abi.encodePacked("access.role", _role, _address)));
}
}
interface IStafiEther {
function balanceOf(address _contractAddress) external view returns (uint256);
function depositEther() external payable;
function withdrawEther(uint256 _amount) external;
}
interface IStafiEtherWithdrawer {
function receiveEtherWithdrawal() external payable;
}
// ETH are stored here to prevent contract upgrades from affecting balances
// The contract must not be upgraded
contract StafiEther is StafiBase, IStafiEther {
// Libs
using SafeMath for uint256;
// Contract balances
mapping(bytes32 => uint256) balances;
// Events
event EtherDeposited(bytes32 indexed by, uint256 amount, uint256 time);
event EtherWithdrawn(bytes32 indexed by, uint256 amount, uint256 time);
// Construct
constructor(address _stafiStorageAddress) StafiBase(_stafiStorageAddress) public {
version = 1;
}
// Get a contract's ETH balance by address
function balanceOf(address _contractAddress) override public view returns (uint256) {
return balances[keccak256(abi.encodePacked(getContractName(_contractAddress)))];
}
// Accept an ETH deposit from a network contract
function depositEther() override external payable onlyLatestNetworkContract {
// Get contract key
bytes32 contractKey = keccak256(abi.encodePacked(getContractName(msg.sender)));
// Update contract balance
balances[contractKey] = balances[contractKey].add(msg.value);
// Emit ether deposited event
emit EtherDeposited(contractKey, msg.value, now);
}
// Withdraw an amount of ETH to a network contract
function withdrawEther(uint256 _amount) override external onlyLatestNetworkContract {
// Get contract key
bytes32 contractKey = keccak256(abi.encodePacked(getContractName(msg.sender)));
// Check and update contract balance
require(balances[contractKey] >= _amount, "Insufficient contract ETH balance");
balances[contractKey] = balances[contractKey].sub(_amount);
// Withdraw
IStafiEtherWithdrawer withdrawer = IStafiEtherWithdrawer(msg.sender);
withdrawer.receiveEtherWithdrawal{value: _amount}();
// Emit ether withdrawn event
emit EtherWithdrawn(contractKey, _amount, now);
}
}
|
ETH are stored here to prevent contract upgrades from affecting balances The contract must not be upgraded Libs Contract balances Events Construct
|
contract StafiEther is StafiBase, IStafiEther {
using SafeMath for uint256;
mapping(bytes32 => uint256) balances;
event EtherDeposited(bytes32 indexed by, uint256 amount, uint256 time);
event EtherWithdrawn(bytes32 indexed by, uint256 amount, uint256 time);
constructor(address _stafiStorageAddress) StafiBase(_stafiStorageAddress) public {
version = 1;
}
function balanceOf(address _contractAddress) override public view returns (uint256) {
return balances[keccak256(abi.encodePacked(getContractName(_contractAddress)))];
}
function depositEther() override external payable onlyLatestNetworkContract {
bytes32 contractKey = keccak256(abi.encodePacked(getContractName(msg.sender)));
balances[contractKey] = balances[contractKey].add(msg.value);
emit EtherDeposited(contractKey, msg.value, now);
}
function withdrawEther(uint256 _amount) override external onlyLatestNetworkContract {
bytes32 contractKey = keccak256(abi.encodePacked(getContractName(msg.sender)));
require(balances[contractKey] >= _amount, "Insufficient contract ETH balance");
balances[contractKey] = balances[contractKey].sub(_amount);
IStafiEtherWithdrawer withdrawer = IStafiEtherWithdrawer(msg.sender);
emit EtherWithdrawn(contractKey, _amount, now);
}
withdrawer.receiveEtherWithdrawal{value: _amount}();
}
| 2,006,602 |
[
1,
1584,
44,
854,
4041,
2674,
358,
5309,
6835,
28844,
628,
13418,
310,
324,
26488,
1021,
6835,
1297,
486,
506,
31049,
10560,
87,
13456,
324,
26488,
9043,
14291,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
934,
1727,
77,
41,
1136,
353,
934,
1727,
77,
2171,
16,
467,
510,
1727,
77,
41,
1136,
288,
203,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
2874,
12,
3890,
1578,
516,
2254,
5034,
13,
324,
26488,
31,
203,
203,
565,
871,
512,
1136,
758,
1724,
329,
12,
3890,
1578,
8808,
635,
16,
2254,
5034,
3844,
16,
2254,
5034,
813,
1769,
203,
565,
871,
512,
1136,
1190,
9446,
82,
12,
3890,
1578,
8808,
635,
16,
2254,
5034,
3844,
16,
2254,
5034,
813,
1769,
203,
203,
565,
3885,
12,
2867,
389,
334,
1727,
77,
3245,
1887,
13,
934,
1727,
77,
2171,
24899,
334,
1727,
77,
3245,
1887,
13,
1071,
288,
203,
3639,
1177,
273,
404,
31,
203,
565,
289,
203,
203,
565,
445,
11013,
951,
12,
2867,
389,
16351,
1887,
13,
3849,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
324,
26488,
63,
79,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
588,
8924,
461,
24899,
16351,
1887,
20349,
15533,
203,
565,
289,
203,
203,
565,
445,
443,
1724,
41,
1136,
1435,
3849,
3903,
8843,
429,
1338,
18650,
3906,
8924,
288,
203,
3639,
1731,
1578,
6835,
653,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
588,
8924,
461,
12,
3576,
18,
15330,
3719,
1769,
203,
3639,
324,
26488,
63,
16351,
653,
65,
273,
324,
26488,
63,
16351,
653,
8009,
1289,
12,
3576,
18,
1132,
1769,
203,
3639,
3626,
512,
1136,
758,
1724,
329,
12,
16351,
653,
16,
1234,
18,
1132,
16,
2
] |
./full_match/137/0x03CEf0b952fEF0c4b8fEF33B8E39d6B36c28e675/sources/contracts/core/FundVault.sol
|
Must send to Event Pods for now
|
function sendFunds(address currency, address eventPod, uint256 amount) external onlyRole(DEFAULT_ADMIN_ROLE) {
IERC20 token = IERC20(currency);
token.safeTransfer(eventPod, amount);
}
| 4,795,008 |
[
1,
10136,
1366,
358,
2587,
20526,
364,
2037,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1366,
42,
19156,
12,
2867,
5462,
16,
1758,
871,
5800,
16,
2254,
5034,
3844,
13,
3903,
1338,
2996,
12,
5280,
67,
15468,
67,
16256,
13,
288,
203,
3639,
467,
654,
39,
3462,
1147,
273,
467,
654,
39,
3462,
12,
7095,
1769,
203,
3639,
1147,
18,
4626,
5912,
12,
2575,
5800,
16,
3844,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.23;
/**
* @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 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 = 0xcb26A1328d8B9244d43F5D466c62F5b5Fcf9d725;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
/**
* @title RefundVault
* @dev This contract is used for storing funds while a crowdsale
* is in progress. Supports refunding the money if crowdsale fails,
* and forwarding it if crowdsale is successful.
*/
contract RefundVault is Ownable {
using SafeMath for uint256;
enum State { Active, Refunding, Closed }
mapping (address => uint256) public deposited;
address public wallet;
State public state;
event Closed();
event RefundsEnabled();
event Refunded(address indexed beneficiary, uint256 weiAmount);
/**
* @param _wallet Vault address
*/
constructor(address _wallet) public {
require(_wallet != address(0));
wallet = _wallet;
state = State.Active;
}
/**
* @param investor Investor address
*/
function deposit(address investor) onlyOwner public payable {
require(state == State.Active);
deposited[investor] = deposited[investor].add(msg.value);
}
function close() onlyOwner public {
require(state == State.Active);
state = State.Closed;
emit Closed();
wallet.transfer(address(this).balance);
}
function enableRefunds() onlyOwner public {
require(state == State.Active);
state = State.Refunding;
emit RefundsEnabled();
}
/**
* @param investor Investor address
*/
function refund(address investor) public {
require(state == State.Refunding);
uint256 depositedValue = deposited[investor];
deposited[investor] = 0;
investor.transfer(depositedValue);
emit Refunded(investor, depositedValue);
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
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 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 MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(
address _to,
uint256 _amount
)
hasMintPermission
canMint
public
returns (bool)
{
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
contract VIPX_Crowdsale is Pausable {
using SafeMath for uint256;
// The token being sold
ERC20 public token;
// Address where funds are collected
address public wallet;
// minimum amount of funds to be raised in weis
uint256 public goal;
// refund vault used to hold funds while crowdsale is running
RefundVault public vault;
// How many token units a buyer gets per wei
uint256 public rate;
// Amount of wei raised
uint256 public weiRaised;
// Max amount of wei accepted in the crowdsale
uint256 public cap;
// Min amount of wei an investor can send
uint256 public minInvest;
// Crowdsale opening time
uint256 public openingTime;
// Crowdsale closing time
uint256 public closingTime;
// Crowdsale duration in days
uint256 public duration;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
constructor() public {
rate = 500;
wallet = owner;
token = ERC20(0x7b9585eeC0598c8C5E508fB42B23D9d21B645170);
minInvest = 0.1 * 1 ether;
duration = 60 days;
openingTime = 2524608000; // Determined by start()
closingTime = openingTime + duration; // Determined by start()
goal = 2000 ether;
vault = new RefundVault(wallet);
}
/**
* @dev called by the owner to start the crowdsale
*/
function start() public onlyOwner {
openingTime = now;
closingTime = now + duration;
}
/**
* @dev Returns the rate of tokens per wei at the present time.
* Note that, as price _increases_ with time, the rate _decreases_.
* @return The number of tokens a buyer gets per wei at a given time
*/
function getCurrentRate() public view returns (uint256) {
if (now <= openingTime.add(7 days)) return rate.add(rate*3/10); // bonus 30% first week
if (now > openingTime.add(7 days) && now <= openingTime.add(14 days)) return rate.add(rate/5); // bonus 20% second week
if (now > openingTime.add(14 days) && now <= openingTime.add(21 days)) return rate.add(rate/10); // bonus 10% third week
if (now > openingTime.add(21 days) && now <= openingTime.add(28 days)) return rate.add(rate/20); // bonus 5% fourd week
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param _beneficiary Address performing the token purchase
*/
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
weiRaised = weiRaised.add(weiAmount);
_processPurchase(_beneficiary, tokens);
emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens);
_forwardFunds();
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal whenNotPaused {
require(_beneficiary != address(0));
require(_weiAmount >= minInvest);
require(now >= openingTime && now <= closingTime);
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param _beneficiary Address performing the token purchase
* @param _tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
require(MintableToken(token).mint(_beneficiary, _tokenAmount));
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param _beneficiary Address receiving the tokens
* @param _tokenAmount Number of tokens to be purchased
*/
function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal {
_deliverTokens(_beneficiary, _tokenAmount);
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param _weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) {
uint256 currentRate = getCurrentRate();
return currentRate.mul(_weiAmount);
}
/**
* @dev Overrides Crowdsale fund forwarding, sending funds to vault.
*/
function _forwardFunds() internal {
vault.deposit.value(msg.value)(msg.sender);
}
/**
* @dev Checks whether the period in which the crowdsale is open has already elapsed.
* @return Whether crowdsale period has elapsed
*/
function hasClosed() public view returns (bool) {
return now > closingTime;
}
bool public isFinalized = false;
event Finalized();
/**
* @dev Must be called after crowdsale ends, to do some extra finalization
* work. Calls the contract's finalization function.
*/
function finalize() onlyOwner public {
require(!isFinalized);
require(hasClosed());
finalization();
emit Finalized();
isFinalized = true;
}
/**
* @dev Investors can claim refunds here if crowdsale is unsuccessful
*/
function claimRefund() public {
require(isFinalized);
require(!goalReached());
vault.refund(msg.sender);
}
/**
* @dev Checks whether funding goal was reached.
* @return Whether funding goal was reached
*/
function goalReached() public view returns (bool) {
return weiRaised >= goal;
}
/**
* @dev vault finalization task, called when owner calls finalize()
*/
function finalization() internal {
if (goalReached()) {
vault.close();
} else {
vault.enableRefunds();
}
}
}
|
bonus 30% first week
|
if (now <= openingTime.add(7 days)) return rate.add(rate*3/10);
| 11,789,745 |
[
1,
18688,
407,
5196,
9,
1122,
4860,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
309,
261,
3338,
1648,
10890,
950,
18,
1289,
12,
27,
4681,
3719,
327,
4993,
18,
1289,
12,
5141,
14,
23,
19,
2163,
1769,
565,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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: CC-BY-4.0
pragma solidity ^0.5.11;
/**
* Rule 506(b)
* -----------
* https://www.sec.gov/smallbusiness/exemptofferings/
*
* Rule 506(b) of Regulation D is considered a “safe harbor” under Section 4(a)(2). It provides objective standards that a company can rely on to meet the requirements
* of the Section 4(a)(2) exemption. Companies conducting an offering under Rule 506(b) can raise an unlimited amount of money and can sell securities to an
* unlimited number of accredited investors. An offering under Rule 506(b), however, is subject to the following requirements:
*
* - no general solicitation or advertising to market the securities
* - securities may not be sold to more than 35 non-accredited investors (all non-accredited investors, either alone or with a purchaser representative,
* must meet the legal standard of having sufficient knowledge and experience in financial and business matters to be capable of evaluating the merits and
* risks of the prospective investment)
*
* If non-accredited investors are participating in the offering, the company conducting the offering:
*
* - must give any non-accredited investors disclosure documents that generally contain the same type of information as provided in Regulation A offerings
* (the company is not required to provide specified disclosure documents to accredited investors, but, if it does provide information to accredited investors,
* it must also make this information available to the non-accredited investors as well)
* - must give any non-accredited investors financial statement information specified in Rule 506 and
* - should be available to answer questions from prospective purchasers who are non-accredited investors
*
* Purchasers in a Rule 506(b) offering receive “restricted securities." A company is required to file a notice with the Commission on Form D within 15 days
* after the first sale of securities in the offering. Although the Securities Act provides a federal preemption from state registration and qualification
* under Rule 506(b), the states still have authority to require notice filings and collect state fees.
*/
import '@openzeppelin/contracts/token/ERC20/ERC20Mintable.sol';
import './token/ERC884.sol';
contract ExemptEquityToken506B is ERC884, ERC20Mintable {
string public constant name = "Rule 506(b) Token";
string public constant symbol = "TOKEN.506B";
uint8 public constant decimals = 0;
uint public constant INITIAL_SUPPLY = 100000 * 1 ether;
bytes32 constant private ZERO_BYTES = bytes32(0);
address constant private ZERO_ADDRESS = address(0);
mapping(address => bytes32) private verified;
mapping(address => address) private cancellations;
mapping(address => uint256) private holderIndices;
mapping(address => uint256) public balances;
struct Transaction {
address addr;
uint256 amount;
uint256 time;
}
mapping(address => Transaction[]) public transactions;
address private owner;
address[] private shareholders;
address[] private shareholders_nonacredited;
address[] private shareholders_affiliate;
bool internal active = false;
uint256 private start_timestamp;
event ExemptOffering(address indexed from,string status, uint256 value);
event Bought(uint value);
event Sold(uint value);
uint constant public parValue = 10;
uint256 constant public totalValueMax = 5000000;
uint constant public maxNonaccredited = 35;
uint256 private totalValue = 0;
bool private restricted = true;
constructor() public {
owner = msg.sender;
addMinter(owner);
_mint(owner, INITIAL_SUPPLY);
}
modifier onlyOwner() {
require(msg.sender == owner, "access denied");
_;
}
modifier canMint() {
require(isMinter(msg.sender),"access denied");
_;
}
modifier isActive() {
require(active, "exempt offering is not active");
_;
}
modifier isVerifiedAddress(address addr) {
require(verified[addr] != ZERO_BYTES, "");
_;
}
modifier isShareholder(address addr) {
require(holderIndices[addr] != 0, "");
_;
}
modifier isNotShareholder(address addr) {
require(holderIndices[addr] == 0, "");
_;
}
modifier isNotCancelled(address addr) {
require(cancellations[addr] == ZERO_ADDRESS, "");
_;
}
modifier isPriceBelowParValue(uint amount) {
require(amount > parValue, "amount is below par value");
_;
}
modifier isRestrictedSecurity() {
require(restricted != false, "security is restricted");
_;
}
modifier isMaximumOffering(uint256 amount) {
require(totalValue + amount < totalValueMax, "maximum offering has been reached");
_;
}
/**
* As each token is minted it is added to the shareholders array.
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount)
public
isActive
onlyOwner
canMint
isVerifiedAddress(_to)
isPriceBelowParValue(_amount)
isMaximumOffering(_amount)
returns (bool)
{
Transaction memory trans = Transaction(_to, _amount, now);
transactions[_to].push(trans);
return super.mint(_to, _amount);
}
function toggleExemptOffering(uint256 timestamp, bool _active)
public
onlyOwner
{
start_timestamp = timestamp;
active = _active;
if (active) {
emit ExemptOffering(msg.sender, string(abi.encodePacked(name, " has started")), timestamp);
} else {
emit ExemptOffering(msg.sender, string(abi.encodePacked(name, " has stopped")), timestamp);
}
}
function getTransactions(address addr) public view onlyOwner returns (string memory) {
string memory output = "";
for (uint i = 0; i < transactions[addr].length; i++) {
output = string(
abi.encodePacked(output, "[", transactions[addr][i].addr, ",", transactions[addr][i].amount, ",", transactions[addr][i].time, "]")
);
}
return output;
}
function getTransactionByIndex(address addr, uint index) public view onlyOwner returns (string memory) {
return string(abi.encodePacked(
"[", transactions[addr][index].addr, ",", transactions[addr][index].amount, ",", transactions[addr][index].time, "]"
));
}
/**
* The number of addresses that own tokens.
* @return the number of unique addresses that own tokens.
*/
function holderCount()
public
onlyOwner
view
returns (uint)
{
return shareholders.length;
}
/**
* By counting the number of token holders using `holderCount`
* you can retrieve the complete list of token holders, one at a time.
* It MUST throw if `index >= holderCount()`.
* @param index The zero-based index of the holder.
* @return the address of the token holder with the given index.
*/
function holderAt(uint256 index)
public
onlyOwner
view
returns (address)
{
require(index < shareholders.length, "");
return shareholders[index];
}
/**
* Add a verified address, along with an associated verification hash to the contract.
* Upon successful addition of a verified address, the contract must emit
* `VerifiedAddressAdded(addr, hash, msg.sender)`.
* It MUST throw if the supplied address or hash are zero, or if the address has already been supplied.
* @param addr The address of the person represented by the supplied hash.
* @param hash A cryptographic hash of the address holder's verified information.
*/
function addVerified(address addr, bytes32 hash)
public
onlyOwner
isNotCancelled(addr)
{
require(addr != ZERO_ADDRESS, "");
require(hash != ZERO_BYTES, "");
require(verified[addr] == ZERO_BYTES, "");
verified[addr] = hash;
emit VerifiedAddressAdded(addr, hash, msg.sender);
}
/**
* Remove a verified address, and the associated verification hash. If the address is
* unknown to the contract then this does nothing. If the address is successfully removed, this
* function must emit `VerifiedAddressRemoved(addr, msg.sender)`.
* It MUST throw if an attempt is made to remove a verifiedAddress that owns Tokens.
* @param addr The verified address to be removed.
*/
function removeVerified(address addr)
public
onlyOwner
{
require(addr.balance == 0, "account balance is not zero");
if (verified[addr] != ZERO_BYTES) {
verified[addr] = ZERO_BYTES;
emit VerifiedAddressRemoved(addr, msg.sender);
}
}
/**
* Update the hash for a verified address known to the contract.
* Upon successful update of a verified address the contract must emit
* `VerifiedAddressUpdated(addr, oldHash, hash, msg.sender)`.
* If the hash is the same as the value already stored then
* no `VerifiedAddressUpdated` event is to be emitted.
* It MUST throw if the hash is zero, or if the address is unverified.
* @param addr The verified address of the person represented by the supplied hash.
* @param hash A new cryptographic hash of the address holder's updated verified information.
*/
function updateVerified(address addr, bytes32 hash)
public
onlyOwner
isVerifiedAddress(addr)
{
require(hash != ZERO_BYTES, "");
bytes32 oldHash = verified[addr];
if (oldHash != hash) {
verified[addr] = hash;
emit VerifiedAddressUpdated(addr, oldHash, hash, msg.sender);
}
}
/**
* Cancel the original address and reissue the Tokens to the replacement address.
* Access to this function MUST be strictly controlled.
* The `original` address MUST be removed from the set of verified addresses.
* Throw if the `original` address supplied is not a shareholder.
* Throw if the replacement address is not a verified address.
* This function MUST emit the `VerifiedAddressSuperseded` event.
* @param original The address to be superseded. This address MUST NOT be reused.
* @param replacement The address that supersedes the original. This address MUST be verified.
*/
function cancelAndReissue(address original, address replacement)
public
isActive
onlyOwner
isShareholder(original)
isNotShareholder(replacement)
isVerifiedAddress(replacement)
{
// replace the original address in the shareholders array
// and update all the associated mappings
verified[original] = ZERO_BYTES;
cancellations[original] = replacement;
uint256 holderIndex = holderIndices[original] - 1;
shareholders[holderIndex] = replacement;
holderIndices[replacement] = holderIndices[original];
holderIndices[original] = 0;
balances[replacement] = balances[original];
balances[original] = 0;
emit VerifiedAddressSuperseded(original, replacement, msg.sender);
}
/**
* The `transfer` function MUST NOT allow transfers to addresses that
* have not been verified and added to the contract.
* If the `to` address is not currently a shareholder then it MUST become one.
* If the transfer will reduce `msg.sender`'s balance to 0 then that address
* MUST be removed from the list of shareholders.
*/
function transfer(address to, uint256 value)
public
isActive
isVerifiedAddress(to)
isPriceBelowParValue(value)
returns (bool)
{
pruneShareholders(msg.sender, value);
Transaction memory trans = Transaction(to, value, now);
transactions[to].push(trans);
trans = Transaction(msg.sender, uint256(-1) * value, now);
transactions[msg.sender].push(trans);
return super.transfer(to, value);
}
/**
* The `transferFrom` function MUST NOT allow transfers to addresses that
* have not been verified and added to the contract.
* If the `to` address is not currently a shareholder then it MUST become one.
* If the transfer will reduce `from`'s balance to 0 then that address
* MUST be removed from the list of shareholders.
*/
function transferFrom(address from, address to, uint256 value)
public
isActive
isVerifiedAddress(to)
isPriceBelowParValue(value)
returns (bool)
{
pruneShareholders(from, value);
Transaction memory trans = Transaction(to, value, now);
transactions[to].push(trans);
trans = Transaction(from, uint256(-1) * value, now);
transactions[from].push(trans);
return super.transferFrom(from, to, value);
}
/**
* Tests that the supplied address is known to the contract.
* @param addr The address to test.
* @return true if the address is known to the contract.
*/
function isVerified(address addr)
public
view
returns (bool)
{
return verified[addr] != ZERO_BYTES;
}
/**
* Checks to see if the supplied address is a share holder.
* @param addr The address to check.
* @return true if the supplied address owns a token.
*/
function isHolder(address addr)
public
view
returns (bool)
{
return holderIndices[addr] != 0;
}
/**
* Checks that the supplied hash is associated with the given address.
* @param addr The address to test.
* @param hash The hash to test.
* @return true if the hash matches the one supplied with the address in `addVerified`, or `updateVerified`.
*/
function hasHash(address addr, bytes32 hash)
public
view
returns (bool)
{
if (addr == ZERO_ADDRESS) {
return false;
}
return verified[addr] == hash;
}
/**
* Checks to see if the supplied address was superseded.
* @param addr The address to check.
* @return true if the supplied address was superseded by another address.
*/
function isSuperseded(address addr)
public
view
onlyOwner
returns (bool)
{
return cancellations[addr] != ZERO_ADDRESS;
}
/**
* Gets the most recent address, given a superseded one.
* Addresses may be superseded multiple times, so this function needs to
* follow the chain of addresses until it reaches the final, verified address.
* @param addr The superseded address.
* @return the verified address that ultimately holds the share.
*/
function getCurrentFor(address addr)
public
view
onlyOwner
returns (address)
{
return findCurrentFor(addr);
}
/**
* Recursively find the most recent address given a superseded one.
* @param addr The superseded address.
* @return the verified address that ultimately holds the share.
*/
function findCurrentFor(address addr)
internal
view
returns (address)
{
address candidate = cancellations[addr];
if (candidate == ZERO_ADDRESS) {
return addr;
}
return findCurrentFor(candidate);
}
/**
* If the address is not in the `shareholders` array then push it
* and update the `holderIndices` mapping.
* @param addr The address to add as a shareholder if it's not already.
*/
function updateShareholders(address addr)
internal
{
if (holderIndices[addr] == 0) {
holderIndices[addr] = shareholders.push(addr);
}
}
function addShareholder(address addr, uint level)
public
onlyOwner
{
if (holderIndices[addr] == 0) {
if (level == 0) {
require(shareholders_nonacredited.length < maxNonaccredited, "will exceed the maximum number of non-accredited investors");
holderIndices[addr] = shareholders_nonacredited.push(addr);
} else if (level == 1) {
holderIndices[addr] = shareholders.push(addr);
} else if (level == 2) {
holderIndices[addr] = shareholders_affiliate.push(addr);
}
}
}
/**
* If the address is in the `shareholders` array and the forthcoming
* transfer or transferFrom will reduce their balance to 0, then
* we need to remove them from the shareholders array.
* @param addr The address to prune if their balance will be reduced to 0.
@ @dev see https://ethereum.stackexchange.com/a/39311
*/
function pruneShareholders(address addr, uint256 value)
internal
{
uint256 balance = addr.balance - value;
if (balance > 0) {
return;
}
uint256 holderIndex = holderIndices[addr] - 1;
uint256 lastIndex = shareholders.length - 1;
address lastHolder = shareholders[lastIndex];
// overwrite the addr's slot with the last shareholder
shareholders[holderIndex] = lastHolder;
// also copy over the index (thanks @mohoff for spotting this)
// ref https://github.com/davesag/ERC884-reference-implementation/issues/20
holderIndices[lastHolder] = holderIndices[addr];
// trim the shareholders array (which drops the last entry)
shareholders.length--;
// and zero out the index for addr
holderIndices[addr] = 0;
}
function buy()
public
payable
isActive
isMaximumOffering(msg.value)
{
uint256 amountTobuy = msg.value;
uint256 dexBalance = balanceOf(address(this));
require(amountTobuy > 0, "You need to send some ether");
require(amountTobuy <= dexBalance, "Not enough tokens in the reserve");
Transaction memory trans = Transaction(msg.sender, amountTobuy, now);
transactions[msg.sender].push(trans);
transfer(msg.sender, amountTobuy);
emit Bought(amountTobuy);
}
function sell(uint256 amount)
public
payable
isActive
isVerifiedAddress(msg.sender)
{
require(amount > 0, "You need to sell at least some tokens");
uint256 allowance = allowance(msg.sender, address(this));
require(allowance >= amount, "Check the token allowance");
transferFrom(msg.sender, address(this), amount);
Transaction memory trans = Transaction(msg.sender, amount, now);
transactions[msg.sender].push(trans);
msg.sender.transfer(amount);
emit Sold(amount);
}
}
|
* Update the hash for a verified address known to the contract. Upon successful update of a verified address the contract must emit `VerifiedAddressUpdated(addr, oldHash, hash, msg.sender)`. If the hash is the same as the value already stored then no `VerifiedAddressUpdated` event is to be emitted. It MUST throw if the hash is zero, or if the address is unverified. @param addr The verified address of the person represented by the supplied hash. @param hash A new cryptographic hash of the address holder's updated verified information./
|
function updateVerified(address addr, bytes32 hash)
public
onlyOwner
isVerifiedAddress(addr)
{
require(hash != ZERO_BYTES, "");
bytes32 oldHash = verified[addr];
if (oldHash != hash) {
verified[addr] = hash;
emit VerifiedAddressUpdated(addr, oldHash, hash, msg.sender);
}
}
| 13,060,169 |
[
1,
1891,
326,
1651,
364,
279,
13808,
1758,
4846,
358,
326,
6835,
18,
225,
587,
500,
6873,
1089,
434,
279,
13808,
1758,
326,
6835,
1297,
3626,
225,
1375,
24369,
1887,
7381,
12,
4793,
16,
1592,
2310,
16,
1651,
16,
1234,
18,
15330,
13,
8338,
225,
971,
326,
1651,
353,
326,
1967,
487,
326,
460,
1818,
4041,
1508,
225,
1158,
1375,
24369,
1887,
7381,
68,
871,
353,
358,
506,
17826,
18,
225,
2597,
10685,
604,
309,
326,
1651,
353,
3634,
16,
578,
309,
326,
1758,
353,
640,
19685,
18,
282,
3091,
1021,
13808,
1758,
434,
326,
6175,
10584,
635,
326,
4580,
1651,
18,
282,
1651,
432,
394,
13231,
16983,
1651,
434,
326,
1758,
10438,
1807,
3526,
13808,
1779,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
565,
445,
1089,
24369,
12,
2867,
3091,
16,
1731,
1578,
1651,
13,
203,
3639,
1071,
203,
3639,
1338,
5541,
203,
3639,
353,
24369,
1887,
12,
4793,
13,
203,
565,
288,
203,
3639,
2583,
12,
2816,
480,
18449,
67,
13718,
16,
1408,
1769,
203,
3639,
1731,
1578,
1592,
2310,
273,
13808,
63,
4793,
15533,
203,
3639,
309,
261,
1673,
2310,
480,
1651,
13,
288,
203,
5411,
13808,
63,
4793,
65,
273,
1651,
31,
203,
5411,
3626,
6160,
939,
1887,
7381,
12,
4793,
16,
1592,
2310,
16,
1651,
16,
1234,
18,
15330,
1769,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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;
contract OraclizeI {
address public cbAddress;
function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id);
function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id);
function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id);
function getPrice(string _datasource) public returns (uint _dsprice);
function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice);
function setProofType(byte _proofType) external;
function setCustomGasPrice(uint _gasPrice) external;
function randomDS_getSessionPubKeyHash() external constant returns(bytes32);
}
contract OraclizeAddrResolverI {
function getAddress() public returns (address _addr);
}
contract usingOraclize {
uint constant day = 60*60*24;
uint constant week = 60*60*24*7;
uint constant month = 60*60*24*30;
byte constant proofType_NONE = 0x00;
byte constant proofType_TLSNotary = 0x10;
byte constant proofType_Android = 0x20;
byte constant proofType_Ledger = 0x30;
byte constant proofType_Native = 0xF0;
byte constant proofStorage_IPFS = 0x01;
uint8 constant networkID_auto = 0;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_morden = 2;
uint8 constant networkID_consensys = 161;
OraclizeAddrResolverI OAR;
OraclizeI oraclize;
modifier oraclizeAPI {
if((address(OAR)==0)||(getCodeSize(address(OAR))==0))
oraclize_setNetwork(networkID_auto);
if(address(oraclize) != OAR.getAddress())
oraclize = OraclizeI(OAR.getAddress());
_;
}
modifier coupon(string code){
oraclize = OraclizeI(OAR.getAddress());
_;
}
function oraclize_setNetwork(uint8 networkID) internal returns(bool){
return oraclize_setNetwork();
networkID; // silence the warning and remain backwards compatible
}
function oraclize_setNetwork() internal returns(bool){
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet
OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
oraclize_setNetworkName("eth_mainnet");
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet
OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
oraclize_setNetworkName("eth_ropsten3");
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet
OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
oraclize_setNetworkName("eth_kovan");
return true;
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet
OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
oraclize_setNetworkName("eth_rinkeby");
return true;
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
return true;
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide
OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
return true;
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity
OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
return true;
}
return false;
}
function __callback(bytes32 myid, string result) public {
__callback(myid, result, new bytes(0));
}
function __callback(bytes32 myid, string result, bytes proof) public {
return;
myid; result; proof; // Silence compiler warnings
}
function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource);
}
function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource, gaslimit);
}
function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(0, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(timestamp, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(0, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address){
return oraclize.cbAddress();
}
function oraclize_setProof(byte proofP) oraclizeAPI internal {
return oraclize.setProofType(proofP);
}
function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal {
return oraclize.setCustomGasPrice(gasPrice);
}
function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){
return oraclize.randomDS_getSessionPubKeyHash();
}
function getCodeSize(address _addr) constant internal returns(uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function parseAddr(string _a) internal pure returns (address){
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i=2; i<2+2*20; i+=2){
iaddr *= 256;
b1 = uint160(tmp[i]);
b2 = uint160(tmp[i+1]);
if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;
else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55;
else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55;
else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;
iaddr += (b1*16+b2);
}
return address(iaddr);
}
function strCompare(string _a, string _b) internal pure returns (int) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) minLength = b.length;
for (uint i = 0; i < minLength; i ++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
if (a.length < b.length)
return -1;
else if (a.length > b.length)
return 1;
else
return 0;
}
function indexOf(string _haystack, string _needle) internal pure returns (int) {
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if(h.length < 1 || n.length < 1 || (n.length > h.length))
return -1;
else if(h.length > (2**128 -1))
return -1;
else
{
uint subindex = 0;
for (uint i = 0; i < h.length; i ++)
{
if (h[i] == n[0])
{
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex])
{
subindex++;
}
if(subindex == n.length)
return int(i);
}
}
return -1;
}
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal pure returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal pure returns (string) {
return strConcat(_a, _b, "", "", "");
}
// parseInt
function parseInt(string _a) internal pure returns (uint) {
return parseInt(_a, 0);
}
// parseInt(parseFloat*10^_b)
function parseInt(string _a, uint _b) internal pure returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
function uint2str(uint i) internal pure returns (string){
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
function stra2cbor(string[] arr) internal pure returns (bytes) {
uint arrlen = arr.length;
// get correct cbor output length
uint outputlen = 0;
bytes[] memory elemArray = new bytes[](arrlen);
for (uint i = 0; i < arrlen; i++) {
elemArray[i] = (bytes(arr[i]));
outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types
}
uint ctr = 0;
uint cborlen = arrlen + 0x80;
outputlen += byte(cborlen).length;
bytes memory res = new bytes(outputlen);
while (byte(cborlen).length > ctr) {
res[ctr] = byte(cborlen)[ctr];
ctr++;
}
for (i = 0; i < arrlen; i++) {
res[ctr] = 0x5F;
ctr++;
for (uint x = 0; x < elemArray[i].length; x++) {
// if there's a bug with larger strings, this may be the culprit
if (x % 23 == 0) {
uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
elemcborlen += 0x40;
uint lctr = ctr;
while (byte(elemcborlen).length > ctr - lctr) {
res[ctr] = byte(elemcborlen)[ctr - lctr];
ctr++;
}
}
res[ctr] = elemArray[i][x];
ctr++;
}
res[ctr] = 0xFF;
ctr++;
}
return res;
}
function ba2cbor(bytes[] arr) internal pure returns (bytes) {
uint arrlen = arr.length;
// get correct cbor output length
uint outputlen = 0;
bytes[] memory elemArray = new bytes[](arrlen);
for (uint i = 0; i < arrlen; i++) {
elemArray[i] = (bytes(arr[i]));
outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types
}
uint ctr = 0;
uint cborlen = arrlen + 0x80;
outputlen += byte(cborlen).length;
bytes memory res = new bytes(outputlen);
while (byte(cborlen).length > ctr) {
res[ctr] = byte(cborlen)[ctr];
ctr++;
}
for (i = 0; i < arrlen; i++) {
res[ctr] = 0x5F;
ctr++;
for (uint x = 0; x < elemArray[i].length; x++) {
// if there's a bug with larger strings, this may be the culprit
if (x % 23 == 0) {
uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
elemcborlen += 0x40;
uint lctr = ctr;
while (byte(elemcborlen).length > ctr - lctr) {
res[ctr] = byte(elemcborlen)[ctr - lctr];
ctr++;
}
}
res[ctr] = elemArray[i][x];
ctr++;
}
res[ctr] = 0xFF;
ctr++;
}
return res;
}
string oraclize_network_name;
function oraclize_setNetworkName(string _network_name) internal {
oraclize_network_name = _network_name;
}
function oraclize_getNetworkName() internal view returns (string) {
return oraclize_network_name;
}
function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){
require((_nbytes > 0) && (_nbytes <= 32));
// Convert from seconds to ledger timer ticks
_delay *= 10;
bytes memory nbytes = new bytes(1);
nbytes[0] = byte(_nbytes);
bytes memory unonce = new bytes(32);
bytes memory sessionKeyHash = new bytes(32);
bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash();
assembly {
mstore(unonce, 0x20)
mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp)))
mstore(sessionKeyHash, 0x20)
mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32)
}
bytes memory delay = new bytes(32);
assembly {
mstore(add(delay, 0x20), _delay)
}
bytes memory delay_bytes8 = new bytes(8);
copyBytes(delay, 24, 8, delay_bytes8, 0);
bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay];
bytes32 queryId = oraclize_query("random", args, _customGasLimit);
bytes memory delay_bytes8_left = new bytes(8);
assembly {
let x := mload(add(delay_bytes8, 0x20))
mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000))
}
oraclize_randomDS_setCommitment(queryId, keccak256(delay_bytes8_left, args[1], sha256(args[0]), args[2]));
return queryId;
}
function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal {
oraclize_randomDS_args[queryId] = commitment;
}
mapping(bytes32=>bytes32) oraclize_randomDS_args;
mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified;
function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){
bool sigok;
address signer;
bytes32 sigr;
bytes32 sigs;
bytes memory sigr_ = new bytes(32);
uint offset = 4+(uint(dersig[3]) - 0x20);
sigr_ = copyBytes(dersig, offset, 32, sigr_, 0);
bytes memory sigs_ = new bytes(32);
offset += 32 + 2;
sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0);
assembly {
sigr := mload(add(sigr_, 32))
sigs := mload(add(sigs_, 32))
}
(sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs);
if (address(keccak256(pubkey)) == signer) return true;
else {
(sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs);
return (address(keccak256(pubkey)) == signer);
}
}
function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) {
bool sigok;
// Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH)
bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2);
copyBytes(proof, sig2offset, sig2.length, sig2, 0);
bytes memory appkey1_pubkey = new bytes(64);
copyBytes(proof, 3+1, 64, appkey1_pubkey, 0);
bytes memory tosign2 = new bytes(1+65+32);
tosign2[0] = byte(1); //role
copyBytes(proof, sig2offset-65, 65, tosign2, 1);
bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c";
copyBytes(CODEHASH, 0, 32, tosign2, 1+65);
sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey);
if (sigok == false) return false;
// Step 7: verify the APPKEY1 provenance (must be signed by Ledger)
bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4";
bytes memory tosign3 = new bytes(1+65);
tosign3[0] = 0xFE;
copyBytes(proof, 3, 65, tosign3, 1);
bytes memory sig3 = new bytes(uint(proof[3+65+1])+2);
copyBytes(proof, 3+65, sig3.length, sig3, 0);
sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);
return sigok;
}
modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) {
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1));
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
require(proofVerified);
_;
}
function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) return 2;
return 0;
}
function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){
bool match_ = true;
require(prefix.length == n_random_bytes);
for (uint256 i=0; i< n_random_bytes; i++) {
if (content[i] != prefix[i]) match_ = false;
}
return match_;
}
function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){
// Step 2: the unique keyhash has to match with the sha256 of (context name + queryId)
uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32;
bytes memory keyhash = new bytes(32);
copyBytes(proof, ledgerProofLength, 32, keyhash, 0);
if (!(keccak256(keyhash) == keccak256(sha256(context_name, queryId)))) return false;
bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2);
copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0);
// Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1)
if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false;
// Step 4: commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage.
// This is to verify that the computed args match with the ones specified in the query.
bytes memory commitmentSlice1 = new bytes(8+1+32);
copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0);
bytes memory sessionPubkey = new bytes(64);
uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65;
copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0);
bytes32 sessionPubkeyHash = sha256(sessionPubkey);
if (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match
delete oraclize_randomDS_args[queryId];
} else return false;
// Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey)
bytes memory tosign1 = new bytes(32+8+1+32);
copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0);
if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false;
// verify if sessionPubkeyHash was verified already, if not.. let's do it!
if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){
oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset);
}
return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash];
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) {
uint minLength = length + toOffset;
// Buffer too small
require(to.length >= minLength); // Should be a better way?
// NOTE: the offset 32 is added to skip the `size` field of both bytes variables
uint i = 32 + fromOffset;
uint j = 32 + toOffset;
while (i < (32 + fromOffset + length)) {
assembly {
let tmp := mload(add(from, i))
mstore(add(to, j), tmp)
}
i += 32;
j += 32;
}
return to;
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
// Duplicate Solidity's ecrecover, but catching the CALL return value
function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) {
// We do our own memory management here. Solidity uses memory offset
// 0x40 to store the current end of memory. We write past it (as
// writes are memory extensions), but don't update the offset so
// Solidity will reuse it. The memory used here is only needed for
// this context.
// FIXME: inline assembly can't access return values
bool ret;
address addr;
assembly {
let size := mload(0x40)
mstore(size, hash)
mstore(add(size, 32), v)
mstore(add(size, 64), r)
mstore(add(size, 96), s)
// NOTE: we can reuse the request memory because we deal with
// the return code
ret := call(3000, 1, 0, size, 128, size, 32)
addr := mload(size)
}
return (ret, addr);
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) {
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65)
return (false, 0);
// The signature format is a compact form of:
// {bytes32 r}{bytes32 s}{uint8 v}
// Compact means, uint8 is not padded to 32 bytes.
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
// Here we are loading the last 32 bytes. We exploit the fact that
// 'mload' will pad with zeroes if we overread.
// There is no 'mload8' to do this, but that would be nicer.
v := byte(0, mload(add(sig, 96)))
// Alternative solution:
// 'byte' is not working due to the Solidity parser, so lets
// use the second best option, 'and'
// v := and(mload(add(sig, 65)), 255)
}
// albeit non-transactional signatures are not specified by the YP, one would expect it
// to match the YP range of [27, 28]
//
// geth uses [0, 1] and some clients have followed. This might change, see:
// https://github.com/ethereum/go-ethereum/issues/2053
if (v < 27)
v += 27;
if (v != 27 && v != 28)
return (false, 0);
return safer_ecrecover(hash, v, r, s);
}
}
// </ORACLIZE_API>
contract EOSBetGameInterface {
uint256 public DEVELOPERSFUND;
uint256 public LIABILITIES;
function payDevelopersFund(address developer) public;
function receivePaymentForOraclize() payable public;
function getMaxWin() public view returns(uint256);
}
contract EOSBetBankrollInterface {
function payEtherToWinner(uint256 amtEther, address winner) public;
function receiveEtherFromGameAddress() payable public;
function payOraclize(uint256 amountToPay) public;
function getBankroll() public view returns(uint256);
}
contract ERC20 {
function totalSupply() constant public returns (uint supply);
function balanceOf(address _owner) constant public returns (uint balance);
function transfer(address _to, uint _value) public returns (bool success);
function transferFrom(address _from, address _to, uint _value) public returns (bool success);
function approve(address _spender, uint _value) public returns (bool success);
function allowance(address _owner, address _spender) constant public returns (uint remaining);
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
contract EOSBetBankroll is ERC20, EOSBetBankrollInterface {
using SafeMath for *;
// constants for EOSBet Bankroll
address public OWNER;
uint256 public MAXIMUMINVESTMENTSALLOWED;
uint256 public WAITTIMEUNTILWITHDRAWORTRANSFER;
uint256 public DEVELOPERSFUND;
// this will be initialized as the trusted game addresses which will forward their ether
// to the bankroll contract, and when players win, they will request the bankroll contract
// to send these players their winnings.
// Feel free to audit these contracts on etherscan...
mapping(address => bool) public TRUSTEDADDRESSES;
address public DICE;
address public SLOTS;
// mapping to log the last time a user contributed to the bankroll
mapping(address => uint256) contributionTime;
// constants for ERC20 standard
string public constant name = "EOSBet Stake Tokens";
string public constant symbol = "EOSBETST";
uint8 public constant decimals = 18;
// variable total supply
uint256 public totalSupply;
// mapping to store tokens
mapping(address => uint256) public balances;
mapping(address => mapping(address => uint256)) public allowed;
// events
event FundBankroll(address contributor, uint256 etherContributed, uint256 tokensReceived);
event CashOut(address contributor, uint256 etherWithdrawn, uint256 tokensCashedIn);
event FailedSend(address sendTo, uint256 amt);
// checks that an address is a "trusted address of a legitimate EOSBet game"
modifier addressInTrustedAddresses(address thisAddress){
require(TRUSTEDADDRESSES[thisAddress]);
_;
}
// initialization function
function EOSBetBankroll(address dice, address slots) public payable {
// function is payable, owner of contract MUST "seed" contract with some ether,
// so that the ratios are correct when tokens are being minted
require (msg.value > 0);
OWNER = msg.sender;
// 100 tokens/ether is the inital seed amount, so:
uint256 initialTokens = msg.value * 100;
balances[msg.sender] = initialTokens;
totalSupply = initialTokens;
// log a mint tokens event
emit Transfer(0x0, msg.sender, initialTokens);
// insert given game addresses into the TRUSTEDADDRESSES mapping, and save the addresses as global variables
TRUSTEDADDRESSES[dice] = true;
TRUSTEDADDRESSES[slots] = true;
DICE = dice;
SLOTS = slots;
WAITTIMEUNTILWITHDRAWORTRANSFER = 6 hours;
MAXIMUMINVESTMENTSALLOWED = 500 ether;
}
///////////////////////////////////////////////
// VIEW FUNCTIONS
///////////////////////////////////////////////
function checkWhenContributorCanTransferOrWithdraw(address bankrollerAddress) view public returns(uint256){
return contributionTime[bankrollerAddress];
}
function getBankroll() view public returns(uint256){
// returns the total balance minus the developers fund, as the amount of active bankroll
return SafeMath.sub(address(this).balance, DEVELOPERSFUND);
}
///////////////////////////////////////////////
// BANKROLL CONTRACT <-> GAME CONTRACTS functions
///////////////////////////////////////////////
function payEtherToWinner(uint256 amtEther, address winner) public addressInTrustedAddresses(msg.sender){
// this function will get called by a game contract when someone wins a game
// try to send, if it fails, then send the amount to the owner
// note, this will only happen if someone is calling the betting functions with
// a contract. They are clearly up to no good, so they can contact us to retreive
// their ether
// if the ether cannot be sent to us, the OWNER, that means we are up to no good,
// and the ether will just be given to the bankrollers as if the player/owner lost
if (! winner.send(amtEther)){
emit FailedSend(winner, amtEther);
if (! OWNER.send(amtEther)){
emit FailedSend(OWNER, amtEther);
}
}
}
function receiveEtherFromGameAddress() payable public addressInTrustedAddresses(msg.sender){
// this function will get called from the game contracts when someone starts a game.
}
function payOraclize(uint256 amountToPay) public addressInTrustedAddresses(msg.sender){
// this function will get called when a game contract must pay payOraclize
EOSBetGameInterface(msg.sender).receivePaymentForOraclize.value(amountToPay)();
}
///////////////////////////////////////////////
// BANKROLL CONTRACT MAIN FUNCTIONS
///////////////////////////////////////////////
// this function ADDS to the bankroll of EOSBet, and credits the bankroller a proportional
// amount of tokens so they may withdraw their tokens later
// also if there is only a limited amount of space left in the bankroll, a user can just send as much
// ether as they want, because they will be able to contribute up to the maximum, and then get refunded the rest.
function () public payable {
// save in memory for cheap access.
// this represents the total bankroll balance before the function was called.
uint256 currentTotalBankroll = SafeMath.sub(getBankroll(), msg.value);
uint256 maxInvestmentsAllowed = MAXIMUMINVESTMENTSALLOWED;
require(currentTotalBankroll < maxInvestmentsAllowed && msg.value != 0);
uint256 currentSupplyOfTokens = totalSupply;
uint256 contributedEther;
bool contributionTakesBankrollOverLimit;
uint256 ifContributionTakesBankrollOverLimit_Refund;
uint256 creditedTokens;
if (SafeMath.add(currentTotalBankroll, msg.value) > maxInvestmentsAllowed){
// allow the bankroller to contribute up to the allowed amount of ether, and refund the rest.
contributionTakesBankrollOverLimit = true;
// set contributed ether as (MAXIMUMINVESTMENTSALLOWED - BANKROLL)
contributedEther = SafeMath.sub(maxInvestmentsAllowed, currentTotalBankroll);
// refund the rest of the ether, which is (original amount sent - (maximum amount allowed - bankroll))
ifContributionTakesBankrollOverLimit_Refund = SafeMath.sub(msg.value, contributedEther);
}
else {
contributedEther = msg.value;
}
if (currentSupplyOfTokens != 0){
// determine the ratio of contribution versus total BANKROLL.
creditedTokens = SafeMath.mul(contributedEther, currentSupplyOfTokens) / currentTotalBankroll;
}
else {
// edge case where ALL money was cashed out from bankroll
// so currentSupplyOfTokens == 0
// currentTotalBankroll can == 0 or not, if someone mines/selfdestruct's to the contract
// but either way, give all the bankroll to person who deposits ether
creditedTokens = SafeMath.mul(contributedEther, 100);
}
// now update the total supply of tokens and bankroll amount
totalSupply = SafeMath.add(currentSupplyOfTokens, creditedTokens);
// now credit the user with his amount of contributed tokens
balances[msg.sender] = SafeMath.add(balances[msg.sender], creditedTokens);
// update his contribution time for stake time locking
contributionTime[msg.sender] = block.timestamp;
// now look if the attempted contribution would have taken the BANKROLL over the limit,
// and if true, refund the excess ether.
if (contributionTakesBankrollOverLimit){
msg.sender.transfer(ifContributionTakesBankrollOverLimit_Refund);
}
// log an event about funding bankroll
emit FundBankroll(msg.sender, contributedEther, creditedTokens);
// log a mint tokens event
emit Transfer(0x0, msg.sender, creditedTokens);
}
function cashoutEOSBetStakeTokens(uint256 _amountTokens) public {
// In effect, this function is the OPPOSITE of the un-named payable function above^^^
// this allows bankrollers to "cash out" at any time, and receive the ether that they contributed, PLUS
// a proportion of any ether that was earned by the smart contact when their ether was "staking", However
// this works in reverse as well. Any net losses of the smart contract will be absorbed by the player in like manner.
// Of course, due to the constant house edge, a bankroller that leaves their ether in the contract long enough
// is effectively guaranteed to withdraw more ether than they originally "staked"
// save in memory for cheap access.
uint256 tokenBalance = balances[msg.sender];
// verify that the contributor has enough tokens to cash out this many, and has waited the required time.
require(_amountTokens <= tokenBalance
&& contributionTime[msg.sender] + WAITTIMEUNTILWITHDRAWORTRANSFER <= block.timestamp
&& _amountTokens > 0);
// save in memory for cheap access.
// again, represents the total balance of the contract before the function was called.
uint256 currentTotalBankroll = getBankroll();
uint256 currentSupplyOfTokens = totalSupply;
// calculate the token withdraw ratio based on current supply
uint256 withdrawEther = SafeMath.mul(_amountTokens, currentTotalBankroll) / currentSupplyOfTokens;
// developers take 1% of withdrawls
uint256 developersCut = withdrawEther / 100;
uint256 contributorAmount = SafeMath.sub(withdrawEther, developersCut);
// now update the total supply of tokens by subtracting the tokens that are being "cashed in"
totalSupply = SafeMath.sub(currentSupplyOfTokens, _amountTokens);
// and update the users supply of tokens
balances[msg.sender] = SafeMath.sub(tokenBalance, _amountTokens);
// update the developers fund based on this calculated amount
DEVELOPERSFUND = SafeMath.add(DEVELOPERSFUND, developersCut);
// lastly, transfer the ether back to the bankroller. Thanks for your contribution!
msg.sender.transfer(contributorAmount);
// log an event about cashout
emit CashOut(msg.sender, contributorAmount, _amountTokens);
// log a destroy tokens event
emit Transfer(msg.sender, 0x0, _amountTokens);
}
// TO CALL THIS FUNCTION EASILY, SEND A 0 ETHER TRANSACTION TO THIS CONTRACT WITH EXTRA DATA: 0x7a09588b
function cashoutEOSBetStakeTokens_ALL() public {
// just forward to cashoutEOSBetStakeTokens with input as the senders entire balance
cashoutEOSBetStakeTokens(balances[msg.sender]);
}
////////////////////
// OWNER FUNCTIONS:
////////////////////
// Please, be aware that the owner ONLY can change:
// 1. The owner can increase or decrease the target amount for a game. They can then call the updater function to give/receive the ether from the game.
// 1. The wait time until a user can withdraw or transfer their tokens after purchase through the default function above ^^^
// 2. The owner can change the maximum amount of investments allowed. This allows for early contributors to guarantee
// a certain percentage of the bankroll so that their stake cannot be diluted immediately. However, be aware that the
// maximum amount of investments allowed will be raised over time. This will allow for higher bets by gamblers, resulting
// in higher dividends for the bankrollers
// 3. The owner can freeze payouts to bettors. This will be used in case of an emergency, and the contract will reject all
// new bets as well. This does not mean that bettors will lose their money without recompense. They will be allowed to call the
// "refund" function in the respective game smart contract once payouts are un-frozen.
// 4. Finally, the owner can modify and withdraw the developers reward, which will fund future development, including new games, a sexier frontend,
// and TRUE DAO governance so that onlyOwner functions don't have to exist anymore ;) and in order to effectively react to changes
// in the market (lower the percentage because of increased competition in the blockchain casino space, etc.)
function transferOwnership(address newOwner) public {
require(msg.sender == OWNER);
OWNER = newOwner;
}
function changeWaitTimeUntilWithdrawOrTransfer(uint256 waitTime) public {
// waitTime MUST be less than or equal to 10 weeks
require (msg.sender == OWNER && waitTime <= 6048000);
WAITTIMEUNTILWITHDRAWORTRANSFER = waitTime;
}
function changeMaximumInvestmentsAllowed(uint256 maxAmount) public {
require(msg.sender == OWNER);
MAXIMUMINVESTMENTSALLOWED = maxAmount;
}
function withdrawDevelopersFund(address receiver) public {
require(msg.sender == OWNER);
// first get developers fund from each game
EOSBetGameInterface(DICE).payDevelopersFund(receiver);
EOSBetGameInterface(SLOTS).payDevelopersFund(receiver);
// now send the developers fund from the main contract.
uint256 developersFund = DEVELOPERSFUND;
// set developers fund to zero
DEVELOPERSFUND = 0;
// transfer this amount to the owner!
receiver.transfer(developersFund);
}
// rescue tokens inadvertently sent to the contract address
function ERC20Rescue(address tokenAddress, uint256 amtTokens) public {
require (msg.sender == OWNER);
ERC20(tokenAddress).transfer(msg.sender, amtTokens);
}
///////////////////////////////
// BASIC ERC20 TOKEN OPERATIONS
///////////////////////////////
function totalSupply() constant public returns(uint){
return totalSupply;
}
function balanceOf(address _owner) constant public returns(uint){
return balances[_owner];
}
// don't allow transfers before the required wait-time
// and don't allow transfers to this contract addr, it'll just kill tokens
function transfer(address _to, uint256 _value) public returns (bool success){
require(balances[msg.sender] >= _value
&& contributionTime[msg.sender] + WAITTIMEUNTILWITHDRAWORTRANSFER <= block.timestamp
&& _to != address(this)
&& _to != address(0));
// safely subtract
balances[msg.sender] = SafeMath.sub(balances[msg.sender], _value);
balances[_to] = SafeMath.add(balances[_to], _value);
// log event
emit Transfer(msg.sender, _to, _value);
return true;
}
// don't allow transfers before the required wait-time
// and don't allow transfers to the contract addr, it'll just kill tokens
function transferFrom(address _from, address _to, uint _value) public returns(bool){
require(allowed[_from][msg.sender] >= _value
&& balances[_from] >= _value
&& contributionTime[_from] + WAITTIMEUNTILWITHDRAWORTRANSFER <= block.timestamp
&& _to != address(this)
&& _to != address(0));
// safely add to _to and subtract from _from, and subtract from allowed balances.
balances[_to] = SafeMath.add(balances[_to], _value);
balances[_from] = SafeMath.sub(balances[_from], _value);
allowed[_from][msg.sender] = SafeMath.sub(allowed[_from][msg.sender], _value);
// log event
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public returns(bool){
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
// log event
return true;
}
function allowance(address _owner, address _spender) constant public returns(uint){
return allowed[_owner][_spender];
}
}
pragma solidity ^0.4.18;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn'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;
}
}
contract EOSBetDice is usingOraclize, EOSBetGameInterface {
using SafeMath for *;
// events
event BuyRolls(bytes32 indexed oraclizeQueryId);
event LedgerProofFailed(bytes32 indexed oraclizeQueryId);
event Refund(bytes32 indexed oraclizeQueryId, uint256 amount);
event DiceSmallBet(uint16 actualRolls, uint256 data1, uint256 data2, uint256 data3, uint256 data4);
event DiceLargeBet(bytes32 indexed oraclizeQueryId, uint16 actualRolls, uint256 data1, uint256 data2, uint256 data3, uint256 data4);
// game data structure
struct DiceGameData {
address player;
bool paidOut;
uint256 start;
uint256 etherReceived;
uint256 betPerRoll;
uint16 rolls;
uint8 rollUnder;
}
mapping (bytes32 => DiceGameData) public diceData;
// ether in this contract can be in one of two locations:
uint256 public LIABILITIES;
uint256 public DEVELOPERSFUND;
// counters for frontend statistics
uint256 public AMOUNTWAGERED;
uint256 public GAMESPLAYED;
// togglable values
uint256 public ORACLIZEQUERYMAXTIME;
uint256 public MINBET_perROLL;
uint256 public MINBET_perTX;
uint256 public ORACLIZEGASPRICE;
uint256 public INITIALGASFORORACLIZE;
uint8 public HOUSEEDGE_inTHOUSANDTHPERCENTS; // 1 thousanthpercent == 1/1000,
uint8 public MAXWIN_inTHOUSANDTHPERCENTS; // determines the maximum win a user may receive.
// togglable functionality of contract
bool public GAMEPAUSED;
bool public REFUNDSACTIVE;
// owner of contract
address public OWNER;
// bankroller address
address public BANKROLLER;
// constructor
function EOSBetDice() public {
// ledger proof is ALWAYS verified on-chain
oraclize_setProof(proofType_Ledger);
// gas prices for oraclize call back, can be changed
oraclize_setCustomGasPrice(8000000000);
ORACLIZEGASPRICE = 8000000000;
INITIALGASFORORACLIZE = 300000;
AMOUNTWAGERED = 0;
GAMESPLAYED = 0;
GAMEPAUSED = false;
REFUNDSACTIVE = true;
ORACLIZEQUERYMAXTIME = 6 hours;
MINBET_perROLL = 20 finney;
MINBET_perTX = 100 finney;
HOUSEEDGE_inTHOUSANDTHPERCENTS = 5; // 5/1000 == 0.5% house edge
MAXWIN_inTHOUSANDTHPERCENTS = 20; // 20/1000 == 2.0% of bankroll can be won in a single bet, will be lowered once there is more investors
OWNER = msg.sender;
}
////////////////////////////////////
// INTERFACE CONTACT FUNCTIONS
////////////////////////////////////
function payDevelopersFund(address developer) public {
require(msg.sender == BANKROLLER);
uint256 devFund = DEVELOPERSFUND;
DEVELOPERSFUND = 0;
developer.transfer(devFund);
}
// just a function to receive eth, only allow the bankroll to use this
function receivePaymentForOraclize() payable public {
require(msg.sender == BANKROLLER);
}
////////////////////////////////////
// VIEW FUNCTIONS
////////////////////////////////////
function getMaxWin() public view returns(uint256){
return (SafeMath.mul(EOSBetBankrollInterface(BANKROLLER).getBankroll(), MAXWIN_inTHOUSANDTHPERCENTS) / 1000);
}
////////////////////////////////////
// OWNER ONLY FUNCTIONS
////////////////////////////////////
// WARNING!!!!! Can only set this function once!
function setBankrollerContractOnce(address bankrollAddress) public {
// require that BANKROLLER address == 0 (address not set yet), and coming from owner.
require(msg.sender == OWNER && BANKROLLER == address(0));
// check here to make sure that the bankroll contract is legitimate
// just make sure that calling the bankroll contract getBankroll() returns non-zero
require(EOSBetBankrollInterface(bankrollAddress).getBankroll() != 0);
BANKROLLER = bankrollAddress;
}
function transferOwnership(address newOwner) public {
require(msg.sender == OWNER);
OWNER = newOwner;
}
function setOraclizeQueryMaxTime(uint256 newTime) public {
require(msg.sender == OWNER);
ORACLIZEQUERYMAXTIME = newTime;
}
// store the gas price as a storage variable for easy reference,
// and then change the gas price using the proper oraclize function
function setOraclizeQueryGasPrice(uint256 gasPrice) public {
require(msg.sender == OWNER);
ORACLIZEGASPRICE = gasPrice;
oraclize_setCustomGasPrice(gasPrice);
}
// should be ~175,000 to save eth
function setInitialGasForOraclize(uint256 gasAmt) public {
require(msg.sender == OWNER);
INITIALGASFORORACLIZE = gasAmt;
}
function setGamePaused(bool paused) public {
require(msg.sender == OWNER);
GAMEPAUSED = paused;
}
function setRefundsActive(bool active) public {
require(msg.sender == OWNER);
REFUNDSACTIVE = active;
}
function setHouseEdge(uint8 houseEdgeInThousandthPercents) public {
// house edge cannot be set > 5%, can be set to zero for promotions
require(msg.sender == OWNER && houseEdgeInThousandthPercents <= 50);
HOUSEEDGE_inTHOUSANDTHPERCENTS = houseEdgeInThousandthPercents;
}
function setMinBetPerRoll(uint256 minBet) public {
require(msg.sender == OWNER && minBet > 1000);
MINBET_perROLL = minBet;
}
function setMinBetPerTx(uint256 minBet) public {
require(msg.sender == OWNER && minBet > 1000);
MINBET_perTX = minBet;
}
function setMaxWin(uint8 newMaxWinInThousandthPercents) public {
// cannot set bet limit greater than 5% of total BANKROLL.
require(msg.sender == OWNER && newMaxWinInThousandthPercents <= 50);
MAXWIN_inTHOUSANDTHPERCENTS = newMaxWinInThousandthPercents;
}
// rescue tokens inadvertently sent to the contract address
function ERC20Rescue(address tokenAddress, uint256 amtTokens) public {
require (msg.sender == OWNER);
ERC20(tokenAddress).transfer(msg.sender, amtTokens);
}
// require that the query time is too slow, bet has not been paid out, and either contract owner or player is calling this function.
// this will only be used/can occur on queries that are forwarded to oraclize in the first place. All others will be paid out immediately.
function refund(bytes32 oraclizeQueryId) public {
// store data in memory for easy access.
DiceGameData memory data = diceData[oraclizeQueryId];
require(block.timestamp - data.start >= ORACLIZEQUERYMAXTIME
&& (msg.sender == OWNER || msg.sender == data.player)
&& (!data.paidOut)
&& LIABILITIES >= data.etherReceived
&& data.etherReceived > 0
&& REFUNDSACTIVE);
// set paidout == true, so users can't request more refunds, and a super delayed oraclize __callback will just get reverted
diceData[oraclizeQueryId].paidOut = true;
// subtract etherReceived because the bet is being refunded
LIABILITIES = SafeMath.sub(LIABILITIES, data.etherReceived);
// then transfer the original bet to the player.
data.player.transfer(data.etherReceived);
// finally, log an event saying that the refund has processed.
emit Refund(oraclizeQueryId, data.etherReceived);
}
function play(uint256 betPerRoll, uint16 rolls, uint8 rollUnder) public payable {
// store in memory for cheaper access
uint256 minBetPerTx = MINBET_perTX;
require(!GAMEPAUSED
&& betPerRoll * rolls >= minBetPerTx
&& msg.value >= minBetPerTx
&& betPerRoll >= MINBET_perROLL
&& rolls > 0
&& rolls <= 1024
&& betPerRoll <= msg.value
&& rollUnder > 1
&& rollUnder < 98
// make sure that the player cannot win more than the max win (forget about house edge here)
&& (SafeMath.mul(betPerRoll, 100) / (rollUnder - 1)) <= getMaxWin());
// equation for gas to oraclize is:
// gas = (some fixed gas amt) + 1005 * rolls
uint256 gasToSend = INITIALGASFORORACLIZE + (uint256(1005) * rolls);
EOSBetBankrollInterface(BANKROLLER).payOraclize(oraclize_getPrice('random', gasToSend));
// oraclize_newRandomDSQuery(delay in seconds, bytes of random data, gas for callback function)
bytes32 oraclizeQueryId = oraclize_newRandomDSQuery(0, 30, gasToSend);
diceData[oraclizeQueryId] = DiceGameData({
player : msg.sender,
paidOut : false,
start : block.timestamp,
etherReceived : msg.value,
betPerRoll : betPerRoll,
rolls : rolls,
rollUnder : rollUnder
});
// add the sent value into liabilities. this should NOT go into the bankroll yet
// and must be quarantined here to prevent timing attacks
LIABILITIES = SafeMath.add(LIABILITIES, msg.value);
// log an event
emit BuyRolls(oraclizeQueryId);
}
// oraclize callback.
// Basically do the instant bet resolution in the play(...) function above, but with the random data
// that oraclize returns, instead of getting psuedo-randomness from block.blockhash
function __callback(bytes32 _queryId, string _result, bytes _proof) public {
DiceGameData memory data = diceData[_queryId];
// only need to check these, as all of the game based checks were already done in the play(...) function
require(msg.sender == oraclize_cbAddress()
&& !data.paidOut
&& data.player != address(0)
&& LIABILITIES >= data.etherReceived);
// if the proof has failed, immediately refund the player his original bet...
if (oraclize_randomDS_proofVerify__returnCode(_queryId, _result, _proof) != 0){
if (REFUNDSACTIVE){
// set contract data
diceData[_queryId].paidOut = true;
// if the call fails, then subtract the original value sent from liabilites and amount wagered, and then send it back
LIABILITIES = SafeMath.sub(LIABILITIES, data.etherReceived);
// transfer the original bet
data.player.transfer(data.etherReceived);
// log the refund
emit Refund(_queryId, data.etherReceived);
}
// log the ledger proof fail
emit LedgerProofFailed(_queryId);
}
// else, resolve the bet as normal with this miner-proof proven-randomness from oraclize.
else {
// save these in memory for cheap access
uint8 houseEdgeInThousandthPercents = HOUSEEDGE_inTHOUSANDTHPERCENTS;
// set the current balance available to the player as etherReceived
uint256 etherAvailable = data.etherReceived;
// logs for the frontend, as before...
uint256[] memory logsData = new uint256[](4);
// this loop is highly similar to the one from before. Instead of fully documented, the differences will be pointed out instead.
uint256 winnings;
uint16 gamesPlayed;
// get this value outside of the loop for gas costs sake
uint256 hypotheticalWinAmount = SafeMath.mul(SafeMath.mul(data.betPerRoll, 100), (1000 - houseEdgeInThousandthPercents)) / (data.rollUnder - 1) / 1000;
while (gamesPlayed < data.rolls && etherAvailable >= data.betPerRoll){
// now, this roll is keccak256(_result, nonce) + 1 ... this is the main difference from using oraclize.
if (uint8(uint256(keccak256(_result, gamesPlayed)) % 100) + 1 < data.rollUnder){
// now, just get the respective fields from data.field unlike before where they were in seperate variables.
winnings = hypotheticalWinAmount;
// assemble logs...
if (gamesPlayed <= 255){
logsData[0] += uint256(2) ** (255 - gamesPlayed);
}
else if (gamesPlayed <= 511){
logsData[1] += uint256(2) ** (511 - gamesPlayed);
}
else if (gamesPlayed <= 767){
logsData[2] += uint256(2) ** (767 - gamesPlayed);
}
else {
logsData[3] += uint256(2) ** (1023 - gamesPlayed);
}
}
else {
// leave 1 wei as a consolation prize :)
winnings = 1;
}
gamesPlayed++;
etherAvailable = SafeMath.sub(SafeMath.add(etherAvailable, winnings), data.betPerRoll);
}
// track that these games were played
GAMESPLAYED += gamesPlayed;
// and add the amount wagered
AMOUNTWAGERED = SafeMath.add(AMOUNTWAGERED, SafeMath.mul(data.betPerRoll, gamesPlayed));
// IMPORTANT: we must change the "paidOut" to TRUE here to prevent reentrancy/other nasty effects.
// this was not needed with the previous loop/code block, and is used because variables must be written into storage
diceData[_queryId].paidOut = true;
// decrease LIABILITIES when the spins are made
LIABILITIES = SafeMath.sub(LIABILITIES, data.etherReceived);
// get the developers cut, and send the rest of the ether received to the bankroller contract
uint256 developersCut = SafeMath.mul(SafeMath.mul(data.betPerRoll, houseEdgeInThousandthPercents), gamesPlayed) / 5000;
// add the devs cut to the developers fund.
DEVELOPERSFUND = SafeMath.add(DEVELOPERSFUND, developersCut);
EOSBetBankrollInterface(BANKROLLER).receiveEtherFromGameAddress.value(SafeMath.sub(data.etherReceived, developersCut))();
// force the bankroller contract to pay out the player
EOSBetBankrollInterface(BANKROLLER).payEtherToWinner(etherAvailable, data.player);
// log an event, now with the oraclize query id
emit DiceLargeBet(_queryId, gamesPlayed, logsData[0], logsData[1], logsData[2], logsData[3]);
}
}
// END OF CONTRACT. REPORT ANY BUGS TO [email protected]
// YES! WE _DO_ HAVE A BUG BOUNTY PROGRAM!
// THANK YOU FOR READING THIS CONTRACT, HAVE A NICE DAY :)
}
|
now credit the user with his amount of contributed tokens
|
balances[msg.sender] = SafeMath.add(balances[msg.sender], creditedTokens);
| 450,552 |
[
1,
3338,
12896,
326,
729,
598,
18423,
3844,
434,
356,
11050,
2430,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
202,
202,
70,
26488,
63,
3576,
18,
15330,
65,
273,
14060,
10477,
18,
1289,
12,
70,
26488,
63,
3576,
18,
15330,
6487,
12896,
329,
5157,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.6;
// Imports symbols from other files into the current contract.
// In this case, a series of helper contracts from OpenZeppelin.
// Learn more: https://solidity.readthedocs.io/en/v0.6.2/layout-of-source-files.html#importing-other-source-files
// IERC721 is the ERC721 interface that we'll use to make Avatheeer ERC721 compliant
// More about ERC721: https://eips.ethereum.org/EIPS/eip-721
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
// IERC721Receiver must be implemented to accept safe transfers.
// It is included on the ERC721 standard
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
// ERC165 is used to declare interface support for IERC721
// More about ERC165: https://eips.ethereum.org/EIPS/eip-165
import "@openzeppelin/contracts/introspection/ERC165.sol";
// SafeMath will be used for every math operation
import "@openzeppelin/contracts/math/SafeMath.sol";
// Address will provide functions such as .isContract verification
import "@openzeppelin/contracts/utils/Address.sol";
// Chainlink oracle smart contract for vrf
import "@chainlink/contracts/src/v0.6/VRFConsumerBase.sol";
// The `is` keyword is used to inherit functions and keywords from external contracts.
// In this case, `Avatheeer` inherits from the `IERC721` and `ERC165` contracts.
// Learn more: https://solidity.readthedocs.io/en/v0.6.2/contracts.html#inheritance
contract Avatheeers is IERC721, ERC165, VRFConsumerBase {
// Uses OpenZeppelin's SafeMath library to perform arithmetic operations safely.
// Learn more: https://docs.openzeppelin.com/contracts/3.x/api/math#SafeMath
using SafeMath for uint256;
// Use OpenZeppelin's Address library to validate whether an address is
// is a contract or not.
// Learn more: https://docs.openzeppelin.com/contracts/3.x/api/utils#Address
using Address for address;
// Required variables for chainlink operation
bytes32 internal keyHash;
uint256 internal fee;
uint256 public randomResult;
bytes32 internal currReqId;
// Constant state variables in Solidity are similar to other languages
// but you must assign from an expression which is constant at compile time.
// Learn more: https://solidity.readthedocs.io/en/v0.6.2/contracts.html#constant-state-variables
uint256 constant dnaDigits = 26;
uint256 constant dnaModulus = 26**dnaDigits;
// ERC165 identifier for the ERC721 interface got from
// bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Struct types let you define your own type
// Learn more: https://solidity.readthedocs.io/en/v0.6.2/types.html#structs
struct Avatheeer {
string name;
uint256 dna;
}
// Creates an empty array of Avatheeer structs
Avatheeer[] public avatheeers;
// Mapping from id of Avatheeer to its owner's address
mapping(uint256 => address) public avatheeerToOwner;
// Mapping from owner's address to number of owned token
mapping(address => uint256) public ownerAvatheeerCount;
// Mapping to validate that dna is not already taken
mapping(uint256 => bool) public dnaAvatheeerExists;
// Mapping from token ID to approved address
mapping(uint256 => address) avatheeerApprovals;
// You can nest mappings, this example maps owner to operator approvals
mapping(address => mapping(address => bool)) private operatorApprovals;
// Check if Avatheeer is unique and doesn't exist yet
modifier isUnique(uint256 _dna) {
require(
!dnaAvatheeerExists[_dna],
"Avatheeer with such dna already exists."
);
_;
}
/**
* Constructor inherits VRFConsumerBase
*
* Network: Rinkeby
* Chainlink VRF Coordinator address: 0xb3dCcb4Cf7a26f6cf6B120Cf5A73875B7BBc655B
* LINK token address: 0x01BE23585060835E02B77ef475b0Cc51aA1e0709
* Key Hash: 0x2ed0feb3e7fd2022120aa84fab1945545a9f2ffc9076fd6156fa96eaff4c1311
*/
constructor()
public
VRFConsumerBase(
0xb3dCcb4Cf7a26f6cf6B120Cf5A73875B7BBc655B, // VRF Coordinator
0x01BE23585060835E02B77ef475b0Cc51aA1e0709 // LINK Token
)
{
keyHash = 0x2ed0feb3e7fd2022120aa84fab1945545a9f2ffc9076fd6156fa96eaff4c1311;
fee = 0.1 * 10**18; // 0.1 LINK
}
function refreshRandom(string memory _name)
internal
returns (bytes32 requestId)
{
require(
LINK.balanceOf(address(this)) > fee,
"Not enough LINK - fill contract with faucet"
);
uint256 seed = uint256(keccak256(abi.encodePacked(_name)));
return requestRandomness(keyHash, fee, seed);
}
// Callback function used by VRF Coordinator
// Creates a random Avatheeer from string (name)
function fulfillRandomness(bytes32 requestId, uint256 randomness)
internal
override
{
currReqId = requestId;
randomResult = randomness;
}
// Creates a random Avatheeer from string (name)
function createRandomAvatheeer(string memory _name) public {
uint256 randDna = generateRandomDna(_name, msg.sender);
_createAvatheeer(_name, randDna);
refreshRandom(_name);
}
// Generates random DNA from string (name) and address of the owner (creator)
function generateRandomDna(string memory _str, address _owner)
public
view
returns (
// Functions marked as `pure` promise not to read from or modify the state
// Learn more: https://solidity.readthedocs.io/en/v0.6.2/contracts.html#pure-functions
uint256
)
{
// Generates random uint from string (name) + random chainlink oracle result + address (owner)
uint256 rand = uint256(keccak256(abi.encodePacked(_str))) + randomResult +
uint256(_owner);
rand = SafeMath.mod(rand, dnaModulus);
return rand;
}
// Internal function to create a random Avatheeer from string (name) and DNA
function _createAvatheeer(string memory _name, uint256 _dna)
internal
// The `internal` keyword means this function is only visible
// within this contract and contracts that derive this contract
// Learn more: https://solidity.readthedocs.io/en/v0.6.2/contracts.html#visibility-and-getters
// `isUnique` is a function modifier that checks if the avatheeer already exists
// Learn more: https://solidity.readthedocs.io/en/v0.6.2/structure-of-a-contract.html#function-modifiers
isUnique(_dna)
{
// Adds Avatheeer to array of Avatheeers and get id
avatheeers.push(Avatheeer(_name, _dna));
uint256 id = SafeMath.sub(avatheeers.length, 1);
// Mark as existent avatheeer name and dna
dnaAvatheeerExists[_dna] = true;
// Checks that Avatheeer owner is the same as current user
// Learn more: https://solidity.readthedocs.io/en/v0.6.2/control-structures.html#error-handling-assert-require-revert-and-exceptions
assert(avatheeerToOwner[id] == address(0));
// Maps the Avatheeer to the owner
avatheeerToOwner[id] = msg.sender;
ownerAvatheeerCount[msg.sender] = SafeMath.add(
ownerAvatheeerCount[msg.sender],
1
);
}
// Returns array of Avatheeers found by owner
function getAvatheeersByOwner(address _owner)
public
view
returns (
// Functions marked as `view` promise not to modify state
// Learn more: https://solidity.readthedocs.io/en/v0.6.2/contracts.html#view-functions
uint256[] memory
)
{
// Uses the `memory` storage location to store values only for the
// lifecycle of this function call.
// Learn more: https://solidity.readthedocs.io/en/v0.6.2/introduction-to-smart-contracts.html#storage-memory-and-the-stack
uint256[] memory result = new uint256[](ownerAvatheeerCount[_owner]);
uint256 counter = 0;
for (uint256 i = 0; i < avatheeers.length; i++) {
if (avatheeerToOwner[i] == _owner) {
result[counter] = i;
counter++;
}
}
return result;
}
// Returns count of Avatheeers by address
function balanceOf(address _owner)
public
override
view
returns (uint256 _balance)
{
return ownerAvatheeerCount[_owner];
}
// Returns owner of the Avatheeer found by id
function ownerOf(uint256 _avatheeerId)
public
override
view
returns (address _owner)
{
address owner = avatheeerToOwner[_avatheeerId];
require(owner != address(0), "Invalid Avatheeer ID.");
return owner;
}
/**
* Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`;
* otherwise, the transfer is reverted.
*/
function safeTransferFrom(
address from,
address to,
uint256 avatheeerId
) public override {
// solium-disable-next-line arg-overflow
safeTransferFrom(from, to, avatheeerId, "");
}
// Transfers Avatheeer and ownership to other address
function transferFrom(
address _from,
address _to,
uint256 _avatheeerId
) public override {
require(_from != address(0) && _to != address(0), "Invalid address.");
require(_exists(_avatheeerId), "Avatheeer does not exist.");
require(_from != _to, "Cannot transfer to the same address.");
require(
_isApprovedOrOwner(msg.sender, _avatheeerId),
"Address is not approved."
);
ownerAvatheeerCount[_to] = SafeMath.add(ownerAvatheeerCount[_to], 1);
ownerAvatheeerCount[_from] = SafeMath.sub(ownerAvatheeerCount[_from], 1);
avatheeerToOwner[_avatheeerId] = _to;
// Emits event defined in the imported IERC721 contract
emit Transfer(_from, _to, _avatheeerId);
_clearApproval(_to, _avatheeerId);
}
// Checks if Avatheeer exists
function _exists(uint256 avatheeerId) internal view returns (bool) {
address owner = avatheeerToOwner[avatheeerId];
return owner != address(0);
}
// Checks if address is owner or is approved to transfer Avatheeer
function _isApprovedOrOwner(address spender, uint256 avatheeerId)
internal
view
returns (bool)
{
address owner = avatheeerToOwner[avatheeerId];
// Disable solium check because of
// https://github.com/duaraghav8/Solium/issues/175
// solium-disable-next-line operator-whitespace
return (spender == owner ||
getApproved(avatheeerId) == spender ||
isApprovedForAll(owner, spender));
}
/**
* Private function to clear current approval of a given token ID
* Reverts if the given address is not indeed the owner of the token
*/
function _clearApproval(address owner, uint256 _avatheeerId) private {
require(
avatheeerToOwner[_avatheeerId] == owner,
"Must be avatheeer owner."
);
require(_exists(_avatheeerId), "Avatheeer does not exist.");
if (avatheeerApprovals[_avatheeerId] != address(0)) {
avatheeerApprovals[_avatheeerId] = address(0);
}
}
// Approves other address to transfer ownership of Avatheeer
function approve(address _to, uint256 _avatheeerId) public override {
require(
msg.sender == avatheeerToOwner[_avatheeerId],
"Must be the Avatheeer owner."
);
avatheeerApprovals[_avatheeerId] = _to;
emit Approval(msg.sender, _to, _avatheeerId);
}
// Returns approved address for specific Avatheeer
function getApproved(uint256 _avatheeerId)
public
override
view
returns (address operator)
{
require(_exists(_avatheeerId), "Avatheeer does not exist.");
return avatheeerApprovals[_avatheeerId];
}
/*
* Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf
*/
function setApprovalForAll(address to, bool approved) public override {
require(to != msg.sender, "Cannot approve own address");
operatorApprovals[msg.sender][to] = approved;
emit ApprovalForAll(msg.sender, to, approved);
}
// Tells whether an operator is approved by a given owner
function isApprovedForAll(address owner, address operator)
public
override
view
returns (bool)
{
return operatorApprovals[owner][operator];
}
/**
* Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`;
* otherwise, the transfer is reverted.
*/
function safeTransferFrom(
address from,
address to,
uint256 avatheeerId,
bytes memory _data
) public override {
transferFrom(from, to, avatheeerId);
require(
_checkOnERC721Received(from, to, avatheeerId, _data),
"Must implmement onERC721Received."
);
}
/**
* Internal function to invoke `onERC721Received` on a target address
* The call is not executed if the target address is not a contract
*/
function _checkOnERC721Received(
address from,
address to,
uint256 avatheeerId,
bytes memory _data
) internal returns (bool) {
if (!to.isContract()) {
return true;
}
bytes4 retval = IERC721Receiver(to).onERC721Received(
msg.sender,
from,
avatheeerId,
_data
);
return (retval == _ERC721_RECEIVED);
}
// Burns a Avatheeer - destroys Token completely
// The `external` function modifier means this function is
// part of the contract interface and other contracts can call it
function burn(uint256 _avatheeerId) external {
require(msg.sender != address(0), "Invalid address.");
require(_exists(_avatheeerId), "Avatheeer does not exist.");
require(
_isApprovedOrOwner(msg.sender, _avatheeerId),
"Address is not approved."
);
ownerAvatheeerCount[msg.sender] = SafeMath.sub(
ownerAvatheeerCount[msg.sender],
1
);
avatheeerToOwner[_avatheeerId] = address(0);
}
// Takes ownership of Avatheeer - only for approved users
function takeOwnership(uint256 _avatheeerId) public {
require(
_isApprovedOrOwner(msg.sender, _avatheeerId),
"Address is not approved."
);
address owner = ownerOf(_avatheeerId);
transferFrom(owner, msg.sender, _avatheeerId);
}
}
|
Internal function to create a random Avatheeer from string (name) and DNA The `internal` keyword means this function is only visible within this contract and contracts that derive this contract Learn more: https:solidity.readthedocs.io/en/v0.6.2/contracts.html#visibility-and-getters `isUnique` is a function modifier that checks if the avatheeer already exists Learn more: https:solidity.readthedocs.io/en/v0.6.2/structure-of-a-contract.html#function-modifiers Adds Avatheeer to array of Avatheeers and get id Mark as existent avatheeer name and dna Checks that Avatheeer owner is the same as current user Learn more: https:solidity.readthedocs.io/en/v0.6.2/control-structures.html#error-handling-assert-require-revert-and-exceptions Maps the Avatheeer to the owner
|
function _createAvatheeer(string memory _name, uint256 _dna)
internal
isUnique(_dna)
{
avatheeers.push(Avatheeer(_name, _dna));
uint256 id = SafeMath.sub(avatheeers.length, 1);
dnaAvatheeerExists[_dna] = true;
assert(avatheeerToOwner[id] == address(0));
avatheeerToOwner[id] = msg.sender;
ownerAvatheeerCount[msg.sender] = SafeMath.add(
ownerAvatheeerCount[msg.sender],
1
);
}
| 6,463,358 |
[
1,
3061,
445,
358,
752,
279,
2744,
8789,
421,
1340,
264,
628,
533,
261,
529,
13,
471,
463,
11277,
1021,
1375,
7236,
68,
4932,
4696,
333,
445,
353,
1338,
6021,
3470,
333,
6835,
471,
20092,
716,
14763,
333,
6835,
3519,
1303,
1898,
30,
2333,
30,
30205,
560,
18,
25254,
329,
22280,
18,
1594,
19,
275,
19,
90,
20,
18,
26,
18,
22,
19,
16351,
87,
18,
2620,
14422,
17,
464,
17,
588,
5432,
1375,
291,
6303,
68,
353,
279,
445,
9606,
716,
4271,
309,
326,
1712,
421,
1340,
264,
1818,
1704,
3519,
1303,
1898,
30,
2333,
30,
30205,
560,
18,
25254,
329,
22280,
18,
1594,
19,
275,
19,
90,
20,
18,
26,
18,
22,
19,
7627,
17,
792,
17,
69,
17,
16351,
18,
2620,
915,
17,
15432,
15605,
8789,
421,
1340,
264,
358,
526,
434,
8789,
421,
1340,
414,
471,
336,
612,
6622,
487,
30364,
1712,
421,
1340,
264,
2
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
[
1,
565,
445,
389,
2640,
3769,
421,
1340,
264,
12,
1080,
3778,
389,
529,
16,
2254,
5034,
389,
5176,
69,
13,
203,
3639,
2713,
203,
3639,
353,
6303,
24899,
5176,
69,
13,
203,
565,
288,
203,
3639,
1712,
421,
1340,
414,
18,
6206,
12,
3769,
421,
1340,
264,
24899,
529,
16,
389,
5176,
69,
10019,
203,
3639,
2254,
5034,
612,
273,
14060,
10477,
18,
1717,
12,
842,
421,
1340,
414,
18,
2469,
16,
404,
1769,
203,
203,
3639,
31702,
3769,
421,
1340,
264,
4002,
63,
67,
5176,
69,
65,
273,
638,
31,
203,
203,
3639,
1815,
12,
842,
421,
1340,
264,
774,
5541,
63,
350,
65,
422,
1758,
12,
20,
10019,
203,
203,
3639,
1712,
421,
1340,
264,
774,
5541,
63,
350,
65,
273,
1234,
18,
15330,
31,
203,
3639,
3410,
3769,
421,
1340,
264,
1380,
63,
3576,
18,
15330,
65,
273,
14060,
10477,
18,
1289,
12,
203,
5411,
3410,
3769,
421,
1340,
264,
1380,
63,
3576,
18,
15330,
6487,
203,
5411,
404,
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
] |
./full_match/1/0x3b871aa1b9Af565A30466c9fa4B90e651891E4ee/sources/contracts/Strategy.sol
|
@notice Emergency withdraw all assets on the contract. @return _treasuryAmount The amount of treasury asset. @return _feeAmount The amount of mint/redeem fee.
|
function emergencyWithdraw() external onlyOwner returns (uint256 _treasuryAmount, uint256 _feeAmount) {
address owner = owner();
ITreasury _treasury = ITreasury(treasury);
IERC20Upgradeable baseToken = IERC20Upgradeable(_treasury.baseToken());
_treasuryAmount = baseToken.balanceOf(treasury);
_feeAmount = baseToken.balanceOf(address(this));
if (_treasuryAmount > 0) {
ITreasury(treasury).transferToStrategy(_treasuryAmount);
baseToken.transfer(owner, _treasuryAmount);
}
if (_feeAmount > 0) baseToken.transfer(owner, _feeAmount);
}
| 3,131,361 |
[
1,
1514,
24530,
598,
9446,
777,
7176,
603,
326,
6835,
18,
327,
389,
27427,
345,
22498,
6275,
1021,
3844,
434,
9787,
345,
22498,
3310,
18,
327,
389,
21386,
6275,
1021,
3844,
434,
312,
474,
19,
266,
24903,
14036,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
225,
445,
801,
24530,
1190,
9446,
1435,
3903,
1338,
5541,
1135,
261,
11890,
5034,
389,
27427,
345,
22498,
6275,
16,
2254,
5034,
389,
21386,
6275,
13,
288,
203,
565,
1758,
3410,
273,
3410,
5621,
203,
565,
24142,
266,
345,
22498,
389,
27427,
345,
22498,
273,
24142,
266,
345,
22498,
12,
27427,
345,
22498,
1769,
203,
565,
467,
654,
39,
3462,
10784,
429,
1026,
1345,
273,
467,
654,
39,
3462,
10784,
429,
24899,
27427,
345,
22498,
18,
1969,
1345,
10663,
203,
565,
389,
27427,
345,
22498,
6275,
273,
1026,
1345,
18,
12296,
951,
12,
27427,
345,
22498,
1769,
203,
565,
389,
21386,
6275,
273,
1026,
1345,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
203,
565,
309,
261,
67,
27427,
345,
22498,
6275,
405,
374,
13,
288,
203,
1377,
24142,
266,
345,
22498,
12,
27427,
345,
22498,
2934,
13866,
774,
4525,
24899,
27427,
345,
22498,
6275,
1769,
203,
1377,
1026,
1345,
18,
13866,
12,
8443,
16,
389,
27427,
345,
22498,
6275,
1769,
203,
565,
289,
203,
565,
309,
261,
67,
21386,
6275,
405,
374,
13,
1026,
1345,
18,
13866,
12,
8443,
16,
389,
21386,
6275,
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
] |
pragma solidity ^0.4.18;
import "./zeppelin-solidity/contracts/ownership/Ownable.sol";
import "./interfaces/ISettingsStorage.sol";
import "./IssuanceWhiteList.sol";
contract SettingsStorage is ISettingsStorage, Ownable {
/**
* @dev Toggle for locking/unlocking trades at a token level.
* The default behavior of the zero memory state for locking will be unlocked.
*/
bool public locked;
/// @dev Toggle for allowing/disallowing new shareholders
bool public newShareholdersAllowed;
/// @dev Issuers of the token
mapping(address => bool) public officers;
/// @dev Initial offering end date
uint256 public initialOfferEndDate;
/// @dev Array of whitelists
IssuanceWhiteList[] whitelists;
mapping(string => bool) issuerPermissions;
constructor (bool _locked, bool _newShareholdersAllowed, uint256 _initialOfferEndDate) public {
locked = _locked;
newShareholdersAllowed = _newShareholdersAllowed;
initialOfferEndDate = _initialOfferEndDate;
}
function setIssuerPermission(string permission, bool setting) public {
require (msg.sender == owner);
issuerPermissions[permission] = setting;
}
/**
* @notice Locks the ability to trade a token
*
* @dev This method can only be called by this contract's issuer
*
* @param _locked True for lock the token
*/
function setLocked(bool _locked) public {
require(issuerPermissions["setLocked"] && officers[msg.sender] || msg.sender == owner);
locked = _locked;
LogLockSet(_locked);
}
/**
* @notice Get whitelists
*
* @return IssuanceWhiteList[] Array of whitelists
*/
function getWhitelists() view public returns (IssuanceWhiteList[]) {
return whitelists;
}
function addWhitelist(IssuanceWhiteList _whitelist) public {
//check that we don't pass an empty list
require(_whitelist != address(0));
require(issuerPermissions["addWhitelist"] && officers[msg.sender] || msg.sender == owner);
bool contains = false;
//Loop through array to see if the whitelist is present
for (uint256 i = 0; i < whitelists.length; i++) {
if (whitelists[i] == _whitelist) {
//if it is, change the value of contains and stop
contains = true;
break;
}
}
//if not, push it into the array
if (!contains) {
whitelists.push(_whitelist);
WhitelistAdded(_whitelist);
}
}
function removeWhitelist(IssuanceWhiteList _whitelist) public {
//check that we don't pass an empty list
require(_whitelist != address(0));
require(issuerPermissions["removeWhitelist"] && officers[msg.sender] || msg.sender == owner);
//Loop through array to see if the whitelist is present
for (uint256 i = 0; i < whitelists.length; i++) {
//if we find it, we remove it from the list
if (whitelists[i] == _whitelist) {
remove(i);
WhitelistRemoved(_whitelist);
return;
}
}
}
function remove(uint256 index) private {
//check that the index doesn't exceed the list length
if (index >= whitelists.length)
return;
//move each list with one position on the left
for (uint256 i = index; i < whitelists.length-1; i++) {
whitelists[i] = whitelists[i+1];
}
//delete the last whitelist and decrease the array length
delete whitelists[whitelists.length-1];
whitelists.length--;
}
/**
* @notice Check if address is indeed in one of the whitelists
*
* @param _address Buyer to be added to whitelist
*
* @return True if buyer is added to whitelist, otherwise false
*/
function isWhiteListed(address _address) view public returns (bool, string) {
for (uint256 i = 0; i < whitelists.length; i++) {
if (whitelists[i].verify(_address))
return (true, whitelists[i].whitelistType());
}
return (false, "");
}
/**
* @notice Set initial offering end date
*
* @param _date Initial offering end date
*/
function setInititalOfferEndDate(uint256 _date) public {
require(issuerPermissions["setInititalOfferEndDate"] && officers[msg.sender] || msg.sender == owner);
initialOfferEndDate = _date;
InititalOfferEndDateSet(_date);
}
/**
* @notice Set officer of token
*
* @param _officer Officer to be set
*/
function addOfficer(address _officer) public {
require((officers[msg.sender] && _officer != address(0)) ||
msg.sender == owner);
officers[_officer] = true;
OfficerAdded(_officer);
}
/**
* @notice Remove officer of token
*
* @param _officer Officer to be removed
*/
function removeOfficer(address _officer) public {
require((officers[msg.sender] && _officer != address(0)) ||
msg.sender == owner);
officers[_officer] = false;
OfficerRemoved(_officer);
}
/**
* @notice Allow/disallow new shareholders
*
* @param allow Allow/disallow new shareholders
*/
function allowNewShareholders(bool allow) public {
require(issuerPermissions["allowNewShareholders"] && officers[msg.sender] || msg.sender == owner);
newShareholdersAllowed = allow;
NewShareholdersAllowance(allow);
}
}
|
* @notice Remove officer of token @param _officer Officer to be removed/
|
function removeOfficer(address _officer) public {
require((officers[msg.sender] && _officer != address(0)) ||
msg.sender == owner);
officers[_officer] = false;
OfficerRemoved(_officer);
}
| 12,800,760 |
[
1,
3288,
3397,
21349,
434,
1147,
282,
389,
3674,
21349,
531,
4493,
264,
358,
506,
3723,
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,
225,
445,
1206,
7210,
21349,
12,
2867,
389,
3674,
21349,
13,
1071,
288,
203,
565,
2583,
12443,
3674,
335,
414,
63,
3576,
18,
15330,
65,
597,
389,
3674,
21349,
480,
1758,
12,
20,
3719,
747,
203,
5411,
1234,
18,
15330,
422,
3410,
1769,
203,
203,
565,
3397,
335,
414,
63,
67,
3674,
21349,
65,
273,
629,
31,
203,
565,
531,
4493,
264,
10026,
24899,
3674,
21349,
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
] |
// SPDX-License-Identifier: AGPL-3.0-only
/*
DelegationController.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.8.11;
import "@openzeppelin/contracts/token/ERC777/IERC777.sol";
import "@skalenetwork/skale-manager-interfaces/delegation/IDelegationController.sol";
import "@skalenetwork/skale-manager-interfaces/delegation/IDelegationPeriodManager.sol";
import "@skalenetwork/skale-manager-interfaces/delegation/IPunisher.sol";
import "@skalenetwork/skale-manager-interfaces/delegation/ITokenState.sol";
import "@skalenetwork/skale-manager-interfaces/delegation/IValidatorService.sol";
import "@skalenetwork/skale-manager-interfaces/delegation/ILocker.sol";
import "@skalenetwork/skale-manager-interfaces/delegation/ITimeHelpers.sol";
import "@skalenetwork/skale-manager-interfaces/IBountyV2.sol";
import "@skalenetwork/skale-manager-interfaces/INodes.sol";
import "@skalenetwork/skale-manager-interfaces/IConstantsHolder.sol";
import "../Permissions.sol";
import "../utils/FractionUtils.sol";
import "../utils/MathUtils.sol";
import "./PartialDifferences.sol";
/**
* @title Delegation Controller
* @dev This contract performs all delegation functions including delegation
* requests, and undelegation, etc.
*
* Delegators and validators may both perform delegations. Validators who perform
* delegations to themselves are effectively self-delegating or self-bonding.
*
* IMPORTANT: Undelegation may be requested at any time, but undelegation is only
* performed at the completion of the current delegation period.
*
* Delegated tokens may be in one of several states:
*
* - PROPOSED: token holder proposes tokens to delegate to a validator.
* - ACCEPTED: token delegations are accepted by a validator and are locked-by-delegation.
* - CANCELED: token holder cancels delegation proposal. Only allowed before the proposal is accepted by the validator.
* - REJECTED: token proposal expires at the UTC start of the next month.
* - DELEGATED: accepted delegations are delegated at the UTC start of the month.
* - UNDELEGATION_REQUESTED: token holder requests delegations to undelegate from the validator.
* - COMPLETED: undelegation request is completed at the end of the delegation period.
*/
contract DelegationController is Permissions, ILocker, IDelegationController {
using MathUtils for uint;
using PartialDifferences for PartialDifferences.Sequence;
using PartialDifferences for PartialDifferences.Value;
using FractionUtils for FractionUtils.Fraction;
struct SlashingLogEvent {
FractionUtils.Fraction reducingCoefficient;
uint nextMonth;
}
struct SlashingLog {
// month => slashing event
mapping (uint => SlashingLogEvent) slashes;
uint firstMonth;
uint lastMonth;
}
struct DelegationExtras {
uint lastSlashingMonthBeforeDelegation;
}
struct SlashingEvent {
FractionUtils.Fraction reducingCoefficient;
uint validatorId;
uint month;
}
struct SlashingSignal {
address holder;
uint penalty;
}
struct LockedInPending {
uint amount;
uint month;
}
struct FirstDelegationMonth {
// month
uint value;
//validatorId => month
mapping (uint => uint) byValidator;
}
struct ValidatorsStatistics {
// number of validators
uint number;
//validatorId => amount of delegations
mapping (uint => uint) delegated;
}
uint public constant UNDELEGATION_PROHIBITION_WINDOW_SECONDS = 3 * 24 * 60 * 60;
/// @dev delegations will never be deleted to index in this array may be used like delegation id
Delegation[] public delegations;
// validatorId => delegationId[]
mapping (uint => uint[]) public delegationsByValidator;
// holder => delegationId[]
mapping (address => uint[]) public delegationsByHolder;
// delegationId => extras
mapping(uint => DelegationExtras) private _delegationExtras;
// validatorId => sequence
mapping (uint => PartialDifferences.Value) private _delegatedToValidator;
// validatorId => sequence
mapping (uint => PartialDifferences.Sequence) private _effectiveDelegatedToValidator;
// validatorId => slashing log
mapping (uint => SlashingLog) private _slashesOfValidator;
// holder => sequence
mapping (address => PartialDifferences.Value) private _delegatedByHolder;
// holder => validatorId => sequence
mapping (address => mapping (uint => PartialDifferences.Value)) private _delegatedByHolderToValidator;
// holder => validatorId => sequence
mapping (address => mapping (uint => PartialDifferences.Sequence)) private _effectiveDelegatedByHolderToValidator;
SlashingEvent[] private _slashes;
// holder => index in _slashes;
mapping (address => uint) private _firstUnprocessedSlashByHolder;
// holder => validatorId => month
mapping (address => FirstDelegationMonth) private _firstDelegationMonth;
// holder => locked in pending
mapping (address => LockedInPending) private _lockedInPendingDelegations;
mapping (address => ValidatorsStatistics) private _numberOfValidatorsPerDelegator;
/**
* @dev Modifier to make a function callable only if delegation exists.
*/
modifier checkDelegationExists(uint delegationId) {
require(delegationId < delegations.length, "Delegation does not exist");
_;
}
/**
* @dev Update and return a validator's delegations.
*/
function getAndUpdateDelegatedToValidatorNow(uint validatorId) external override returns (uint) {
return _getAndUpdateDelegatedToValidator(validatorId, _getCurrentMonth());
}
/**
* @dev Update and return the amount delegated.
*/
function getAndUpdateDelegatedAmount(address holder) external override returns (uint) {
return _getAndUpdateDelegatedByHolder(holder);
}
/**
* @dev Update and return the effective amount delegated (minus slash) for
* the given month.
*/
function getAndUpdateEffectiveDelegatedByHolderToValidator(address holder, uint validatorId, uint month)
external
override
allow("Distributor")
returns (uint effectiveDelegated)
{
SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(holder);
effectiveDelegated = _effectiveDelegatedByHolderToValidator[holder][validatorId]
.getAndUpdateValueInSequence(month);
_sendSlashingSignals(slashingSignals);
}
/**
* @dev Allows a token holder to create a delegation proposal of an `amount`
* and `delegationPeriod` to a `validatorId`. Delegation must be accepted
* by the validator before the UTC start of the month, otherwise the
* delegation will be rejected.
*
* The token holder may add additional information in each proposal.
*
* Emits a {DelegationProposed} event.
*
* Requirements:
*
* - Holder must have sufficient delegatable tokens.
* - Delegation must be above the validator's minimum delegation amount.
* - Delegation period must be allowed.
* - Validator must be authorized if trusted list is enabled.
* - Validator must be accepting new delegation requests.
*/
function delegate(
uint validatorId,
uint amount,
uint delegationPeriod,
string calldata info
)
external
override
{
require(
_getDelegationPeriodManager().isDelegationPeriodAllowed(delegationPeriod),
"This delegation period is not allowed");
_getValidatorService().checkValidatorCanReceiveDelegation(validatorId, amount);
_checkIfDelegationIsAllowed(msg.sender, validatorId);
SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(msg.sender);
uint delegationId = _addDelegation(
msg.sender,
validatorId,
amount,
delegationPeriod,
info);
// check that there is enough money
uint holderBalance = IERC777(contractManager.getSkaleToken()).balanceOf(msg.sender);
uint forbiddenForDelegation = ILocker(contractManager.getTokenState())
.getAndUpdateForbiddenForDelegationAmount(msg.sender);
require(holderBalance >= forbiddenForDelegation, "Token holder does not have enough tokens to delegate");
emit DelegationProposed(delegationId);
_sendSlashingSignals(slashingSignals);
}
/**
* @dev See {ILocker-getAndUpdateLockedAmount}.
*/
function getAndUpdateLockedAmount(address wallet) external override returns (uint) {
return _getAndUpdateLockedAmount(wallet);
}
/**
* @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}.
*/
function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) {
return _getAndUpdateLockedAmount(wallet);
}
/**
* @dev Allows token holder to cancel a delegation proposal.
*
* Emits a {DelegationRequestCanceledByUser} event.
*
* Requirements:
*
* - `msg.sender` must be the token holder of the delegation proposal.
* - Delegation state must be PROPOSED.
*/
function cancelPendingDelegation(uint delegationId) external override checkDelegationExists(delegationId) {
require(msg.sender == delegations[delegationId].holder, "Only token holders can cancel delegation request");
require(getState(delegationId) == State.PROPOSED, "Token holders are only able to cancel PROPOSED delegations");
delegations[delegationId].finished = _getCurrentMonth();
_subtractFromLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount);
emit DelegationRequestCanceledByUser(delegationId);
}
/**
* @dev Allows a validator to accept a proposed delegation.
* Successful acceptance of delegations transition the tokens from a
* PROPOSED state to ACCEPTED, and tokens are locked for the remainder of the
* delegation period.
*
* Emits a {DelegationAccepted} event.
*
* Requirements:
*
* - Validator must be recipient of proposal.
* - Delegation state must be PROPOSED.
*/
function acceptPendingDelegation(uint delegationId) external override checkDelegationExists(delegationId) {
require(
_getValidatorService().checkValidatorAddressToId(msg.sender, delegations[delegationId].validatorId),
"No permissions to accept request");
_accept(delegationId);
}
/**
* @dev Allows delegator to undelegate a specific delegation.
*
* Emits UndelegationRequested event.
*
* Requirements:
*
* - `msg.sender` must be the delegator or the validator.
* - Delegation state must be DELEGATED.
*/
function requestUndelegation(uint delegationId) external override checkDelegationExists(delegationId) {
require(getState(delegationId) == State.DELEGATED, "Cannot request undelegation");
IValidatorService validatorService = _getValidatorService();
require(
delegations[delegationId].holder == msg.sender ||
(validatorService.validatorAddressExists(msg.sender) &&
delegations[delegationId].validatorId == validatorService.getValidatorId(msg.sender)),
"Permission denied to request undelegation");
_removeValidatorFromValidatorsPerDelegators(
delegations[delegationId].holder,
delegations[delegationId].validatorId);
processAllSlashes(msg.sender);
delegations[delegationId].finished = _calculateDelegationEndMonth(delegationId);
require(
block.timestamp + UNDELEGATION_PROHIBITION_WINDOW_SECONDS
< _getTimeHelpers().monthToTimestamp(delegations[delegationId].finished),
"Undelegation requests must be sent 3 days before the end of delegation period"
);
_subtractFromAllStatistics(delegationId);
emit UndelegationRequested(delegationId);
}
/**
* @dev Allows Punisher contract to slash an `amount` of stake from
* a validator. This slashes an amount of delegations of the validator,
* which reduces the amount that the validator has staked. This consequence
* may force the SKALE Manager to reduce the number of nodes a validator is
* operating so the validator can meet the Minimum Staking Requirement.
*
* Emits a {SlashingEvent}.
*
* See {Punisher}.
*/
function confiscate(uint validatorId, uint amount) external override allow("Punisher") {
uint currentMonth = _getCurrentMonth();
FractionUtils.Fraction memory coefficient =
_delegatedToValidator[validatorId].reduceValue(amount, currentMonth);
uint initialEffectiveDelegated =
_effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(currentMonth);
uint[] memory initialSubtractions = new uint[](0);
if (currentMonth < _effectiveDelegatedToValidator[validatorId].lastChangedMonth) {
initialSubtractions = new uint[](
_effectiveDelegatedToValidator[validatorId].lastChangedMonth - currentMonth
);
for (uint i = 0; i < initialSubtractions.length; ++i) {
initialSubtractions[i] = _effectiveDelegatedToValidator[validatorId]
.subtractDiff[currentMonth + i + 1];
}
}
_effectiveDelegatedToValidator[validatorId].reduceSequence(coefficient, currentMonth);
_putToSlashingLog(_slashesOfValidator[validatorId], coefficient, currentMonth);
_slashes.push(SlashingEvent({reducingCoefficient: coefficient, validatorId: validatorId, month: currentMonth}));
IBountyV2 bounty = _getBounty();
bounty.handleDelegationRemoving(
initialEffectiveDelegated -
_effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(currentMonth),
currentMonth
);
for (uint i = 0; i < initialSubtractions.length; ++i) {
bounty.handleDelegationAdd(
initialSubtractions[i] -
_effectiveDelegatedToValidator[validatorId].subtractDiff[currentMonth + i + 1],
currentMonth + i + 1
);
}
emit Confiscated(validatorId, amount);
}
/**
* @dev Allows Distributor contract to return and update the effective
* amount delegated (minus slash) to a validator for a given month.
*/
function getAndUpdateEffectiveDelegatedToValidator(uint validatorId, uint month)
external
override
allowTwo("Bounty", "Distributor")
returns (uint)
{
return _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(month);
}
/**
* @dev Return and update the amount delegated to a validator for the
* current month.
*/
function getAndUpdateDelegatedByHolderToValidatorNow(address holder, uint validatorId)
external
override
returns (uint)
{
return _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, _getCurrentMonth());
}
function getEffectiveDelegatedValuesByValidator(uint validatorId) external view override returns (uint[] memory) {
return _effectiveDelegatedToValidator[validatorId].getValuesInSequence();
}
function getEffectiveDelegatedToValidator(uint validatorId, uint month) external view override returns (uint) {
return _effectiveDelegatedToValidator[validatorId].getValueInSequence(month);
}
function getDelegatedToValidator(uint validatorId, uint month) external view override returns (uint) {
return _delegatedToValidator[validatorId].getValue(month);
}
/**
* @dev Return Delegation struct.
*/
function getDelegation(uint delegationId)
external
view
override
checkDelegationExists(delegationId)
returns (Delegation memory)
{
return delegations[delegationId];
}
/**
* @dev Returns the first delegation month.
*/
function getFirstDelegationMonth(address holder, uint validatorId) external view override returns(uint) {
return _firstDelegationMonth[holder].byValidator[validatorId];
}
/**
* @dev Returns a validator's total number of delegations.
*/
function getDelegationsByValidatorLength(uint validatorId) external view override returns (uint) {
return delegationsByValidator[validatorId].length;
}
/**
* @dev Returns a holder's total number of delegations.
*/
function getDelegationsByHolderLength(address holder) external view override returns (uint) {
return delegationsByHolder[holder].length;
}
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
}
/**
* @dev Process slashes up to the given limit.
*/
function processSlashes(address holder, uint limit) public override {
_sendSlashingSignals(_processSlashesWithoutSignals(holder, limit));
emit SlashesProcessed(holder, limit);
}
/**
* @dev Process all slashes.
*/
function processAllSlashes(address holder) public override {
processSlashes(holder, 0);
}
/**
* @dev Returns the token state of a given delegation.
*/
function getState(uint delegationId)
public
view
override
checkDelegationExists(delegationId)
returns (State state)
{
if (delegations[delegationId].started == 0) {
if (delegations[delegationId].finished == 0) {
if (_getCurrentMonth() == _getTimeHelpers().timestampToMonth(delegations[delegationId].created)) {
return State.PROPOSED;
} else {
return State.REJECTED;
}
} else {
return State.CANCELED;
}
} else {
if (_getCurrentMonth() < delegations[delegationId].started) {
return State.ACCEPTED;
} else {
if (delegations[delegationId].finished == 0) {
return State.DELEGATED;
} else {
if (_getCurrentMonth() < delegations[delegationId].finished) {
return State.UNDELEGATION_REQUESTED;
} else {
return State.COMPLETED;
}
}
}
}
}
/**
* @dev Returns the amount of tokens in PENDING delegation state.
*/
function getLockedInPendingDelegations(address holder) public view override returns (uint) {
uint currentMonth = _getCurrentMonth();
if (_lockedInPendingDelegations[holder].month < currentMonth) {
return 0;
} else {
return _lockedInPendingDelegations[holder].amount;
}
}
/**
* @dev Checks whether there are any unprocessed slashes.
*/
function hasUnprocessedSlashes(address holder) public view override returns (bool) {
return _everDelegated(holder) && _firstUnprocessedSlashByHolder[holder] < _slashes.length;
}
// private
/**
* @dev Allows Nodes contract to get and update the amount delegated
* to validator for a given month.
*/
function _getAndUpdateDelegatedToValidator(uint validatorId, uint month)
private returns (uint)
{
return _delegatedToValidator[validatorId].getAndUpdateValue(month);
}
/**
* @dev Adds a new delegation proposal.
*/
function _addDelegation(
address holder,
uint validatorId,
uint amount,
uint delegationPeriod,
string memory info
)
private
returns (uint delegationId)
{
delegationId = delegations.length;
delegations.push(Delegation(
holder,
validatorId,
amount,
delegationPeriod,
block.timestamp,
0,
0,
info
));
delegationsByValidator[validatorId].push(delegationId);
delegationsByHolder[holder].push(delegationId);
_addToLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount);
}
function _addToDelegatedToValidator(uint validatorId, uint amount, uint month) private {
_delegatedToValidator[validatorId].addToValue(amount, month);
}
function _addToEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private {
_effectiveDelegatedToValidator[validatorId].addToSequence(effectiveAmount, month);
}
function _addToDelegatedByHolder(address holder, uint amount, uint month) private {
_delegatedByHolder[holder].addToValue(amount, month);
}
function _addToDelegatedByHolderToValidator(
address holder, uint validatorId, uint amount, uint month) private
{
_delegatedByHolderToValidator[holder][validatorId].addToValue(amount, month);
}
function _addValidatorToValidatorsPerDelegators(address holder, uint validatorId) private {
if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0) {
_numberOfValidatorsPerDelegator[holder].number += 1;
}
_numberOfValidatorsPerDelegator[holder].delegated[validatorId] += 1;
}
function _removeFromDelegatedByHolder(address holder, uint amount, uint month) private {
_delegatedByHolder[holder].subtractFromValue(amount, month);
}
function _removeFromDelegatedByHolderToValidator(
address holder, uint validatorId, uint amount, uint month) private
{
_delegatedByHolderToValidator[holder][validatorId].subtractFromValue(amount, month);
}
function _removeValidatorFromValidatorsPerDelegators(address holder, uint validatorId) private {
if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 1) {
_numberOfValidatorsPerDelegator[holder].number -= 1;
}
_numberOfValidatorsPerDelegator[holder].delegated[validatorId] -= 1;
}
function _addToEffectiveDelegatedByHolderToValidator(
address holder,
uint validatorId,
uint effectiveAmount,
uint month)
private
{
_effectiveDelegatedByHolderToValidator[holder][validatorId].addToSequence(effectiveAmount, month);
}
function _removeFromEffectiveDelegatedByHolderToValidator(
address holder,
uint validatorId,
uint effectiveAmount,
uint month)
private
{
_effectiveDelegatedByHolderToValidator[holder][validatorId].subtractFromSequence(effectiveAmount, month);
}
function _getAndUpdateDelegatedByHolder(address holder) private returns (uint) {
uint currentMonth = _getCurrentMonth();
processAllSlashes(holder);
return _delegatedByHolder[holder].getAndUpdateValue(currentMonth);
}
function _getAndUpdateDelegatedByHolderToValidator(
address holder,
uint validatorId,
uint month)
private returns (uint)
{
return _delegatedByHolderToValidator[holder][validatorId].getAndUpdateValue(month);
}
function _addToLockedInPendingDelegations(address holder, uint amount) private {
uint currentMonth = _getCurrentMonth();
if (_lockedInPendingDelegations[holder].month < currentMonth) {
_lockedInPendingDelegations[holder].amount = amount;
_lockedInPendingDelegations[holder].month = currentMonth;
} else {
assert(_lockedInPendingDelegations[holder].month == currentMonth);
_lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount + amount;
}
}
function _subtractFromLockedInPendingDelegations(address holder, uint amount) private {
uint currentMonth = _getCurrentMonth();
assert(_lockedInPendingDelegations[holder].month == currentMonth);
_lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount - amount;
}
/**
* @dev See {ILocker-getAndUpdateLockedAmount}.
*/
function _getAndUpdateLockedAmount(address wallet) private returns (uint) {
return _getAndUpdateDelegatedByHolder(wallet) + getLockedInPendingDelegations(wallet);
}
function _updateFirstDelegationMonth(address holder, uint validatorId, uint month) private {
if (_firstDelegationMonth[holder].value == 0) {
_firstDelegationMonth[holder].value = month;
_firstUnprocessedSlashByHolder[holder] = _slashes.length;
}
if (_firstDelegationMonth[holder].byValidator[validatorId] == 0) {
_firstDelegationMonth[holder].byValidator[validatorId] = month;
}
}
function _removeFromDelegatedToValidator(uint validatorId, uint amount, uint month) private {
_delegatedToValidator[validatorId].subtractFromValue(amount, month);
}
function _removeFromEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private {
_effectiveDelegatedToValidator[validatorId].subtractFromSequence(effectiveAmount, month);
}
function _putToSlashingLog(
SlashingLog storage log,
FractionUtils.Fraction memory coefficient,
uint month)
private
{
if (log.firstMonth == 0) {
log.firstMonth = month;
log.lastMonth = month;
log.slashes[month].reducingCoefficient = coefficient;
log.slashes[month].nextMonth = 0;
} else {
require(log.lastMonth <= month, "Cannot put slashing event in the past");
if (log.lastMonth == month) {
log.slashes[month].reducingCoefficient =
log.slashes[month].reducingCoefficient.multiplyFraction(coefficient);
} else {
log.slashes[month].reducingCoefficient = coefficient;
log.slashes[month].nextMonth = 0;
log.slashes[log.lastMonth].nextMonth = month;
log.lastMonth = month;
}
}
}
function _processSlashesWithoutSignals(address holder, uint limit)
private returns (SlashingSignal[] memory slashingSignals)
{
if (hasUnprocessedSlashes(holder)) {
uint index = _firstUnprocessedSlashByHolder[holder];
uint end = _slashes.length;
if (limit > 0 && (index + limit) < end) {
end = index + limit;
}
slashingSignals = new SlashingSignal[](end - index);
uint begin = index;
for (; index < end; ++index) {
uint validatorId = _slashes[index].validatorId;
uint month = _slashes[index].month;
uint oldValue = _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month);
if (oldValue.muchGreater(0)) {
_delegatedByHolderToValidator[holder][validatorId].reduceValueByCoefficientAndUpdateSum(
_delegatedByHolder[holder],
_slashes[index].reducingCoefficient,
month);
_effectiveDelegatedByHolderToValidator[holder][validatorId].reduceSequence(
_slashes[index].reducingCoefficient,
month);
slashingSignals[index - begin].holder = holder;
slashingSignals[index - begin].penalty
= oldValue.boundedSub(_getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month));
}
}
_firstUnprocessedSlashByHolder[holder] = end;
}
}
function _processAllSlashesWithoutSignals(address holder)
private returns (SlashingSignal[] memory slashingSignals)
{
return _processSlashesWithoutSignals(holder, 0);
}
function _sendSlashingSignals(SlashingSignal[] memory slashingSignals) private {
IPunisher punisher = IPunisher(contractManager.getPunisher());
address previousHolder = address(0);
uint accumulatedPenalty = 0;
for (uint i = 0; i < slashingSignals.length; ++i) {
if (slashingSignals[i].holder != previousHolder) {
if (accumulatedPenalty > 0) {
punisher.handleSlash(previousHolder, accumulatedPenalty);
}
previousHolder = slashingSignals[i].holder;
accumulatedPenalty = slashingSignals[i].penalty;
} else {
accumulatedPenalty = accumulatedPenalty + slashingSignals[i].penalty;
}
}
if (accumulatedPenalty > 0) {
punisher.handleSlash(previousHolder, accumulatedPenalty);
}
}
function _addToAllStatistics(uint delegationId) private {
uint currentMonth = _getCurrentMonth();
delegations[delegationId].started = currentMonth + 1;
if (_slashesOfValidator[delegations[delegationId].validatorId].lastMonth > 0) {
_delegationExtras[delegationId].lastSlashingMonthBeforeDelegation =
_slashesOfValidator[delegations[delegationId].validatorId].lastMonth;
}
_addToDelegatedToValidator(
delegations[delegationId].validatorId,
delegations[delegationId].amount,
currentMonth + 1);
_addToDelegatedByHolder(
delegations[delegationId].holder,
delegations[delegationId].amount,
currentMonth + 1);
_addToDelegatedByHolderToValidator(
delegations[delegationId].holder,
delegations[delegationId].validatorId,
delegations[delegationId].amount,
currentMonth + 1);
_updateFirstDelegationMonth(
delegations[delegationId].holder,
delegations[delegationId].validatorId,
currentMonth + 1);
uint effectiveAmount = delegations[delegationId].amount *
_getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod);
_addToEffectiveDelegatedToValidator(
delegations[delegationId].validatorId,
effectiveAmount,
currentMonth + 1);
_addToEffectiveDelegatedByHolderToValidator(
delegations[delegationId].holder,
delegations[delegationId].validatorId,
effectiveAmount,
currentMonth + 1);
_addValidatorToValidatorsPerDelegators(
delegations[delegationId].holder,
delegations[delegationId].validatorId
);
}
function _subtractFromAllStatistics(uint delegationId) private {
uint amountAfterSlashing = _calculateDelegationAmountAfterSlashing(delegationId);
_removeFromDelegatedToValidator(
delegations[delegationId].validatorId,
amountAfterSlashing,
delegations[delegationId].finished);
_removeFromDelegatedByHolder(
delegations[delegationId].holder,
amountAfterSlashing,
delegations[delegationId].finished);
_removeFromDelegatedByHolderToValidator(
delegations[delegationId].holder,
delegations[delegationId].validatorId,
amountAfterSlashing,
delegations[delegationId].finished);
uint effectiveAmount = amountAfterSlashing *
_getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod);
_removeFromEffectiveDelegatedToValidator(
delegations[delegationId].validatorId,
effectiveAmount,
delegations[delegationId].finished);
_removeFromEffectiveDelegatedByHolderToValidator(
delegations[delegationId].holder,
delegations[delegationId].validatorId,
effectiveAmount,
delegations[delegationId].finished);
_getBounty().handleDelegationRemoving(
effectiveAmount,
delegations[delegationId].finished);
}
function _accept(uint delegationId) private {
_checkIfDelegationIsAllowed(delegations[delegationId].holder, delegations[delegationId].validatorId);
State currentState = getState(delegationId);
if (currentState != State.PROPOSED) {
if (currentState == State.ACCEPTED ||
currentState == State.DELEGATED ||
currentState == State.UNDELEGATION_REQUESTED ||
currentState == State.COMPLETED)
{
revert("The delegation has been already accepted");
} else if (currentState == State.CANCELED) {
revert("The delegation has been cancelled by token holder");
} else if (currentState == State.REJECTED) {
revert("The delegation request is outdated");
}
}
require(currentState == State.PROPOSED, "Cannot set delegation state to accepted");
SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(delegations[delegationId].holder);
_addToAllStatistics(delegationId);
uint amount = delegations[delegationId].amount;
uint effectiveAmount = amount *
_getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod);
_getBounty().handleDelegationAdd(
effectiveAmount,
delegations[delegationId].started
);
_sendSlashingSignals(slashingSignals);
emit DelegationAccepted(delegationId);
}
function _getCurrentMonth() private view returns (uint) {
return _getTimeHelpers().getCurrentMonth();
}
/**
* @dev Checks whether the holder has performed a delegation.
*/
function _everDelegated(address holder) private view returns (bool) {
return _firstDelegationMonth[holder].value > 0;
}
/**
* @dev Returns the month when a delegation ends.
*/
function _calculateDelegationEndMonth(uint delegationId) private view returns (uint) {
uint currentMonth = _getCurrentMonth();
uint started = delegations[delegationId].started;
if (currentMonth < started) {
return started + delegations[delegationId].delegationPeriod;
} else {
uint completedPeriods = (currentMonth - started) / delegations[delegationId].delegationPeriod;
return started + (completedPeriods + 1) * delegations[delegationId].delegationPeriod;
}
}
/**
* @dev Returns the delegated amount after a slashing event.
*/
function _calculateDelegationAmountAfterSlashing(uint delegationId) private view returns (uint) {
uint startMonth = _delegationExtras[delegationId].lastSlashingMonthBeforeDelegation;
uint validatorId = delegations[delegationId].validatorId;
uint amount = delegations[delegationId].amount;
if (startMonth == 0) {
startMonth = _slashesOfValidator[validatorId].firstMonth;
if (startMonth == 0) {
return amount;
}
}
for (uint i = startMonth;
i > 0 && i < delegations[delegationId].finished;
i = _slashesOfValidator[validatorId].slashes[i].nextMonth) {
if (i >= delegations[delegationId].started) {
amount = amount
* _slashesOfValidator[validatorId].slashes[i].reducingCoefficient.numerator
/ _slashesOfValidator[validatorId].slashes[i].reducingCoefficient.denominator;
}
}
return amount;
}
/**
* @dev Checks whether delegation to a validator is allowed.
*
* Requirements:
*
* - Delegator must not have reached the validator limit.
* - Delegation must be made in or after the first delegation month.
*/
function _checkIfDelegationIsAllowed(address holder, uint validatorId) private view {
require(
_numberOfValidatorsPerDelegator[holder].delegated[validatorId] > 0 ||
_numberOfValidatorsPerDelegator[holder].number < _getConstantsHolder().limitValidatorsPerDelegator(),
"Limit of validators is reached"
);
}
function _getDelegationPeriodManager() private view returns (IDelegationPeriodManager) {
return IDelegationPeriodManager(contractManager.getDelegationPeriodManager());
}
function _getBounty() private view returns (IBountyV2) {
return IBountyV2(contractManager.getBounty());
}
function _getValidatorService() private view returns (IValidatorService) {
return IValidatorService(contractManager.getValidatorService());
}
function _getTimeHelpers() private view returns (ITimeHelpers) {
return ITimeHelpers(contractManager.getTimeHelpers());
}
function _getConstantsHolder() private view returns (IConstantsHolder) {
return IConstantsHolder(contractManager.getConstantsHolder());
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC777/IERC777.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC777Token standard as defined in the EIP.
*
* This contract uses the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let
* token holders and recipients react to token movements by using setting implementers
* for the associated interfaces in said registry. See {IERC1820Registry} and
* {ERC1820Implementer}.
*/
interface IERC777 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the smallest part of the token that is not divisible. This
* means all token operations (creation, movement and destruction) must have
* amounts that are a multiple of this number.
*
* For most token contracts, this value will equal 1.
*/
function granularity() external view returns (uint256);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by an account (`owner`).
*/
function balanceOf(address owner) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* If send or receive hooks are registered for the caller and `recipient`,
* the corresponding functions will be called with `data` and empty
* `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
*
* Emits a {Sent} event.
*
* Requirements
*
* - the caller must have at least `amount` tokens.
* - `recipient` cannot be the zero address.
* - if `recipient` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function send(
address recipient,
uint256 amount,
bytes calldata data
) external;
/**
* @dev Destroys `amount` tokens from the caller's account, reducing the
* total supply.
*
* If a send hook is registered for the caller, the corresponding function
* will be called with `data` and empty `operatorData`. See {IERC777Sender}.
*
* Emits a {Burned} event.
*
* Requirements
*
* - the caller must have at least `amount` tokens.
*/
function burn(uint256 amount, bytes calldata data) external;
/**
* @dev Returns true if an account is an operator of `tokenHolder`.
* Operators can send and burn tokens on behalf of their owners. All
* accounts are their own operator.
*
* See {operatorSend} and {operatorBurn}.
*/
function isOperatorFor(address operator, address tokenHolder) external view returns (bool);
/**
* @dev Make an account an operator of the caller.
*
* See {isOperatorFor}.
*
* Emits an {AuthorizedOperator} event.
*
* Requirements
*
* - `operator` cannot be calling address.
*/
function authorizeOperator(address operator) external;
/**
* @dev Revoke an account's operator status for the caller.
*
* See {isOperatorFor} and {defaultOperators}.
*
* Emits a {RevokedOperator} event.
*
* Requirements
*
* - `operator` cannot be calling address.
*/
function revokeOperator(address operator) external;
/**
* @dev Returns the list of default operators. These accounts are operators
* for all token holders, even if {authorizeOperator} was never called on
* them.
*
* This list is immutable, but individual holders may revoke these via
* {revokeOperator}, in which case {isOperatorFor} will return false.
*/
function defaultOperators() external view returns (address[] memory);
/**
* @dev Moves `amount` tokens from `sender` to `recipient`. The caller must
* be an operator of `sender`.
*
* If send or receive hooks are registered for `sender` and `recipient`,
* the corresponding functions will be called with `data` and
* `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
*
* Emits a {Sent} event.
*
* Requirements
*
* - `sender` cannot be the zero address.
* - `sender` must have at least `amount` tokens.
* - the caller must be an operator for `sender`.
* - `recipient` cannot be the zero address.
* - if `recipient` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function operatorSend(
address sender,
address recipient,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
/**
* @dev Destroys `amount` tokens from `account`, reducing the total supply.
* The caller must be an operator of `account`.
*
* If a send hook is registered for `account`, the corresponding function
* will be called with `data` and `operatorData`. See {IERC777Sender}.
*
* Emits a {Burned} event.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
* - the caller must be an operator for `account`.
*/
function operatorBurn(
address account,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
event Sent(
address indexed operator,
address indexed from,
address indexed to,
uint256 amount,
bytes data,
bytes operatorData
);
event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData);
event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData);
event AuthorizedOperator(address indexed operator, address indexed tokenHolder);
event RevokedOperator(address indexed operator, address indexed tokenHolder);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
IDelegationController.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface IDelegationController {
enum State {
PROPOSED,
ACCEPTED,
CANCELED,
REJECTED,
DELEGATED,
UNDELEGATION_REQUESTED,
COMPLETED
}
struct Delegation {
address holder; // address of token owner
uint validatorId;
uint amount;
uint delegationPeriod;
uint created; // time of delegation creation
uint started; // month when a delegation becomes active
uint finished; // first month after a delegation ends
string info;
}
/**
* @dev Emitted when validator was confiscated.
*/
event Confiscated(
uint indexed validatorId,
uint amount
);
/**
* @dev Emitted when validator was confiscated.
*/
event SlashesProcessed(
address indexed holder,
uint limit
);
/**
* @dev Emitted when a delegation is proposed to a validator.
*/
event DelegationProposed(
uint delegationId
);
/**
* @dev Emitted when a delegation is accepted by a validator.
*/
event DelegationAccepted(
uint delegationId
);
/**
* @dev Emitted when a delegation is cancelled by the delegator.
*/
event DelegationRequestCanceledByUser(
uint delegationId
);
/**
* @dev Emitted when a delegation is requested to undelegate.
*/
event UndelegationRequested(
uint delegationId
);
function getAndUpdateDelegatedToValidatorNow(uint validatorId) external returns (uint);
function getAndUpdateDelegatedAmount(address holder) external returns (uint);
function getAndUpdateEffectiveDelegatedByHolderToValidator(address holder, uint validatorId, uint month)
external
returns (uint effectiveDelegated);
function delegate(
uint validatorId,
uint amount,
uint delegationPeriod,
string calldata info
)
external;
function cancelPendingDelegation(uint delegationId) external;
function acceptPendingDelegation(uint delegationId) external;
function requestUndelegation(uint delegationId) external;
function confiscate(uint validatorId, uint amount) external;
function getAndUpdateEffectiveDelegatedToValidator(uint validatorId, uint month) external returns (uint);
function getAndUpdateDelegatedByHolderToValidatorNow(address holder, uint validatorId) external returns (uint);
function processSlashes(address holder, uint limit) external;
function processAllSlashes(address holder) external;
function getEffectiveDelegatedValuesByValidator(uint validatorId) external view returns (uint[] memory);
function getEffectiveDelegatedToValidator(uint validatorId, uint month) external view returns (uint);
function getDelegatedToValidator(uint validatorId, uint month) external view returns (uint);
function getDelegation(uint delegationId) external view returns (Delegation memory);
function getFirstDelegationMonth(address holder, uint validatorId) external view returns(uint);
function getDelegationsByValidatorLength(uint validatorId) external view returns (uint);
function getDelegationsByHolderLength(address holder) external view returns (uint);
function getState(uint delegationId) external view returns (State state);
function getLockedInPendingDelegations(address holder) external view returns (uint);
function hasUnprocessedSlashes(address holder) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
IDelegationPeriodManager.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface IDelegationPeriodManager {
/**
* @dev Emitted when a new delegation period is specified.
*/
event DelegationPeriodWasSet(
uint length,
uint stakeMultiplier
);
function setDelegationPeriod(uint monthsCount, uint stakeMultiplier) external;
function stakeMultipliers(uint monthsCount) external view returns (uint);
function isDelegationPeriodAllowed(uint monthsCount) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
IPunisher.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface IPunisher {
/**
* @dev Emitted upon slashing condition.
*/
event Slash(
uint validatorId,
uint amount
);
/**
* @dev Emitted upon forgive condition.
*/
event Forgive(
address wallet,
uint amount
);
function slash(uint validatorId, uint amount) external;
function forgive(address holder, uint amount) external;
function handleSlash(address holder, uint amount) external;
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ITokenState.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface ITokenState {
/**
* @dev Emitted when a contract is added to the locker.
*/
event LockerWasAdded(
string locker
);
/**
* @dev Emitted when a contract is removed from the locker.
*/
event LockerWasRemoved(
string locker
);
function removeLocker(string calldata locker) external;
function addLocker(string memory locker) external;
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
IValidatorService.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface IValidatorService {
struct Validator {
string name;
address validatorAddress;
address requestedAddress;
string description;
uint feeRate;
uint registrationTime;
uint minimumDelegationAmount;
bool acceptNewRequests;
}
/**
* @dev Emitted when a validator registers.
*/
event ValidatorRegistered(
uint validatorId
);
/**
* @dev Emitted when a validator address changes.
*/
event ValidatorAddressChanged(
uint validatorId,
address newAddress
);
/**
* @dev Emitted when a validator is enabled.
*/
event ValidatorWasEnabled(
uint validatorId
);
/**
* @dev Emitted when a validator is disabled.
*/
event ValidatorWasDisabled(
uint validatorId
);
/**
* @dev Emitted when a node address is linked to a validator.
*/
event NodeAddressWasAdded(
uint validatorId,
address nodeAddress
);
/**
* @dev Emitted when a node address is unlinked from a validator.
*/
event NodeAddressWasRemoved(
uint validatorId,
address nodeAddress
);
/**
* @dev Emitted when whitelist disabled.
*/
event WhitelistDisabled(bool status);
/**
* @dev Emitted when validator requested new address.
*/
event RequestNewAddress(uint indexed validatorId, address previousAddress, address newAddress);
/**
* @dev Emitted when validator set new minimum delegation amount.
*/
event SetMinimumDelegationAmount(uint indexed validatorId, uint previousMDA, uint newMDA);
/**
* @dev Emitted when validator set new name.
*/
event SetValidatorName(uint indexed validatorId, string previousName, string newName);
/**
* @dev Emitted when validator set new description.
*/
event SetValidatorDescription(uint indexed validatorId, string previousDescription, string newDescription);
/**
* @dev Emitted when validator start or stop accepting new delegation requests.
*/
event AcceptingNewRequests(uint indexed validatorId, bool status);
function registerValidator(
string calldata name,
string calldata description,
uint feeRate,
uint minimumDelegationAmount
)
external
returns (uint validatorId);
function enableValidator(uint validatorId) external;
function disableValidator(uint validatorId) external;
function disableWhitelist() external;
function requestForNewAddress(address newValidatorAddress) external;
function confirmNewAddress(uint validatorId) external;
function linkNodeAddress(address nodeAddress, bytes calldata sig) external;
function unlinkNodeAddress(address nodeAddress) external;
function setValidatorMDA(uint minimumDelegationAmount) external;
function setValidatorName(string calldata newName) external;
function setValidatorDescription(string calldata newDescription) external;
function startAcceptingNewRequests() external;
function stopAcceptingNewRequests() external;
function removeNodeAddress(uint validatorId, address nodeAddress) external;
function getAndUpdateBondAmount(uint validatorId) external returns (uint);
function getMyNodesAddresses() external view returns (address[] memory);
function getTrustedValidators() external view returns (uint[] memory);
function checkValidatorAddressToId(address validatorAddress, uint validatorId)
external
view
returns (bool);
function getValidatorIdByNodeAddress(address nodeAddress) external view returns (uint validatorId);
function checkValidatorCanReceiveDelegation(uint validatorId, uint amount) external view;
function getNodeAddresses(uint validatorId) external view returns (address[] memory);
function validatorExists(uint validatorId) external view returns (bool);
function validatorAddressExists(address validatorAddress) external view returns (bool);
function checkIfValidatorAddressExists(address validatorAddress) external view;
function getValidator(uint validatorId) external view returns (Validator memory);
function getValidatorId(address validatorAddress) external view returns (uint);
function isAcceptingNewRequests(uint validatorId) external view returns (bool);
function isAuthorizedValidator(uint validatorId) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ILocker.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
/**
* @dev Interface of the Locker functions.
*/
interface ILocker {
/**
* @dev Returns and updates the total amount of locked tokens of a given
* `holder`.
*/
function getAndUpdateLockedAmount(address wallet) external returns (uint);
/**
* @dev Returns and updates the total non-transferrable and un-delegatable
* amount of a given `holder`.
*/
function getAndUpdateForbiddenForDelegationAmount(address wallet) external returns (uint);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ITimeHelpers.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface ITimeHelpers {
function calculateProofOfUseLockEndTime(uint month, uint lockUpPeriodDays) external view returns (uint timestamp);
function getCurrentMonth() external view returns (uint);
function timestampToYear(uint timestamp) external view returns (uint);
function timestampToMonth(uint timestamp) external view returns (uint);
function monthToTimestamp(uint month) external view returns (uint timestamp);
function addDays(uint fromTimestamp, uint n) external pure returns (uint);
function addMonths(uint fromTimestamp, uint n) external pure returns (uint);
function addYears(uint fromTimestamp, uint n) external pure returns (uint);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
IBountyV2.sol - SKALE Manager Interfaces
Copyright (C) 2021-Present SKALE Labs
@author Artem Payvin
SKALE Manager Interfaces is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager Interfaces is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface IBountyV2 {
/**
* @dev Emitted when bounty reduction is turned on or turned off.
*/
event BountyReduction(bool status);
/**
* @dev Emitted when a node creation window was changed.
*/
event NodeCreationWindowWasChanged(
uint oldValue,
uint newValue
);
function calculateBounty(uint nodeIndex) external returns (uint);
function enableBountyReduction() external;
function disableBountyReduction() external;
function setNodeCreationWindowSeconds(uint window) external;
function handleDelegationAdd(uint amount, uint month) external;
function handleDelegationRemoving(uint amount, uint month) external;
function estimateBounty(uint nodeIndex) external view returns (uint);
function getNextRewardTimestamp(uint nodeIndex) external view returns (uint);
function getEffectiveDelegatedSum() external view returns (uint[] memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
INodes.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
import "./utils/IRandom.sol";
interface INodes {
// All Nodes states
enum NodeStatus {Active, Leaving, Left, In_Maintenance}
struct Node {
string name;
bytes4 ip;
bytes4 publicIP;
uint16 port;
bytes32[2] publicKey;
uint startBlock;
uint lastRewardDate;
uint finishTime;
NodeStatus status;
uint validatorId;
}
// struct to note which Nodes and which number of Nodes owned by user
struct CreatedNodes {
mapping (uint => bool) isNodeExist;
uint numberOfNodes;
}
struct SpaceManaging {
uint8 freeSpace;
uint indexInSpaceMap;
}
struct NodeCreationParams {
string name;
bytes4 ip;
bytes4 publicIp;
uint16 port;
bytes32[2] publicKey;
uint16 nonce;
string domainName;
}
/**
* @dev Emitted when a node is created.
*/
event NodeCreated(
uint nodeIndex,
address owner,
string name,
bytes4 ip,
bytes4 publicIP,
uint16 port,
uint16 nonce,
string domainName
);
/**
* @dev Emitted when a node completes a network exit.
*/
event ExitCompleted(
uint nodeIndex
);
/**
* @dev Emitted when a node begins to exit from the network.
*/
event ExitInitialized(
uint nodeIndex,
uint startLeavingPeriod
);
/**
* @dev Emitted when a node set to in compliant or compliant.
*/
event IncompliantNode(
uint indexed nodeIndex,
bool status
);
/**
* @dev Emitted when a node set to in maintenance or from in maintenance.
*/
event MaintenanceNode(
uint indexed nodeIndex,
bool status
);
/**
* @dev Emitted when a node status changed.
*/
event IPChanged(
uint indexed nodeIndex,
bytes4 previousIP,
bytes4 newIP
);
function removeSpaceFromNode(uint nodeIndex, uint8 space) external returns (bool);
function addSpaceToNode(uint nodeIndex, uint8 space) external;
function changeNodeLastRewardDate(uint nodeIndex) external;
function changeNodeFinishTime(uint nodeIndex, uint time) external;
function createNode(address from, NodeCreationParams calldata params) external;
function initExit(uint nodeIndex) external;
function completeExit(uint nodeIndex) external returns (bool);
function deleteNodeForValidator(uint validatorId, uint nodeIndex) external;
function checkPossibilityCreatingNode(address nodeAddress) external;
function checkPossibilityToMaintainNode(uint validatorId, uint nodeIndex) external returns (bool);
function setNodeInMaintenance(uint nodeIndex) external;
function removeNodeFromInMaintenance(uint nodeIndex) external;
function setNodeIncompliant(uint nodeIndex) external;
function setNodeCompliant(uint nodeIndex) external;
function setDomainName(uint nodeIndex, string memory domainName) external;
function makeNodeVisible(uint nodeIndex) external;
function makeNodeInvisible(uint nodeIndex) external;
function changeIP(uint nodeIndex, bytes4 newIP, bytes4 newPublicIP) external;
function numberOfActiveNodes() external view returns (uint);
function incompliant(uint nodeIndex) external view returns (bool);
function getRandomNodeWithFreeSpace(
uint8 freeSpace,
IRandom.RandomGenerator memory randomGenerator
)
external
view
returns (uint);
function isTimeForReward(uint nodeIndex) external view returns (bool);
function getNodeIP(uint nodeIndex) external view returns (bytes4);
function getNodeDomainName(uint nodeIndex) external view returns (string memory);
function getNodePort(uint nodeIndex) external view returns (uint16);
function getNodePublicKey(uint nodeIndex) external view returns (bytes32[2] memory);
function getNodeAddress(uint nodeIndex) external view returns (address);
function getNodeFinishTime(uint nodeIndex) external view returns (uint);
function isNodeLeft(uint nodeIndex) external view returns (bool);
function isNodeInMaintenance(uint nodeIndex) external view returns (bool);
function getNodeLastRewardDate(uint nodeIndex) external view returns (uint);
function getNodeNextRewardDate(uint nodeIndex) external view returns (uint);
function getNumberOfNodes() external view returns (uint);
function getNumberOnlineNodes() external view returns (uint);
function getActiveNodeIds() external view returns (uint[] memory activeNodeIds);
function getNodeStatus(uint nodeIndex) external view returns (NodeStatus);
function getValidatorNodeIndexes(uint validatorId) external view returns (uint[] memory);
function countNodesWithFreeSpace(uint8 freeSpace) external view returns (uint count);
function getValidatorId(uint nodeIndex) external view returns (uint);
function isNodeExist(address from, uint nodeIndex) external view returns (bool);
function isNodeActive(uint nodeIndex) external view returns (bool);
function isNodeLeaving(uint nodeIndex) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
IConstantsHolder.sol - SKALE Manager Interfaces
Copyright (C) 2021-Present SKALE Labs
@author Artem Payvin
SKALE Manager Interfaces is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager Interfaces is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface IConstantsHolder {
/**
* @dev Emitted when constants updated.
*/
event ConstantUpdated(
bytes32 indexed constantHash,
uint previousValue,
uint newValue
);
function setPeriods(uint32 newRewardPeriod, uint32 newDeltaPeriod) external;
function setCheckTime(uint newCheckTime) external;
function setLatency(uint32 newAllowableLatency) external;
function setMSR(uint newMSR) external;
function setLaunchTimestamp(uint timestamp) external;
function setRotationDelay(uint newDelay) external;
function setProofOfUseLockUpPeriod(uint periodDays) external;
function setProofOfUseDelegationPercentage(uint percentage) external;
function setLimitValidatorsPerDelegator(uint newLimit) external;
function setSchainCreationTimeStamp(uint timestamp) external;
function setMinimalSchainLifetime(uint lifetime) external;
function setComplaintTimeLimit(uint timeLimit) external;
function msr() external view returns (uint);
function launchTimestamp() external view returns (uint);
function rotationDelay() external view returns (uint);
function limitValidatorsPerDelegator() external view returns (uint);
function schainCreationTimeStamp() external view returns (uint);
function minimalSchainLifetime() external view returns (uint);
function complaintTimeLimit() external view returns (uint);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Permissions.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.8.11;
import "@skalenetwork/skale-manager-interfaces/IContractManager.sol";
import "@skalenetwork/skale-manager-interfaces/IPermissions.sol";
import "./thirdparty/openzeppelin/AccessControlUpgradeableLegacy.sol";
/**
* @title Permissions
* @dev Contract is connected module for Upgradeable approach, knows ContractManager
*/
contract Permissions is AccessControlUpgradeableLegacy, IPermissions {
using AddressUpgradeable for address;
IContractManager public contractManager;
/**
* @dev Modifier to make a function callable only when caller is the Owner.
*
* Requirements:
*
* - The caller must be the owner.
*/
modifier onlyOwner() {
require(_isOwner(), "Caller is not the owner");
_;
}
/**
* @dev Modifier to make a function callable only when caller is an Admin.
*
* Requirements:
*
* - The caller must be an admin.
*/
modifier onlyAdmin() {
require(_isAdmin(msg.sender), "Caller is not an admin");
_;
}
/**
* @dev Modifier to make a function callable only when caller is the Owner
* or `contractName` contract.
*
* Requirements:
*
* - The caller must be the owner or `contractName`.
*/
modifier allow(string memory contractName) {
require(
contractManager.getContract(contractName) == msg.sender || _isOwner(),
"Message sender is invalid");
_;
}
/**
* @dev Modifier to make a function callable only when caller is the Owner
* or `contractName1` or `contractName2` contract.
*
* Requirements:
*
* - The caller must be the owner, `contractName1`, or `contractName2`.
*/
modifier allowTwo(string memory contractName1, string memory contractName2) {
require(
contractManager.getContract(contractName1) == msg.sender ||
contractManager.getContract(contractName2) == msg.sender ||
_isOwner(),
"Message sender is invalid");
_;
}
/**
* @dev Modifier to make a function callable only when caller is the Owner
* or `contractName1`, `contractName2`, or `contractName3` contract.
*
* Requirements:
*
* - The caller must be the owner, `contractName1`, `contractName2`, or
* `contractName3`.
*/
modifier allowThree(string memory contractName1, string memory contractName2, string memory contractName3) {
require(
contractManager.getContract(contractName1) == msg.sender ||
contractManager.getContract(contractName2) == msg.sender ||
contractManager.getContract(contractName3) == msg.sender ||
_isOwner(),
"Message sender is invalid");
_;
}
function initialize(address contractManagerAddress) public virtual override initializer {
AccessControlUpgradeableLegacy.__AccessControl_init();
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setContractManager(contractManagerAddress);
}
function _isOwner() internal view returns (bool) {
return hasRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
function _isAdmin(address account) internal view returns (bool) {
address skaleManagerAddress = contractManager.contracts(keccak256(abi.encodePacked("SkaleManager")));
if (skaleManagerAddress != address(0)) {
AccessControlUpgradeableLegacy skaleManager = AccessControlUpgradeableLegacy(skaleManagerAddress);
return skaleManager.hasRole(keccak256("ADMIN_ROLE"), account) || _isOwner();
} else {
return _isOwner();
}
}
function _setContractManager(address contractManagerAddress) private {
require(contractManagerAddress != address(0), "ContractManager address is not set");
require(contractManagerAddress.isContract(), "Address is not contract");
contractManager = IContractManager(contractManagerAddress);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
FractionUtils.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.8.11;
library FractionUtils {
struct Fraction {
uint numerator;
uint denominator;
}
function createFraction(uint numerator, uint denominator) internal pure returns (Fraction memory) {
require(denominator > 0, "Division by zero");
Fraction memory fraction = Fraction({numerator: numerator, denominator: denominator});
reduceFraction(fraction);
return fraction;
}
function createFraction(uint value) internal pure returns (Fraction memory) {
return createFraction(value, 1);
}
function reduceFraction(Fraction memory fraction) internal pure {
uint _gcd = gcd(fraction.numerator, fraction.denominator);
fraction.numerator = fraction.numerator / _gcd;
fraction.denominator = fraction.denominator / _gcd;
}
// numerator - is limited by 7*10^27, we could multiply it numerator * numerator - it would less than 2^256-1
function multiplyFraction(Fraction memory a, Fraction memory b) internal pure returns (Fraction memory) {
return createFraction(a.numerator * b.numerator, a.denominator * b.denominator);
}
function gcd(uint a, uint b) internal pure returns (uint) {
uint _a = a;
uint _b = b;
if (_b > _a) {
(_a, _b) = swap(_a, _b);
}
while (_b > 0) {
_a = _a % _b;
(_a, _b) = swap (_a, _b);
}
return _a;
}
function swap(uint a, uint b) internal pure returns (uint, uint) {
return (b, a);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
MathUtils.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.8.11;
library MathUtils {
uint constant private _EPS = 1e6;
event UnderflowError(
uint a,
uint b
);
function boundedSub(uint256 a, uint256 b) internal returns (uint256) {
if (a >= b) {
return a - b;
} else {
emit UnderflowError(a, b);
return 0;
}
}
function boundedSubWithoutEvent(uint256 a, uint256 b) internal pure returns (uint256) {
if (a >= b) {
return a - b;
} else {
return 0;
}
}
function muchGreater(uint256 a, uint256 b) internal pure returns (bool) {
assert(type(uint).max - _EPS > b);
return a > b + _EPS;
}
function approximatelyEqual(uint256 a, uint256 b) internal pure returns (bool) {
if (a > b) {
return a - b < _EPS;
} else {
return b - a < _EPS;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
PartialDifferences.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.8.11;
import "../utils/MathUtils.sol";
import "../utils/FractionUtils.sol";
/**
* @title Partial Differences Library
* @dev This library contains functions to manage Partial Differences data
* structure. Partial Differences is an array of value differences over time.
*
* For example: assuming an array [3, 6, 3, 1, 2], partial differences can
* represent this array as [_, 3, -3, -2, 1].
*
* This data structure allows adding values on an open interval with O(1)
* complexity.
*
* For example: add +5 to [3, 6, 3, 1, 2] starting from the second element (3),
* instead of performing [3, 6, 3+5, 1+5, 2+5] partial differences allows
* performing [_, 3, -3+5, -2, 1]. The original array can be restored by
* adding values from partial differences.
*/
library PartialDifferences {
using MathUtils for uint;
struct Sequence {
// month => diff
mapping (uint => uint) addDiff;
// month => diff
mapping (uint => uint) subtractDiff;
// month => value
mapping (uint => uint) value;
uint firstUnprocessedMonth;
uint lastChangedMonth;
}
struct Value {
// month => diff
mapping (uint => uint) addDiff;
// month => diff
mapping (uint => uint) subtractDiff;
uint value;
uint firstUnprocessedMonth;
uint lastChangedMonth;
}
// functions for sequence
function addToSequence(Sequence storage sequence, uint diff, uint month) internal {
require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past");
if (sequence.firstUnprocessedMonth == 0) {
sequence.firstUnprocessedMonth = month;
}
sequence.addDiff[month] = sequence.addDiff[month] + diff;
if (sequence.lastChangedMonth != month) {
sequence.lastChangedMonth = month;
}
}
function subtractFromSequence(Sequence storage sequence, uint diff, uint month) internal {
require(sequence.firstUnprocessedMonth <= month, "Cannot subtract from the past");
if (sequence.firstUnprocessedMonth == 0) {
sequence.firstUnprocessedMonth = month;
}
sequence.subtractDiff[month] = sequence.subtractDiff[month] + diff;
if (sequence.lastChangedMonth != month) {
sequence.lastChangedMonth = month;
}
}
function getAndUpdateValueInSequence(Sequence storage sequence, uint month) internal returns (uint) {
if (sequence.firstUnprocessedMonth == 0) {
return 0;
}
if (sequence.firstUnprocessedMonth <= month) {
for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) {
uint nextValue = (sequence.value[i - 1] + sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]);
if (sequence.value[i] != nextValue) {
sequence.value[i] = nextValue;
}
if (sequence.addDiff[i] > 0) {
delete sequence.addDiff[i];
}
if (sequence.subtractDiff[i] > 0) {
delete sequence.subtractDiff[i];
}
}
sequence.firstUnprocessedMonth = month + 1;
}
return sequence.value[month];
}
function reduceSequence(
Sequence storage sequence,
FractionUtils.Fraction memory reducingCoefficient,
uint month) internal
{
require(month + 1 >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past");
require(
reducingCoefficient.numerator <= reducingCoefficient.denominator,
"Increasing of values is not implemented");
if (sequence.firstUnprocessedMonth == 0) {
return;
}
uint value = getAndUpdateValueInSequence(sequence, month);
if (value.approximatelyEqual(0)) {
return;
}
sequence.value[month] = sequence.value[month]
* reducingCoefficient.numerator
/ reducingCoefficient.denominator;
for (uint i = month + 1; i <= sequence.lastChangedMonth; ++i) {
sequence.subtractDiff[i] = sequence.subtractDiff[i]
* reducingCoefficient.numerator
/ reducingCoefficient.denominator;
}
}
// functions for value
function addToValue(Value storage sequence, uint diff, uint month) internal {
require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past");
if (sequence.firstUnprocessedMonth == 0) {
sequence.firstUnprocessedMonth = month;
sequence.lastChangedMonth = month;
}
if (month > sequence.lastChangedMonth) {
sequence.lastChangedMonth = month;
}
if (month >= sequence.firstUnprocessedMonth) {
sequence.addDiff[month] = sequence.addDiff[month] + diff;
} else {
sequence.value = sequence.value + diff;
}
}
function subtractFromValue(Value storage sequence, uint diff, uint month) internal {
require(sequence.firstUnprocessedMonth <= month + 1, "Cannot subtract from the past");
if (sequence.firstUnprocessedMonth == 0) {
sequence.firstUnprocessedMonth = month;
sequence.lastChangedMonth = month;
}
if (month > sequence.lastChangedMonth) {
sequence.lastChangedMonth = month;
}
if (month >= sequence.firstUnprocessedMonth) {
sequence.subtractDiff[month] = sequence.subtractDiff[month] + diff;
} else {
sequence.value = sequence.value.boundedSub(diff);
}
}
function getAndUpdateValue(Value storage sequence, uint month) internal returns (uint) {
require(
month + 1 >= sequence.firstUnprocessedMonth,
"Cannot calculate value in the past");
if (sequence.firstUnprocessedMonth == 0) {
return 0;
}
if (sequence.firstUnprocessedMonth <= month) {
uint value = sequence.value;
for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) {
value = (value + sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]);
if (sequence.addDiff[i] > 0) {
delete sequence.addDiff[i];
}
if (sequence.subtractDiff[i] > 0) {
delete sequence.subtractDiff[i];
}
}
if (sequence.value != value) {
sequence.value = value;
}
sequence.firstUnprocessedMonth = month + 1;
}
return sequence.value;
}
function reduceValue(
Value storage sequence,
uint amount,
uint month)
internal returns (FractionUtils.Fraction memory)
{
require(month + 1 >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past");
if (sequence.firstUnprocessedMonth == 0) {
return FractionUtils.createFraction(0);
}
uint value = getAndUpdateValue(sequence, month);
if (value.approximatelyEqual(0)) {
return FractionUtils.createFraction(0);
}
uint _amount = amount;
if (value < amount) {
_amount = value;
}
FractionUtils.Fraction memory reducingCoefficient =
FractionUtils.createFraction(value.boundedSub(_amount), value);
reduceValueByCoefficient(sequence, reducingCoefficient, month);
return reducingCoefficient;
}
function reduceValueByCoefficient(
Value storage sequence,
FractionUtils.Fraction memory reducingCoefficient,
uint month)
internal
{
reduceValueByCoefficientAndUpdateSumIfNeeded(
sequence,
sequence,
reducingCoefficient,
month,
false);
}
function reduceValueByCoefficientAndUpdateSum(
Value storage sequence,
Value storage sumSequence,
FractionUtils.Fraction memory reducingCoefficient,
uint month) internal
{
reduceValueByCoefficientAndUpdateSumIfNeeded(
sequence,
sumSequence,
reducingCoefficient,
month,
true);
}
function reduceValueByCoefficientAndUpdateSumIfNeeded(
Value storage sequence,
Value storage sumSequence,
FractionUtils.Fraction memory reducingCoefficient,
uint month,
bool hasSumSequence) internal
{
require(month + 1 >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past");
if (hasSumSequence) {
require(month + 1 >= sumSequence.firstUnprocessedMonth, "Cannot reduce value in the past");
}
require(
reducingCoefficient.numerator <= reducingCoefficient.denominator,
"Increasing of values is not implemented");
if (sequence.firstUnprocessedMonth == 0) {
return;
}
uint value = getAndUpdateValue(sequence, month);
if (value.approximatelyEqual(0)) {
return;
}
uint newValue = sequence.value * reducingCoefficient.numerator / reducingCoefficient.denominator;
if (hasSumSequence) {
subtractFromValue(sumSequence, sequence.value.boundedSub(newValue), month);
}
sequence.value = newValue;
for (uint i = month + 1; i <= sequence.lastChangedMonth; ++i) {
uint newDiff = sequence.subtractDiff[i]
* reducingCoefficient.numerator
/ reducingCoefficient.denominator;
if (hasSumSequence) {
sumSequence.subtractDiff[i] = sumSequence.subtractDiff[i]
.boundedSub(sequence.subtractDiff[i].boundedSub(newDiff));
}
sequence.subtractDiff[i] = newDiff;
}
}
function getValueInSequence(Sequence storage sequence, uint month) internal view returns (uint) {
if (sequence.firstUnprocessedMonth == 0) {
return 0;
}
if (sequence.firstUnprocessedMonth <= month) {
uint value = sequence.value[sequence.firstUnprocessedMonth - 1];
for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) {
value = value + sequence.addDiff[i] - sequence.subtractDiff[i];
}
return value;
} else {
return sequence.value[month];
}
}
function getValuesInSequence(Sequence storage sequence) internal view returns (uint[] memory values) {
if (sequence.firstUnprocessedMonth == 0) {
return values;
}
uint begin = sequence.firstUnprocessedMonth - 1;
uint end = sequence.lastChangedMonth + 1;
if (end <= begin) {
end = begin + 1;
}
values = new uint[](end - begin);
values[0] = sequence.value[sequence.firstUnprocessedMonth - 1];
for (uint i = 0; i + 1 < values.length; ++i) {
uint month = sequence.firstUnprocessedMonth + i;
values[i + 1] = values[i] + sequence.addDiff[month] - sequence.subtractDiff[month];
}
}
function getValue(Value storage sequence, uint month) internal view returns (uint) {
require(
month + 1 >= sequence.firstUnprocessedMonth,
"Cannot calculate value in the past");
if (sequence.firstUnprocessedMonth == 0) {
return 0;
}
if (sequence.firstUnprocessedMonth <= month) {
uint value = sequence.value;
for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) {
value = value + sequence.addDiff[i] - sequence.subtractDiff[i];
}
return value;
} else {
return sequence.value;
}
}
function getValues(Value storage sequence) internal view returns (uint[] memory values) {
if (sequence.firstUnprocessedMonth == 0) {
return values;
}
uint begin = sequence.firstUnprocessedMonth - 1;
uint end = sequence.lastChangedMonth + 1;
if (end <= begin) {
end = begin + 1;
}
values = new uint[](end - begin);
values[0] = sequence.value;
for (uint i = 0; i + 1 < values.length; ++i) {
uint month = sequence.firstUnprocessedMonth + i;
values[i + 1] = values[i] + sequence.addDiff[month] - sequence.subtractDiff[month];
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
IRandom.sol - SKALE Manager Interfaces
Copyright (C) 2022-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager Interfaces is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager Interfaces is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface IRandom {
struct RandomGenerator {
uint seed;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
IContractManager.sol - SKALE Manager Interfaces
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaeiv
SKALE Manager Interfaces is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager Interfaces is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface IContractManager {
/**
* @dev Emitted when contract is upgraded.
*/
event ContractUpgraded(string contractsName, address contractsAddress);
function initialize() external;
function setContractsAddress(string calldata contractsName, address newContractsAddress) external;
function contracts(bytes32 nameHash) external view returns (address);
function getDelegationPeriodManager() external view returns (address);
function getBounty() external view returns (address);
function getValidatorService() external view returns (address);
function getTimeHelpers() external view returns (address);
function getConstantsHolder() external view returns (address);
function getSkaleToken() external view returns (address);
function getTokenState() external view returns (address);
function getPunisher() external view returns (address);
function getContract(string calldata name) external view returns (address);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
IPermissions.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface IPermissions {
function initialize(address contractManagerAddress) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import "@skalenetwork/skale-manager-interfaces/thirdparty/openzeppelin/IAccessControlUpgradeableLegacy.sol";
import "./InitializableWithGap.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, _msgSender()));
* ...
* }
* ```
*
* 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}.
*/
abstract contract AccessControlUpgradeableLegacy is InitializableWithGap, ContextUpgradeable, IAccessControlUpgradeableLegacy {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
struct RoleData {
EnumerableSetUpgradeable.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override 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 override 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 override 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 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 {
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 override {
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 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.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
_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());
}
}
uint256[49] 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/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: AGPL-3.0-only
/*
IAccessControlUpgradeableLegacy.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface IAccessControlUpgradeableLegacy {
/**
* @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);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleMemberCount(bytes32 role) external view returns (uint256);
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.7;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
contract InitializableWithGap is Initializable {
uint256[50] private ______gap;
}
// 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/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);
}
}
}
}
|
* @dev Process slashes up to the given limit./
|
function processSlashes(address holder, uint limit) public override {
_sendSlashingSignals(_processSlashesWithoutSignals(holder, limit));
emit SlashesProcessed(holder, limit);
}
| 5,869,459 |
[
1,
2227,
19034,
731,
358,
326,
864,
1800,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
1207,
3738,
7690,
12,
2867,
10438,
16,
2254,
1800,
13,
1071,
3849,
288,
203,
3639,
389,
4661,
11033,
310,
23346,
24899,
2567,
3738,
7690,
8073,
23346,
12,
4505,
16,
1800,
10019,
203,
3639,
3626,
9708,
7690,
13533,
12,
4505,
16,
1800,
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
] |
./full_match/4/0x4bDcAF3340FE31eFD1a4cdD30fE9dB3eab17DfDb/sources/tenderly/project/VaderBond.sol
|
* @notice set control variable adjustment @param _add bool @param _rate uint @param _target uint @param _buffer uint/
|
function setAdjustment(
bool _add,
uint _rate,
uint _target,
uint _buffer
) external onlyOwner {
require(_rate <= terms.controlVariable.mul(3) / 100, "rate > 3%");
if (_add) {
require(_target >= terms.controlVariable, "target < cv");
require(_target <= terms.controlVariable, "target > cv");
}
emit SetAdjustment(_add, _rate, _target, _buffer);
}
| 13,298,509 |
[
1,
542,
3325,
2190,
18335,
282,
389,
1289,
1426,
282,
389,
5141,
2254,
282,
389,
3299,
2254,
282,
389,
4106,
2254,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
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,
444,
19985,
12,
203,
3639,
1426,
389,
1289,
16,
203,
3639,
2254,
389,
5141,
16,
203,
3639,
2254,
389,
3299,
16,
203,
3639,
2254,
389,
4106,
203,
565,
262,
3903,
1338,
5541,
288,
203,
3639,
2583,
24899,
5141,
1648,
6548,
18,
7098,
3092,
18,
16411,
12,
23,
13,
342,
2130,
16,
315,
5141,
405,
890,
9,
8863,
203,
3639,
309,
261,
67,
1289,
13,
288,
203,
5411,
2583,
24899,
3299,
1545,
6548,
18,
7098,
3092,
16,
315,
3299,
411,
8951,
8863,
203,
5411,
2583,
24899,
3299,
1648,
6548,
18,
7098,
3092,
16,
315,
3299,
405,
8951,
8863,
203,
3639,
289,
203,
3639,
3626,
1000,
19985,
24899,
1289,
16,
389,
5141,
16,
389,
3299,
16,
389,
4106,
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
] |
pragma solidity ^0.4.23;
import "../storage/TeamsStorageController.sol";
import "../storage/StorageInterface.sol";
import "../token/ERC20TokenInterface.sol";
contract TeamContracts is TeamsStorageController {
event TeamCreated(uint indexed teamId);
event TeamMemberAdded(uint indexed contractId);
event TeamBalanceRefilled(uint indexed teamId, address payer, uint amount);
event TeamMemberRemoved(uint indexed contractId, uint amountPaidToMember, uint amountReturnedToTeam);
event Payout(uint indexed contractId, uint amount, address triggeredBy);
event ContractCompleted(uint indexed contractId, bool extended); // Boolean extended: whether the contract was extended to a new period
event ContractProlongationFailed(uint indexed contractId);
event Upgraded(address newContract);
address public erc20TokenAddress; // Address of authorized token
address public dreamTeamAddress; // Authorized account for managing teams
modifier dreamTeamOnly {require(msg.sender == dreamTeamAddress); _;} // allows only dreamTeamAddress to trigger fun
/**
* Constructor. This is yet the only way to set owner address, token address and storage address.
*/
constructor (address dt, address token, address dbAddress) public {
dreamTeamAddress = dt;
erc20TokenAddress = token;
db = dbAddress;
}
function createTeam (address teamOwnerAccount) dreamTeamOnly public returns(uint) {
uint teamId = storageAddTeam(teamOwnerAccount);
emit TeamCreated(teamId);
return teamId;
}
/**
* Adds a new member to a team. Member adding is only possible when team balance covers their first payout period.
* @param teamId - Team ID to add member to.
* @param memberAccount - Member address (where token balance live in token contract)
* @param agreementMinutes - Number of minutes to
*/
function addMember (uint teamId, address memberAccount, uint agreementMinutes, uint agreementValue, bool singleTermAgreement, uint contractId) dreamTeamOnly public {
storageDecTeamBalance(teamId, agreementValue); // throws if balance goes negative
storageAddTeamMember(teamId, memberAccount, agreementMinutes, agreementValue, singleTermAgreement, contractId);
emit TeamMemberAdded(contractId);
}
function removeMember (uint teamId, uint contractId) dreamTeamOnly public {
int memberIndex = storageGetTeamMemberIndexByContractId(teamId, contractId);
require(memberIndex != -1);
uint payoutDate = storageGetTeamMemberPayoutDate(teamId, uint(memberIndex));
if (payoutDate <= now) { // return full amount to the player
ERC20TokenInterface(erc20TokenAddress).transfer(storageGetTeamMemberAddress(teamId, uint(memberIndex)), agreementValue);
emit TeamMemberRemoved(contractId, agreementValue, 0);
} else { // if (payoutDate > now): return a part of the amount based on the number of days spent in the team, in proportion
uint agreementMinutes = storageGetTeamMemberAgreementMinutes(teamId, uint(memberIndex));
uint agreementValue = storageGetTeamMemberAgreementValue(teamId, uint(memberIndex));
// amountToPayout = numberOfFullDaysSpentInTheTeam * dailyRate; dailyRate = totalValue / numberOfDaysInAgreement
uint amountToPayout = ((agreementMinutes * 60 - (payoutDate - now)) / 1 days) * (60 * 24 * agreementValue / agreementMinutes);
if (amountToPayout > 0)
ERC20TokenInterface(erc20TokenAddress).transfer(storageGetTeamMemberAddress(teamId, uint(memberIndex)), amountToPayout);
if (amountToPayout < agreementValue)
storageIncTeamBalance(teamId, agreementValue - amountToPayout); // unlock the rest of the funds
emit TeamMemberRemoved(contractId, amountToPayout, agreementValue - amountToPayout);
}
// Actually delete team member from a storage
storageDeleteTeamMember(teamId, uint(memberIndex));
}
function payout (uint teamId) public {
uint value;
uint contractId;
// Iterate over all team members and payout to those who need to be paid.
// This is intended to restrict DreamTeam or anyone else from triggering payout (and thus the contract extension) for
// a particular team member only, avoiding paying out other team members. Also since sorting payouts by dates are
// expensive, we managed that giving a priority of contract extension to the leftmost team members (i = 0, 1, 2, ...)
// over other members (including those whose contract extension must have happened before the leftmost members) is okay,
// as we are going to trigger the payout daily and such case is more an exceptional one rather than the dangerous.
// Even if team owner/member knows how to cheat over payout, the only thing they can do is to fail contract extension
// for a particular team member (N rightmost team members) due to the lack of funds on the team balance.
for (uint index = 0; index < storageGetNumberOfMembers(teamId); ++index) {
if (storageGetTeamMemberPayoutDate(teamId, index) > now)
continue;
value = storageGetTeamMemberAgreementValue(teamId, index);
contractId = storageGetMemberContractId(teamId, index);
ERC20TokenInterface(erc20TokenAddress).transfer(storageGetTeamMemberAddress(teamId, index), value);
emit Payout(contractId, value, msg.sender);
if (storageGetTeamMemberSingleTermAgreement(teamId, index)) { // Terminate the contract due to a single-term agreement
storageDeleteTeamMember(teamId, index);
emit ContractCompleted(contractId, false);
} else { // Extend the contract
if (storageGetTeamBalance(teamId) < value) { // No funds in the team: auto extend is not possible, remove the team member
storageDeleteTeamMember(teamId, index);
emit ContractCompleted(contractId, false);
emit ContractProlongationFailed(contractId);
} else {
storageDecTeamBalance(teamId, value);
storageSetTeamMemberPayoutDate(
teamId,
index,
storageGetTeamMemberPayoutDate(teamId, index) + storageGetTeamMemberAgreementMinutes(teamId, index) * 60
);
emit ContractCompleted(contractId, true);
}
}
}
}
function batchPayout (uint[] teamIds) public {
for (uint i = 0; i < teamIds.length; ++i) {
payout(teamIds[i]);
}
}
/**
* Refill team balance for a given amount.
*/
function transferToTeam (uint teamId, uint amount) public {
// require(teamId < getNumberOfTeams()); // Does not open vulnerabilities but charities :)
// require(amount > 0); // already tested in ERC20 token + has no sense
require( // before calling transferToTeam, set allowance msg.sender->contractAddress in ERC20 token.
ERC20TokenInterface(erc20TokenAddress).transferFrom(msg.sender, address(this), amount)
);
storageIncTeamBalance(teamId, amount);
emit TeamBalanceRefilled(teamId, msg.sender, amount);
}
/**
* Destroys the current contract and moves permissions and funds to a new contract.
* @param newDeployedTeamContracts - Deployed teams contract.
*/
function upgrade (address newDeployedTeamContracts) dreamTeamOnly public {
require(TeamContracts(newDeployedTeamContracts).db() == db); // Switch between contracts linked to the same storage
// Do not enforce the same token contract for new TeamContracts; this took place when a token is upgraded (changed)
// In case of the new token contract, a special care should be taken into account to preserve the same balance in
// tokens in the newly deployed token contract.
// - require(TeamContracts(newDeployedTeamContracts).erc20TokenAddress() == erc20TokenAddress);
StorageInterface(db).transferOwnership(newDeployedTeamContracts); // Revoke access from the current contract and grant access to a new one
ERC20TokenInterface(erc20TokenAddress).transfer( // Move all funds to a new contract
newDeployedTeamContracts, ERC20TokenInterface(erc20TokenAddress).balanceOf(this)
);
emit Upgraded(newDeployedTeamContracts);
selfdestruct(newDeployedTeamContracts);
}
}
|
Boolean extended: whether the contract was extended to a new period
|
event ContractCompleted(uint indexed contractId, bool extended);
| 12,919,362 |
[
1,
5507,
7021,
30,
2856,
326,
6835,
1703,
7021,
358,
279,
394,
3879,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
871,
13456,
9556,
12,
11890,
8808,
6835,
548,
16,
1426,
7021,
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
] |
./partial_match/4/0x3582FD38d347785A256f2aDbcdd5a75dBfd00635/sources/DigitalaxPodePortal.sol
|
* @title Digitalax PCP NFT a.k.a. parent NFTs/ @notice event emitted upon construction of this contract, used to bootstrap external indexers
|
contract DigitalaxPodePortal is ERC721("DigitalaxPodePortal", "PCP") {
event DigitalaxPodePortalContractDeployed();
event DigitalaxPodePortalMetadataAdded(string tokenUri);
DigitalaxAccessControls public accessControls;
DigitalaxPodeNFT public podeNft;
uint256 public tokenIdPointer;
mapping(uint256 => address) public designers;
string[] public metadataList;
mapping(uint256 => mapping(uint256 => uint256)) private balances;
@param _accessControls Address of the Digitalax access control contract
constructor(DigitalaxAccessControls _accessControls, DigitalaxPodeNFT _podeNft) public {
accessControls = _accessControls;
podeNft = _podeNft;
emit DigitalaxPodePortalContractDeployed();
}
@dev Only senders with either the minter or smart contract role can invoke this method
@param _beneficiary Recipient of the NFT
@param _designer NFT designer - will be required for issuing royalties from secondary sales
@return uint256 The token ID of the token that was minted
@notice Mints a DigitalaxPodePortal AND when minting to a contract checks if the beneficiary is a 721 compatible
function mint(address _beneficiary, address _designer) external returns (uint256) {
require(balanceOf(_msgSender()) == 0, "DigitalaxPodePortal.mint: Sender already minted");
require(podeNft.balanceOf(_msgSender()) > 0, "DigitalaxPodePortal.mint: Sender must have PODE NFT");
uint256 _randomIndex = _rand();
require(bytes(metadataList[_randomIndex]).length > 0, "DigitalaxPodePortal.mint: Token URI is empty");
require(_designer != address(0), "DigitalaxPodePortal.mint: Designer is zero address");
tokenIdPointer = tokenIdPointer.add(1);
uint256 tokenId = tokenIdPointer;
_safeMint(_beneficiary, tokenId);
_setTokenURI(tokenId, metadataList[_randomIndex]);
designers[tokenId] = _designer;
return tokenId;
}
@dev Only the owner or an approved sender can call this method
@param _tokenId the token ID to burn
@notice Burns a DigitalaxPodePortal, releasing any composed 1155 tokens held by the token itself
function burn(uint256 _tokenId) external {
address operator = _msgSender();
require(
ownerOf(_tokenId) == operator || isApproved(_tokenId, operator),
"DigitalaxPodePortal.burn: Only garment owner or approved"
);
_burn(_tokenId);
delete designers[_tokenId];
}
@dev Only admin or smart contract
@param _tokenUri The new URI
@notice Updates the token URI of a given token
function addTokenURI(string calldata _tokenUri) external {
require(
accessControls.hasSmartContractRole(_msgSender()) || accessControls.hasAdminRole(_msgSender()),
"DigitalaxPodePortal.addTokenURI: Sender must be an authorised contract or admin"
);
}
@dev Only admin
@param _accessControls Address of the new access controls contract
@notice Method for updating the access controls contract used by the NFT
function updateAccessControls(DigitalaxAccessControls _accessControls) external {
require(accessControls.hasAdminRole(_msgSender()), "DigitalaxPodePortal.updateAccessControls: Sender must be admin");
accessControls = _accessControls;
}
@param _tokenId ID of the token being checked
@notice View method for checking whether a token has been minted
function exists(uint256 _tokenId) external view returns (bool) {
return _exists(_tokenId);
}
function isApproved(uint256 _tokenId, address _operator) public view returns (bool) {
return isApprovedForAll(ownerOf(_tokenId), _operator) || getApproved(_tokenId) == _operator;
}
@param _tokenUri URI supplied on minting
@param _designer Address supplied on minting
@notice Checks that the URI is not empty and the designer is a real address
function _assertMintingParamsValid(string calldata _tokenUri, address _designer) pure internal {
require(bytes(_tokenUri).length > 0, "DigitalaxPodePortal._assertMintingParamsValid: Token URI is empty");
require(_designer != address(0), "DigitalaxPodePortal._assertMintingParamsValid: Designer is zero address");
}
@notice Generate unpredictable random number
function _rand() private view returns (uint256) {
uint256 seed = uint256(keccak256(abi.encodePacked(
block.timestamp + block.difficulty +
((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)) +
block.gaslimit +
((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)) +
block.number
)));
return seed.sub(seed.div(metadataList.length).mul(metadataList.length));
}
@param _tokenUri URI for metadata
@notice Method for adding metadata to the list
function _addTokenURI(string calldata _tokenUri) internal {
metadataList.push(_tokenUri);
emit DigitalaxPodePortalMetadataAdded(_tokenUri);
}
}
| 8,508,355 |
[
1,
4907,
7053,
651,
453,
4258,
423,
4464,
279,
18,
79,
18,
69,
18,
982,
423,
4464,
87,
19,
225,
871,
17826,
12318,
16171,
434,
333,
6835,
16,
1399,
358,
7065,
3903,
31932,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
11678,
7053,
651,
52,
390,
24395,
353,
4232,
39,
27,
5340,
2932,
4907,
7053,
651,
52,
390,
24395,
3113,
315,
3513,
52,
7923,
288,
203,
203,
565,
871,
11678,
7053,
651,
52,
390,
24395,
8924,
31954,
5621,
203,
565,
871,
11678,
7053,
651,
52,
390,
24395,
2277,
8602,
12,
1080,
1147,
3006,
1769,
203,
203,
565,
11678,
7053,
651,
16541,
87,
1071,
2006,
16795,
31,
203,
565,
11678,
7053,
651,
52,
390,
50,
4464,
1071,
293,
390,
50,
1222,
31,
203,
203,
565,
2254,
5034,
1071,
1147,
548,
4926,
31,
203,
203,
565,
2874,
12,
11890,
5034,
516,
1758,
13,
1071,
8281,
414,
31,
203,
203,
565,
533,
8526,
1071,
1982,
682,
31,
203,
203,
565,
2874,
12,
11890,
5034,
516,
2874,
12,
11890,
5034,
516,
2254,
5034,
3719,
3238,
324,
26488,
31,
203,
203,
377,
632,
891,
389,
3860,
16795,
5267,
434,
326,
11678,
7053,
651,
2006,
3325,
6835,
203,
565,
3885,
12,
4907,
7053,
651,
16541,
87,
389,
3860,
16795,
16,
11678,
7053,
651,
52,
390,
50,
4464,
389,
84,
390,
50,
1222,
13,
1071,
288,
203,
3639,
2006,
16795,
273,
389,
3860,
16795,
31,
203,
3639,
293,
390,
50,
1222,
273,
389,
84,
390,
50,
1222,
31,
203,
3639,
3626,
11678,
7053,
651,
52,
390,
24395,
8924,
31954,
5621,
203,
565,
289,
203,
203,
377,
632,
5206,
5098,
1366,
414,
598,
3344,
326,
1131,
387,
578,
13706,
6835,
2478,
848,
4356,
333,
707,
203,
377,
632,
891,
389,
70,
4009,
74,
14463,
814,
23550,
434,
326,
423,
4464,
203,
377,
2
] |
// Sources flattened with hardhat v2.4.1 https://hardhat.org
// File contracts/interfaces/IERC721.sol
pragma solidity 0.5.7;
/// @title ERC-721 Non-Fungible Token Standard
/// @dev See https://eips.ethereum.org/EIPS/eip-721
/// Note: the ERC-165 identifier for this interface is 0x80ac58cd
interface IERC721 {
/// @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, uint 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, uint 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 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, uint _tokenId) external payable;
/// @notice Set or reaffirm the approved address for an NFT
/// @dev The zero address indicates there is no approved address.
/// @dev 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, uint _tokenId) external payable;
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT. When transfer is complete, this function
/// checks if `_to` is a smart contract (code size > 0). If so, it calls
/// `onERC721Received` on `_to` and throws if the return value is not
/// `bytes4(keccak256('onERC721Received(address,address,uint,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, uint _tokenId, bytes calldata data) external payable;
/// @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, uint _tokenId) external payable;
/// @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 (uint);
/// @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(uint _tokenId) external 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(uint _tokenId) external 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) external view returns (bool);
/// @notice A descriptive name for a collection of NFTs in this contract
function name() external view returns (string memory _name);
}
// File contracts/interfaces/ILockCore.sol
pragma solidity 0.5.7;
/**
* @title The Lock interface core methods for a Lock
* @author HardlyDifficult (unlock-protocol.com)
*/
interface ILockCore {
/**
* @dev Purchase function, public version, with no referrer.
* @param _recipient address of the recipient of the purchased key
*/
function purchaseFor(
address _recipient
)
external
payable;
/**
* @dev Purchase function, public version, with referrer.
* @param _recipient address of the recipient of the purchased key
* @param _referrer address of the user making the referral
*/
function purchaseForFrom(
address _recipient,
address _referrer
)
external
payable;
/**
* @dev Destroys the user's key and sends a refund based on the amount of time remaining.
*/
function cancelAndRefund()
external;
/**
* @dev Called by owner to withdraw all funds from the lock.
*/
function withdraw(
)
external;
/**
* @dev Called by owner to partially withdraw funds from the lock.
*/
function partialWithdraw(
uint _amount
)
external;
/**
* A function which lets the owner of the lock expire a users' key.
*/
function expireKeyFor(
address _owner
)
external;
/**
* A function which lets the owner of the lock to change the price for future purchases.
*/
function updateKeyPrice(
uint _keyPrice
)
external;
/**
* @dev Used to disable lock before migrating keys and/or destroying contract.
* @dev Reverts if called by anyone but the owner.
* @dev Reverts if isAlive == false
* @dev Should emit Disable event.
*/
function disableLock(
)
external;
/**
* @dev Used to clean up old lock contracts from the blockchain by using selfdestruct.
* @dev Reverts if called by anyone but the owner.
* @dev Reverts if isAlive == true
* @dev Should emit Destroy event.
*/
function destroyLock(
)
external;
/**
* @dev Determines how much of a refund a key owner would receive if they issued
* a cancelAndRefund now.
* @param _owner The owner of the key check the refund value for.
* Note that due to the time required to mine a tx, the actual refund amount will be lower
* than what the user reads from this call.
*/
function getCancelAndRefundValueFor(
address _owner
)
external
view
returns (uint refund);
/**
* Checks if the user has a non-expired key.
*/
function getHasValidKey(
address _owner
)
external
view
returns (bool);
/**
* Public function which returns the total number of unique owners (both expired
* and valid). This may be larger than totalSupply.
*/
function numberOfOwners()
external
view
returns (uint);
/**
* Public function which returns the total number of keys (both expired and valid)
*
* This function signature is from the ERC-721 enumerable extension.
* https://eips.ethereum.org/EIPS/eip-721
* @notice Count NFTs tracked by this contract
* @return A count of valid NFTs tracked by this contract, where each one of
* them has an assigned and queryable owner not equal to the zero address
*/
function totalSupply()
external
view
returns (uint);
/**
* @dev Returns the key's ExpirationTimestamp field for a given owner.
* @param _owner address of the user for whom we search the key
*/
function keyExpirationTimestampFor(
address _owner
)
external
view
returns (uint timestamp);
/**
* @param _page the page of key owners requested when faceted by page size
* @param _pageSize the number of Key Owners requested per page
*/
function getOwnersByPage(
uint _page,
uint _pageSize
)
external
view
returns (address[] memory);
}
// File zos-lib/contracts/[email protected]
pragma solidity >=0.4.24 <0.6.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 wasInitializing = initializing;
initializing = true;
initialized = true;
_;
initializing = wasInitializing;
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
uint256 cs;
assembly { cs := extcodesize(address) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// File openzeppelin-eth/contracts/ownership/[email protected]
pragma solidity ^0.5.0;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable is Initializable {
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.
*/
function initialize(address sender) public initializer {
_owner = 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;
}
uint256[50] private ______gap;
}
// File openzeppelin-solidity/contracts/introspection/[email protected]
pragma solidity ^0.5.0;
/**
* @title IERC165
* @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md
*/
interface IERC165 {
/**
* @notice Query if a contract implements an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File openzeppelin-solidity/contracts/introspection/[email protected]
pragma solidity ^0.5.0;
/**
* @title ERC165
* @author Matt Condon (@shrugs)
* @dev Implements ERC165 using a lookup table.
*/
contract ERC165 is IERC165 {
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* 0x01ffc9a7 ===
* bytes4(keccak256('supportsInterface(bytes4)'))
*/
/**
* @dev a mapping of interface id to whether or not it's supported
*/
mapping(bytes4 => bool) private _supportedInterfaces;
/**
* @dev A contract implementing SupportsInterfaceWithLookup
* implement ERC165 itself
*/
constructor () internal {
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev implement supportsInterface(bytes4) using a lookup table
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev internal method for registering an interface
*/
function _registerInterface(bytes4 interfaceId) internal {
require(interfaceId != 0xffffffff);
_supportedInterfaces[interfaceId] = true;
}
}
// File openzeppelin-solidity/contracts/token/ERC721/[email protected]
pragma solidity ^0.5.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract IERC721Receiver {
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safeTransfer`. This function MUST return the function selector,
* otherwise the caller will revert the transaction. The selector to be
* returned can be obtained as `this.onERC721Received.selector`. This
* function MAY throw to revert and reject the transfer.
* Note: the ERC721 contract address is always the message sender.
* @param operator The address which called `safeTransferFrom` function
* @param from The address which previously owned the token
* @param tokenId The NFT identifier which is being transferred
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data)
public returns (bytes4);
}
// File openzeppelin-solidity/contracts/token/ERC721/[email protected]
pragma solidity ^0.5.0;
contract ERC721Holder is IERC721Receiver {
function onERC721Received(address, address, uint256, bytes memory) public returns (bytes4) {
return this.onERC721Received.selector;
}
}
// File contracts/mixins/MixinDisableAndDestroy.sol
pragma solidity 0.5.7;
/**
* @title Mixin allowing the Lock owner to disable a Lock (preventing new purchases)
* and then destroy it.
* @author HardlyDifficult
* @dev `Mixins` are a design pattern seen in the 0x contracts. It simply
* separates logically groupings of code to ease readability.
*/
contract MixinDisableAndDestroy is
IERC721,
Ownable
{
// Used to disable payable functions when deprecating an old lock
bool public isAlive;
event Destroy(
uint balance,
address indexed owner
);
event Disable();
constructor(
) internal
{
isAlive = true;
}
// Only allow usage when contract is Alive
modifier onlyIfAlive() {
require(isAlive, 'LOCK_DEPRECATED');
_;
}
/**
* @dev Used to disable lock before migrating keys and/or destroying contract
*/
function disableLock()
external
onlyOwner
onlyIfAlive
{
emit Disable();
isAlive = false;
}
/**
* @dev Used to clean up old lock contracts from the blockchain
* TODO: add a check to ensure all keys are INVALID!
*/
function destroyLock()
external
onlyOwner
{
require(isAlive == false, 'DISABLE_FIRST');
emit Destroy(address(this).balance, msg.sender);
selfdestruct(msg.sender);
// Note we don't clean up the `locks` data in Unlock.sol as it should not be necessary
// and leaves some data behind ('Unlock.LockBalances') which may be helpful.
}
}
// File contracts/interfaces/IUnlock.sol
pragma solidity 0.5.7;
/**
* @title The Unlock Interface
* @author Nick Furfaro (unlock-protocol.com)
**/
interface IUnlock {
// Events
event NewLock(
address indexed lockOwner,
address indexed newLockAddress
);
// Use initialize instead of a constructor to support proxies (for upgradeability via zos).
function initialize(address _owner) external;
/**
* @dev Create lock
* This deploys a lock for a creator. It also keeps track of the deployed lock.
* @param _tokenAddress set to the ERC20 token address, or 0 for ETH.
* Return type `ILockCore` is the most specific interface from which all lock types inherit.
*/
function createLock(
uint _expirationDuration,
address _tokenAddress,
uint _keyPrice,
uint _maxNumberOfKeys
)
external
returns (ILockCore lock);
/**
* This function keeps track of the added GDP, as well as grants of discount tokens
* to the referrer, if applicable.
* The number of discount tokens granted is based on the value of the referal,
* the current growth rate and the lock's discount token distribution rate
* This function is invoked by a previously deployed lock only.
*/
function recordKeyPurchase(
uint _value,
address _referrer // solhint-disable-line no-unused-vars
)
external;
/**
* This function will keep track of consumed discounts by a given user.
* It will also grant discount tokens to the creator who is granting the discount based on the
* amount of discount and compensation rate.
* This function is invoked by a previously deployed lock only.
*/
function recordConsumedDiscount(
uint _discount,
uint _tokens // solhint-disable-line no-unused-vars
)
external;
/**
* This function returns the discount available for a user, when purchasing a
* a key from a lock.
* This does not modify the state. It returns both the discount and the number of tokens
* consumed to grant that discount.
*/
function computeAvailableDiscountFor(
address _purchaser, // solhint-disable-line no-unused-vars
uint _keyPrice // solhint-disable-line no-unused-vars
)
external
view
returns (uint discount, uint tokens);
}
// File openzeppelin-solidity/contracts/token/ERC20/[email protected]
pragma solidity ^0.5.0;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File contracts/mixins/MixinFunds.sol
pragma solidity 0.5.7;
/**
* @title An implementation of the money related functions.
* @author HardlyDifficult (unlock-protocol.com)
*/
contract MixinFunds
{
/**
* The token-type that this Lock is priced in. If 0, then use ETH, else this is
* a ERC20 token address.
*/
address public tokenAddress;
constructor(
address _tokenAddress
) public
{
require(
_tokenAddress == address(0) || IERC20(_tokenAddress).totalSupply() > 0,
'INVALID_TOKEN'
);
tokenAddress = _tokenAddress;
}
/**
* Ensures that the msg.sender has paid at least the price stated.
*
* With ETH, this means the function originally called was `payable` and the
* transaction included at least the amount requested.
*
* Security: be wary of re-entrancy when calling this function.
*/
function _chargeAtLeast(
uint _price
) internal
{
if(tokenAddress == address(0)) {
require(msg.value >= _price, 'NOT_ENOUGH_FUNDS');
} else {
IERC20 token = IERC20(tokenAddress);
uint balanceBefore = token.balanceOf(address(this));
token.transferFrom(msg.sender, address(this), _price);
// There are known bugs in popular ERC20 implements which means we cannot
// trust the return value of `transferFrom`. This require statement ensures
// that a transfer occurred.
require(token.balanceOf(address(this)) > balanceBefore, 'TRANSFER_FAILED');
}
}
/**
* Transfers funds from the contract to the account provided.
*
* Security: be wary of re-entrancy when calling this function.
*/
function _transfer(
address _to,
uint _amount
) internal
{
if(tokenAddress == address(0)) {
address(uint160(_to)).transfer(_amount);
} else {
IERC20 token = IERC20(tokenAddress);
uint balanceBefore = token.balanceOf(_to);
token.transfer(_to, _amount);
// There are known bugs in popular ERC20 implements which means we cannot
// trust the return value of `transferFrom`. This require statement ensures
// that a transfer occurred.
require(token.balanceOf(_to) > balanceBefore, 'TRANSFER_FAILED');
}
}
/**
* Gets the current balance of the account provided.
*/
function _getBalance(
address _account
) internal view
returns (uint)
{
if(tokenAddress == address(0)) {
return _account.balance;
} else {
return IERC20(tokenAddress).balanceOf(_account);
}
}
}
// File contracts/mixins/MixinLockCore.sol
pragma solidity 0.5.7;
/**
* @title Mixin for core lock data and functions.
* @author HardlyDifficult
* @dev `Mixins` are a design pattern seen in the 0x contracts. It simply
* separates logically groupings of code to ease readability.
*/
contract MixinLockCore is
Ownable,
MixinFunds,
MixinDisableAndDestroy
{
event PriceChanged(
uint oldKeyPrice,
uint keyPrice
);
event Withdrawal(
address indexed _sender,
uint _amount
);
// Unlock Protocol address
// TODO: should we make that private/internal?
IUnlock public unlockProtocol;
// Duration in seconds for which the keys are valid, after creation
// should we take a smaller type use less gas?
// TODO: add support for a timestamp instead of duration
uint public expirationDuration;
// price in wei of the next key
// TODO: allow support for a keyPriceCalculator which could set prices dynamically
uint public keyPrice;
// Max number of keys sold if the keyReleaseMechanism is public
uint public maxNumberOfKeys;
// A count of how many new key purchases there have been
uint public numberOfKeysSold;
// The version number for this lock contract,
uint public publicLockVersion;
// Ensure that the Lock has not sold all of its keys.
modifier notSoldOut() {
require(maxNumberOfKeys > numberOfKeysSold, 'LOCK_SOLD_OUT');
_;
}
constructor(
uint _expirationDuration,
uint _keyPrice,
uint _maxNumberOfKeys,
uint _version
) internal
{
require(_expirationDuration <= 100 * 365 * 24 * 60 * 60, 'MAX_EXPIRATION_100_YEARS');
unlockProtocol = IUnlock(msg.sender); // Make sure we link back to Unlock's smart contract.
expirationDuration = _expirationDuration;
keyPrice = _keyPrice;
maxNumberOfKeys = _maxNumberOfKeys;
publicLockVersion = _version;
}
/**
* @dev Called by owner to withdraw all funds from the lock.
* TODO: consider allowing anybody to trigger this as long as it goes to owner anyway?
*/
function withdraw()
external
onlyOwner
{
uint balance = _getBalance(address(this));
require(balance > 0, 'NOT_ENOUGH_FUNDS');
// Security: re-entrancy not a risk as this is the last line of an external function
_withdraw(balance);
}
/**
* @dev Called by owner to partially withdraw funds from the lock.
* TODO: consider allowing anybody to trigger this as long as it goes to owner anyway?
*/
function partialWithdraw(uint _amount)
external
onlyOwner
{
require(_amount > 0, 'GREATER_THAN_ZERO');
uint balance = _getBalance(address(this));
require(balance >= _amount, 'NOT_ENOUGH_FUNDS');
// Security: re-entrancy not a risk as this is the last line of an external function
_withdraw(_amount);
}
/**
* A function which lets the owner of the lock to change the price for future purchases.
*/
function updateKeyPrice(
uint _keyPrice
)
external
onlyOwner
onlyIfAlive
{
uint oldKeyPrice = keyPrice;
keyPrice = _keyPrice;
emit PriceChanged(oldKeyPrice, keyPrice);
}
/**
* Public function which returns the total number of unique keys sold (both
* expired and valid)
*/
function totalSupply()
public
view
returns (uint)
{
return numberOfKeysSold;
}
/**
* @dev private version of the withdraw function which handles all withdrawals from the lock.
*
* Security: Be wary of re-entrancy when calling this.
*/
function _withdraw(uint _amount)
private
{
_transfer(Ownable.owner(), _amount);
emit Withdrawal(msg.sender, _amount);
}
}
// File contracts/mixins/MixinKeys.sol
pragma solidity 0.5.7;
/**
* @title Mixin for managing `Key` data.
* @author HardlyDifficult
* @dev `Mixins` are a design pattern seen in the 0x contracts. It simply
* separates logically groupings of code to ease readability.
*/
contract MixinKeys is
Ownable,
MixinLockCore
{
// The struct for a key
struct Key {
uint tokenId;
uint expirationTimestamp;
}
// Called when the Lock owner expires a user's Key
event ExpireKey(uint tokenId);
// Keys
// Each owner can have at most exactly one key
// TODO: could we use public here? (this could be confusing though because it getter will
// return 0 values when missing a key)
mapping (address => Key) private keyByOwner;
// Each tokenId can have at most exactly one owner at a time.
// Returns 0 if the token does not exist
// TODO: once we decouple tokenId from owner address (incl in js), then we can consider
// merging this with numberOfKeysSold into an array instead.
mapping (uint => address) private ownerByTokenId;
// Addresses of owners are also stored in an array.
// Addresses are never removed by design to avoid abuses around referals
address[] public owners;
// Ensures that an owner has a key
modifier hasKey(
address _owner
) {
Key storage key = keyByOwner[_owner];
require(
key.expirationTimestamp > 0, 'NO_SUCH_KEY'
);
_;
}
// Ensures that an owner has a valid key
modifier hasValidKey(
address _owner
) {
require(
getHasValidKey(_owner), 'KEY_NOT_VALID'
);
_;
}
// Ensures that a key has an owner
modifier isKey(
uint _tokenId
) {
require(
ownerByTokenId[_tokenId] != address(0), 'NO_SUCH_KEY'
);
_;
}
// Ensure that the caller owns the key
modifier onlyKeyOwner(
uint _tokenId
) {
require(
isKeyOwner(_tokenId, msg.sender), 'ONLY_KEY_OWNER'
);
_;
}
/**
* A function which lets the owner of the lock expire a users' key.
*/
function expireKeyFor(
address _owner
)
public
onlyOwner
hasValidKey(_owner)
{
Key storage key = keyByOwner[_owner];
key.expirationTimestamp = block.timestamp; // Effectively expiring the key
emit ExpireKey(key.tokenId);
}
/**
* In the specific case of a Lock, each owner can own only at most 1 key.
* @return The number of NFTs owned by `_owner`, either 0 or 1.
*/
function balanceOf(
address _owner
)
external
view
returns (uint)
{
require(_owner != address(0), 'INVALID_ADDRESS');
return keyByOwner[_owner].expirationTimestamp > 0 ? 1 : 0;
}
/**
* Checks if the user has a non-expired key.
*/
function getHasValidKey(
address _owner
)
public
view
returns (bool)
{
return keyByOwner[_owner].expirationTimestamp > block.timestamp;
}
/**
* @notice Find the tokenId for a given user
* @return The tokenId of the NFT, else revert
*/
function getTokenIdFor(
address _account
)
external
view
hasKey(_account)
returns (uint)
{
return keyByOwner[_account].tokenId;
}
/**
* A function which returns a subset of the keys for this Lock as an array
* @param _page the page of key owners requested when faceted by page size
* @param _pageSize the number of Key Owners requested per page
*/
function getOwnersByPage(uint _page, uint _pageSize)
public
view
returns (address[] memory)
{
require(owners.length > 0, 'NO_OUTSTANDING_KEYS');
uint pageSize = _pageSize;
uint _startIndex = _page * pageSize;
uint endOfPageIndex;
if (_startIndex + pageSize > owners.length) {
endOfPageIndex = owners.length;
pageSize = owners.length - _startIndex;
} else {
endOfPageIndex = (_startIndex + pageSize);
}
// new temp in-memory array to hold pageSize number of requested owners:
address[] memory ownersByPage = new address[](pageSize);
uint pageIndex = 0;
// Build the requested set of owners into a new temporary array:
for (uint i = _startIndex; i < endOfPageIndex; i++) {
ownersByPage[pageIndex] = owners[i];
pageIndex++;
}
return ownersByPage;
}
/**
* Checks if the given address owns the given tokenId.
*/
function isKeyOwner(
uint _tokenId,
address _owner
) public view
returns (bool)
{
return ownerByTokenId[_tokenId] == _owner;
}
/**
* @dev Returns the key's ExpirationTimestamp field for a given owner.
* @param _owner address of the user for whom we search the key
*/
function keyExpirationTimestampFor(
address _owner
)
public view
hasKey(_owner)
returns (uint timestamp)
{
return keyByOwner[_owner].expirationTimestamp;
}
/**
* Public function which returns the total number of unique owners (both expired
* and valid). This may be larger than totalSupply.
*/
function numberOfOwners()
public
view
returns (uint)
{
return owners.length;
}
/**
* @notice ERC721: Find the owner of an NFT
* @return The address of the owner of the NFT, if applicable
*/
function ownerOf(
uint _tokenId
)
public view
isKey(_tokenId)
returns (address)
{
return ownerByTokenId[_tokenId];
}
/**
* Assigns the key a new tokenId (from numberOfKeysSold) if it does not already have
* one assigned.
*/
function _assignNewTokenId(
Key storage _key
) internal
{
if (_key.tokenId == 0) {
// This is a brand new owner, else an owner of an expired key buying an extension.
// We increment the tokenId counter
numberOfKeysSold++;
// we assign the incremented `numberOfKeysSold` as the tokenId for the new key
_key.tokenId = numberOfKeysSold;
}
}
/**
* Records the owner of a given tokenId
*/
function _recordOwner(
address _owner,
uint _tokenId
) internal
{
if (ownerByTokenId[_tokenId] != _owner) {
// TODO: this may include duplicate entries
owners.push(_owner);
// We register the owner of the tokenID
ownerByTokenId[_tokenId] = _owner;
}
}
/**
* Returns the Key struct for the given owner.
*/
function _getKeyFor(
address _owner
) internal view
returns (Key storage)
{
return keyByOwner[_owner];
}
}
// File contracts/mixins/MixinApproval.sol
pragma solidity 0.5.7;
/**
* @title Mixin for the Approval related functions needed to meet the ERC721
* standard.
* @author HardlyDifficult
* @dev `Mixins` are a design pattern seen in the 0x contracts. It simply
* separates logically groupings of code to ease readability.
*/
contract MixinApproval is
IERC721,
MixinDisableAndDestroy,
MixinKeys
{
// Keeping track of approved transfers
// This is a mapping of addresses which have approved
// the transfer of a key to another address where their key can be transfered
// Note: the approver may actually NOT have a key... and there can only
// be a single approved beneficiary
// Note 2: for transfer, both addresses will be different
// Note 3: for sales (new keys on restricted locks), both addresses will be the same
mapping (uint => address) private approved;
// Keeping track of approved operators for a Key owner.
// Since an owner can have up to 1 Key, this is similiar to above
// but the approval does not reset when a transfer occurs.
mapping (address => mapping (address => bool)) private ownerToOperatorApproved;
// Ensure that the caller has a key
// or that the caller has been approved
// for ownership of that key
modifier onlyKeyOwnerOrApproved(
uint _tokenId
) {
require(
isKeyOwner(_tokenId, msg.sender) ||
_isApproved(_tokenId, msg.sender) ||
isApprovedForAll(ownerOf(_tokenId), msg.sender),
'ONLY_KEY_OWNER_OR_APPROVED');
_;
}
/**
* This approves _approved to get ownership of _tokenId.
* Note: that since this is used for both purchase and transfer approvals
* the approved token may not exist.
*/
function approve(
address _approved,
uint _tokenId
)
external
payable
onlyIfAlive
onlyKeyOwnerOrApproved(_tokenId)
{
require(msg.sender != _approved, 'APPROVE_SELF');
approved[_tokenId] = _approved;
emit Approval(ownerOf(_tokenId), _approved, _tokenId);
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf
* @param _to operator address to set the approval
* @param _approved representing the status of the approval to be set
*/
function setApprovalForAll(
address _to,
bool _approved
) external
onlyIfAlive
{
require(_to != msg.sender, 'APPROVE_SELF');
ownerToOperatorApproved[msg.sender][_to] = _approved;
emit ApprovalForAll(msg.sender, _to, _approved);
}
/**
* external version
* Will return the approved recipient for a key, if any.
*/
function getApproved(
uint _tokenId
)
external
view
returns (address)
{
return _getApproved(_tokenId);
}
/**
* @dev Tells whether an operator is approved by a given owner
* @param _owner owner address which you want to query the approval of
* @param _operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(
address _owner,
address _operator
) public view
returns (bool)
{
return ownerToOperatorApproved[_owner][_operator];
}
/**
* @dev Checks if the given user is approved to transfer the tokenId.
*/
function _isApproved(
uint _tokenId,
address _user
) internal view
returns (bool)
{
return approved[_tokenId] == _user;
}
/**
* Will return the approved recipient for a key transfer or ownership.
* Note: this does not check that a corresponding key
* actually exists.
*/
function _getApproved(
uint _tokenId
)
internal
view
returns (address)
{
address approvedRecipient = approved[_tokenId];
require(approvedRecipient != address(0), 'NONE_APPROVED');
return approvedRecipient;
}
/**
* @dev Function to clear current approval of a given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function _clearApproval(
uint256 _tokenId
) internal
{
if (approved[_tokenId] != address(0)) {
approved[_tokenId] = address(0);
}
}
}
// File contracts/mixins/MixinGrantKeys.sol
pragma solidity 0.5.7;
/**
* @title Mixin allowing the Lock owner to grant / gift keys to users.
* @author HardlyDifficult
* @dev `Mixins` are a design pattern seen in the 0x contracts. It simply
* separates logically groupings of code to ease readability.
*/
contract MixinGrantKeys is
IERC721,
Ownable,
MixinKeys
{
/**
* Allows the Lock owner to give a user a key with no charge.
*/
function grantKey(
address _recipient,
uint _expirationTimestamp
) external
onlyOwner
{
_grantKey(_recipient, _expirationTimestamp);
}
/**
* Allows the Lock owner to give a collection of users a key with no charge.
* All keys granted have the same expiration date.
*/
function grantKeys(
address[] calldata _recipients,
uint _expirationTimestamp
) external
onlyOwner
{
for(uint i = 0; i < _recipients.length; i++) {
_grantKey(_recipients[i], _expirationTimestamp);
}
}
/**
* Allows the Lock owner to give a collection of users a key with no charge.
* Each key may be assigned a different expiration date.
*/
function grantKeys(
address[] calldata _recipients,
uint[] calldata _expirationTimestamps
) external
onlyOwner
{
for(uint i = 0; i < _recipients.length; i++) {
_grantKey(_recipients[i], _expirationTimestamps[i]);
}
}
/**
* Give a key to the given user
*/
function _grantKey(
address _recipient,
uint _expirationTimestamp
) private
{
require(_recipient != address(0), 'INVALID_ADDRESS');
Key storage toKey = _getKeyFor(_recipient);
require(_expirationTimestamp > toKey.expirationTimestamp, 'ALREADY_OWNS_KEY');
_assignNewTokenId(toKey);
_recordOwner(_recipient, toKey.tokenId);
toKey.expirationTimestamp = _expirationTimestamp;
// trigger event
emit Transfer(
address(0), // This is a creation.
_recipient,
toKey.tokenId
);
}
}
// File contracts/mixins/MixinLockMetadata.sol
pragma solidity 0.5.7;
/**
* @title Mixin for metadata about the Lock.
* @author HardlyDifficult
* @dev `Mixins` are a design pattern seen in the 0x contracts. It simply
* separates logically groupings of code to ease readability.
*/
contract MixinLockMetadata is
IERC721,
Ownable
{
/// A descriptive name for a collection of NFTs in this contract
string private lockName;
/**
* Allows the Lock owner to assign a descriptive name for this Lock.
*/
function updateLockName(
string calldata _lockName
) external
onlyOwner
{
lockName = _lockName;
}
/**
* @dev Gets the token name
* @return string representing the token name
*/
function name(
) external view
returns (string memory)
{
return lockName;
}
}
// File contracts/mixins/MixinNoFallback.sol
pragma solidity 0.5.7;
/**
* @title Mixin for the fallback function implementation, which simply reverts.
* @author HardlyDifficult
* @dev `Mixins` are a design pattern seen in the 0x contracts. It simply
* separates logically groupings of code to ease readability.
*/
contract MixinNoFallback
{
/**
* @dev the fallback function should not be used. This explicitly reverts
* to ensure it's never used.
*/
function()
external
{
revert('NO_FALLBACK');
}
}
// File openzeppelin-solidity/contracts/math/[email protected]
pragma solidity ^0.5.0;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
// File contracts/mixins/MixinPurchase.sol
pragma solidity 0.5.7;
/**
* @title Mixin for the purchase-related functions.
* @author HardlyDifficult
* @dev `Mixins` are a design pattern seen in the 0x contracts. It simply
* separates logically groupings of code to ease readability.
*/
contract MixinPurchase is
MixinFunds,
MixinDisableAndDestroy,
MixinLockCore,
MixinKeys
{
using SafeMath for uint;
/**
* @dev Purchase function, public version, with no referrer.
* @param _recipient address of the recipient of the purchased key
*/
function purchaseFor(
address _recipient
)
external
payable
onlyIfAlive
{
return _purchaseFor(_recipient, address(0));
}
/**
* @dev Purchase function, public version, with referrer.
* @param _recipient address of the recipient of the purchased key
* @param _referrer address of the user making the referral
*/
function purchaseForFrom(
address _recipient,
address _referrer
)
external
payable
onlyIfAlive
hasValidKey(_referrer)
{
return _purchaseFor(_recipient, _referrer);
}
/**
* @dev Purchase function: this lets a user purchase a key from the lock for another user
* @param _recipient address of the recipient of the purchased key
* This will fail if
* - the keyReleaseMechanism is private
* - the keyReleaseMechanism is Approved and the recipient has not been previously approved
* - the amount value is smaller than the price
* - the recipient already owns a key
* TODO: next version of solidity will allow for message to be added to require.
*/
function _purchaseFor(
address _recipient,
address _referrer
)
private
notSoldOut()
{ // solhint-disable-line function-max-lines
require(_recipient != address(0), 'INVALID_ADDRESS');
// Let's get the actual price for the key from the Unlock smart contract
uint discount;
uint tokens;
uint inMemoryKeyPrice = keyPrice;
(discount, tokens) = unlockProtocol.computeAvailableDiscountFor(_recipient, inMemoryKeyPrice);
uint netPrice = inMemoryKeyPrice;
if (discount > inMemoryKeyPrice) {
netPrice = 0;
} else {
// SafeSub not required as the if statement already confirmed `inMemoryKeyPrice - discount` cannot underflow
netPrice = inMemoryKeyPrice - discount;
}
// We explicitly allow for greater amounts of ETH to allow 'donations'
_chargeAtLeast(netPrice);
// Assign the key
Key storage toKey = _getKeyFor(_recipient);
uint previousExpiration = toKey.expirationTimestamp;
if (previousExpiration < block.timestamp) {
_assignNewTokenId(toKey);
_recordOwner(_recipient, toKey.tokenId);
// SafeAdd is not required here since expirationDuration is capped to a tiny value
// (relative to the size of a uint)
toKey.expirationTimestamp = block.timestamp + expirationDuration;
} else {
// This is an existing owner trying to extend their key
toKey.expirationTimestamp = previousExpiration.add(expirationDuration);
}
if (discount > 0) {
unlockProtocol.recordConsumedDiscount(discount, tokens);
}
unlockProtocol.recordKeyPurchase(netPrice, _referrer);
// trigger event
emit Transfer(
address(0), // This is a creation.
_recipient,
numberOfKeysSold
);
}
}
// File contracts/mixins/MixinRefunds.sol
pragma solidity 0.5.7;
contract MixinRefunds is
Ownable,
MixinFunds,
MixinLockCore,
MixinKeys
{
using SafeMath for uint;
// CancelAndRefund will return funds based on time remaining minus this penalty.
// This is calculated as `proRatedRefund * refundPenaltyNumerator / refundPenaltyDenominator`.
uint public refundPenaltyNumerator = 1;
uint public refundPenaltyDenominator = 10;
event CancelKey(
uint indexed tokenId,
address indexed owner,
uint refund
);
event RefundPenaltyChanged(
uint oldRefundPenaltyNumerator,
uint oldRefundPenaltyDenominator,
uint refundPenaltyNumerator,
uint refundPenaltyDenominator
);
/**
* @dev Destroys the user's key and sends a refund based on the amount of time remaining.
*/
function cancelAndRefund()
external
{
Key storage key = _getKeyFor(msg.sender);
uint refund = _getCancelAndRefundValue(msg.sender);
emit CancelKey(key.tokenId, msg.sender, refund);
// expirationTimestamp is a proxy for hasKey, setting this to `block.timestamp` instead
// of 0 so that we can still differentiate hasKey from hasValidKey.
key.expirationTimestamp = block.timestamp;
if (refund > 0) {
// Security: doing this last to avoid re-entrancy concerns
_transfer(msg.sender, refund);
}
}
/**
* Allow the owner to change the refund penalty.
*/
function updateRefundPenalty(
uint _refundPenaltyNumerator,
uint _refundPenaltyDenominator
)
external
onlyOwner
{
require(_refundPenaltyDenominator != 0, 'INVALID_RATE');
emit RefundPenaltyChanged(
refundPenaltyNumerator,
refundPenaltyDenominator,
_refundPenaltyNumerator,
_refundPenaltyDenominator
);
refundPenaltyNumerator = _refundPenaltyNumerator;
refundPenaltyDenominator = _refundPenaltyDenominator;
}
/**
* @dev Determines how much of a refund a key owner would receive if they issued
* a cancelAndRefund block.timestamp.
* Note that due to the time required to mine a tx, the actual refund amount will be lower
* than what the user reads from this call.
*/
function getCancelAndRefundValueFor(
address _owner
)
external
view
returns (uint refund)
{
return _getCancelAndRefundValue(_owner);
}
/**
* @dev Determines how much of a refund a key owner would receive if they issued
* a cancelAndRefund now.
* @param _owner The owner of the key check the refund value for.
*/
function _getCancelAndRefundValue(
address _owner
)
private
view
hasValidKey(_owner)
returns (uint refund)
{
Key storage key = _getKeyFor(_owner);
// Math: safeSub is not required since `hasValidKey` confirms timeRemaining is positive
uint timeRemaining = key.expirationTimestamp - block.timestamp;
if(timeRemaining >= expirationDuration) {
refund = keyPrice;
} else {
// Math: using safeMul in case keyPrice or timeRemaining is very large
refund = keyPrice.mul(timeRemaining) / expirationDuration;
}
uint penalty = keyPrice.mul(refundPenaltyNumerator) / refundPenaltyDenominator;
if (refund > penalty) {
// Math: safeSub is not required since the if confirms this won't underflow
refund -= penalty;
} else {
refund = 0;
}
}
}
// File openzeppelin-solidity/contracts/utils/[email protected]
pragma solidity ^0.5.0;
/**
* Utility library of inline functions on addresses
*/
library Address {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param account address of the account to check
* @return whether the target address is a contract
*/
function isContract(address account) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
// File contracts/mixins/MixinTransfer.sol
pragma solidity 0.5.7;
/**
* @title Mixin for the transfer-related functions needed to meet the ERC721
* standard.
* @author Nick Furfaro
* @dev `Mixins` are a design pattern seen in the 0x contracts. It simply
* separates logically groupings of code to ease readability.
*/
contract MixinTransfer is
MixinLockCore,
MixinKeys,
MixinApproval
{
using SafeMath for uint;
using Address for address;
event TransferFeeChanged(
uint oldTransferFeeNumerator,
uint oldTransferFeeDenominator,
uint transferFeeNumerator,
uint transferFeeDenominator
);
// 0x150b7a02 == bytes4(keccak256('onERC721Received(address,address,uint256,bytes)'))
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// The fee relative to keyPrice to charge when transfering a Key to another account
// (potentially on a 0x marketplace).
// This is calculated as `keyPrice * transferFeeNumerator / transferFeeDenominator`.
// TODO: this value is currently ignored and no fee is charged yet!
uint public transferFeeNumerator = 5;
uint public transferFeeDenominator = 100;
/**
* This is payable because at some point we want to allow the LOCK to capture a fee on 2ndary
* market transactions...
*/
function transferFrom(
address _from,
address _recipient,
uint _tokenId
)
public
payable
onlyIfAlive
hasValidKey(_from)
onlyKeyOwnerOrApproved(_tokenId)
{
require(_recipient != address(0), 'INVALID_ADDRESS');
Key storage fromKey = _getKeyFor(_from);
Key storage toKey = _getKeyFor(_recipient);
uint previousExpiration = toKey.expirationTimestamp;
if (toKey.tokenId == 0) {
toKey.tokenId = fromKey.tokenId;
}
_recordOwner(_recipient, toKey.tokenId);
if (previousExpiration <= block.timestamp) {
// The recipient did not have a key, or had a key but it expired. The new expiration is the
// sender's key expiration
toKey.expirationTimestamp = fromKey.expirationTimestamp;
} else {
// The recipient has a non expired key. We just add them the corresponding remaining time
// SafeSub is not required since the if confirms `previousExpiration - block.timestamp` cannot underflow
toKey.expirationTimestamp = fromKey
.expirationTimestamp.add(previousExpiration - block.timestamp);
}
// Effectively expiring the key for the previous owner
fromKey.expirationTimestamp = block.timestamp;
// Clear any previous approvals
_clearApproval(_tokenId);
// trigger event
emit Transfer(
_from,
_recipient,
_tokenId
);
}
/**
* @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,
uint _tokenId
)
external
payable
{
safeTransferFrom(_from, _to, _tokenId, '');
}
/**
* @notice Transfers the ownership of an NFT from one address to another address.
* When transfer is complete, this functions
* 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,uint,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,
uint _tokenId,
bytes memory _data
)
public
payable
onlyIfAlive
onlyKeyOwnerOrApproved(_tokenId)
hasValidKey(ownerOf(_tokenId))
{
transferFrom(_from, _to, _tokenId);
require(_checkOnERC721Received(_from, _to, _tokenId, _data), 'NON_COMPLIANT_ERC721_RECEIVER');
}
/**
* Allow the Lock owner to change the transfer fee.
*/
function updateTransferFee(
uint _transferFeeNumerator,
uint _transferFeeDenominator
)
external
onlyOwner
{
require(_transferFeeDenominator != 0, 'INVALID_RATE');
emit TransferFeeChanged(
transferFeeNumerator,
transferFeeDenominator,
_transferFeeNumerator,
_transferFeeDenominator
);
transferFeeNumerator = _transferFeeNumerator;
transferFeeDenominator = _transferFeeDenominator;
}
/**
* @dev Internal function to invoke `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 whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
)
internal
returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes4 retval = IERC721Receiver(to).onERC721Received(
msg.sender, from, tokenId, _data);
return (retval == _ERC721_RECEIVED);
}
}
// File contracts/PublicLock.sol
pragma solidity 0.5.7;
/**
* @title The Lock contract
* @author Julien Genestoux (unlock-protocol.com)
* Eventually: implement ERC721.
* @dev ERC165 allows our contract to be queried to determine whether it implements a given interface.
* Every ERC-721 compliant contract must implement the ERC165 interface.
* https://eips.ethereum.org/EIPS/eip-721
*/
contract PublicLock is
MixinNoFallback,
ERC721Holder,
IERC721,
ILockCore,
ERC165,
Ownable,
MixinFunds,
MixinDisableAndDestroy,
MixinLockCore,
MixinKeys,
MixinGrantKeys,
MixinApproval,
MixinLockMetadata,
MixinRefunds,
MixinPurchase,
MixinTransfer
{
constructor(
address _owner,
uint _expirationDuration,
address _tokenAddress,
uint _keyPrice,
uint _maxNumberOfKeys
)
public
MixinFunds(_tokenAddress)
MixinLockCore(_expirationDuration, _keyPrice, _maxNumberOfKeys, 1)
{
// registering the interface for erc721 with ERC165.sol using
// the ID specified in the standard: https://eips.ethereum.org/EIPS/eip-721
_registerInterface(0x80ac58cd);
// We must manually initialize Ownable.sol
Ownable.initialize(_owner);
}
}
|
Effectively expiring the key for the previous owner
|
fromKey.expirationTimestamp = block.timestamp;
| 949,569 |
[
1,
12477,
4492,
1329,
11256,
326,
498,
364,
326,
2416,
3410,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
628,
653,
18,
19519,
4921,
273,
1203,
18,
5508,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xb9fbe8fC6EB82b0b52A79C242dDB71f4D4aF6a8e/sources/contracts/shop/ProductComicV2.sol
|
* @notice Kicks off VRF request for the given user @dev Only callable by shop contract @param _to Destination address @param _amount Number of comics to assign @param _transactionId Id based by server to include in event for tracking/
|
function getComics(
address _to,
uint256 _amount,
uint256 _transactionId
) external {
if (msg.sender != shopAddress) {
revert InvalidInvoker();
}
if (numRequestsRemaining < _amount) {
revert SupplyOverflow();
}
numRequestsRemaining -= _amount;
newRequest.owner = _to;
newRequest.numComicsToSend = _amount;
keyHash,
subscriptionId,
requestConfirmations,
callbackGasLimit,
numWords
);
vrfRequestIdToRequest[requestId] = newRequest;
emit ComicPurchased(_to, _amount, requestId, _transactionId);
}
| 8,351,683 |
[
1,
47,
20642,
3397,
776,
12918,
590,
364,
326,
864,
729,
225,
5098,
4140,
635,
12122,
6835,
225,
389,
869,
10691,
1758,
225,
389,
8949,
3588,
434,
532,
2102,
358,
2683,
225,
389,
7958,
548,
3124,
2511,
635,
1438,
358,
2341,
316,
871,
364,
11093,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
565,
445,
336,
799,
2102,
12,
203,
3639,
1758,
389,
869,
16,
203,
3639,
2254,
5034,
389,
8949,
16,
203,
3639,
2254,
5034,
389,
7958,
548,
203,
565,
262,
3903,
288,
203,
3639,
309,
261,
3576,
18,
15330,
480,
12122,
1887,
13,
288,
203,
5411,
15226,
1962,
24455,
5621,
203,
3639,
289,
203,
203,
3639,
309,
261,
2107,
6421,
11429,
411,
389,
8949,
13,
288,
203,
5411,
15226,
3425,
1283,
15526,
5621,
203,
3639,
289,
203,
3639,
818,
6421,
11429,
3947,
389,
8949,
31,
203,
203,
3639,
7428,
18,
8443,
273,
389,
869,
31,
203,
3639,
7428,
18,
2107,
799,
2102,
28878,
273,
389,
8949,
31,
203,
203,
5411,
498,
2310,
16,
203,
5411,
15107,
16,
203,
5411,
590,
11269,
1012,
16,
203,
5411,
1348,
27998,
3039,
16,
203,
5411,
818,
7363,
203,
3639,
11272,
203,
203,
3639,
20466,
15493,
774,
691,
63,
2293,
548,
65,
273,
7428,
31,
203,
3639,
3626,
1286,
335,
10262,
343,
8905,
24899,
869,
16,
389,
8949,
16,
14459,
16,
389,
7958,
548,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2020-10-21
*/
pragma solidity ^0.5.8;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount)external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender,address recipient,uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner,address indexed spender,uint256 value);
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender)
public
view
returns (uint256)
{
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
function increaseAllowance(address spender, uint256 addedValue)
public
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].add(addedValue)
);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue)
public
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(
subtractedValue,
"ERC20: decreased allowance below zero"
)
);
return true;
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(
amount,
"ERC20: transfer amount exceeds balance"
);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(
amount,
"ERC20: burn amount exceeds balance"
);
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(
address owner,
address spender,
uint256 amount
) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(
string memory name,
string memory symbol,
uint8 decimals
) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function 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;
}
}
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) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
}
library Address {
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash
= 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly {
codehash := extcodehash(account)
}
return (codehash != 0x0 && codehash != accountHash);
}
}
library SafeERC20 {
using SafeMath for 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 {
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 callOptionalReturn(IERC20 token, bytes memory data) private {
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 (block.number > 0) { //injected CONTRACT AFFECTED BY MINERS
// Return data is optional
// solhint-disable-next-line max-line-length
require(
abi.decode(returndata, (bool)),
"SafeERC20: ERC20 operation did not succeed"
);
}
}
}
contract GNB is ERC20, ERC20Detailed {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
constructor(address _winner) public ERC20Detailed("Global Newmedia Bank", "GNB", 18) {
_mint(_winner, 100000000000 * 1e18);
}
}
|
solhint-disable-next-line avoid-low-level-calls Return data is optional solhint-disable-next-line max-line-length
|
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
require(
abi.decode(returndata, (bool)),
"SafeERC20: ERC20 operation did not succeed"
);
}
| 1,778,049 |
[
1,
18281,
11317,
17,
8394,
17,
4285,
17,
1369,
4543,
17,
821,
17,
2815,
17,
12550,
2000,
501,
353,
3129,
3704,
11317,
17,
8394,
17,
4285,
17,
1369,
943,
17,
1369,
17,
2469,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
745,
6542,
990,
12,
45,
654,
39,
3462,
1147,
16,
1731,
3778,
501,
13,
3238,
288,
203,
3639,
2583,
12,
2867,
12,
2316,
2934,
291,
8924,
9334,
315,
9890,
654,
39,
3462,
30,
745,
358,
1661,
17,
16351,
8863,
203,
203,
3639,
261,
6430,
2216,
16,
1731,
3778,
327,
892,
13,
273,
1758,
12,
2316,
2934,
1991,
12,
892,
1769,
203,
3639,
2583,
12,
4768,
16,
315,
9890,
654,
39,
3462,
30,
4587,
17,
2815,
745,
2535,
8863,
203,
203,
5411,
2583,
12,
203,
7734,
24126,
18,
3922,
12,
2463,
892,
16,
261,
6430,
13,
3631,
203,
7734,
315,
9890,
654,
39,
3462,
30,
4232,
39,
3462,
1674,
5061,
486,
12897,
6,
203,
5411,
11272,
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
] |
pragma solidity 0.5.16;
interface ICurveMetaPool {
function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy) external returns (uint256);
}
interface IUniswapV2Router02 {
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface ISavingsManager {
/** @dev Admin privs */
function withdrawUnallocatedInterest(address _mAsset, address _recipient) external;
/** @dev Liquidator */
function depositLiquidation(address _mAsset, uint256 _liquidation) external;
/** @dev Public privs */
function collectAndDistributeInterest(address _mAsset) external;
}
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 InitializableModuleKeys {
// Governance // Phases
bytes32 internal KEY_GOVERNANCE; // 2.x
bytes32 internal KEY_STAKING; // 1.2
bytes32 internal KEY_PROXY_ADMIN; // 1.0
// mStable
bytes32 internal KEY_ORACLE_HUB; // 1.2
bytes32 internal KEY_MANAGER; // 1.2
bytes32 internal KEY_RECOLLATERALISER; // 2.x
bytes32 internal KEY_META_TOKEN; // 1.1
bytes32 internal KEY_SAVINGS_MANAGER; // 1.0
/**
* @dev Initialize function for upgradable proxy contracts. This function should be called
* via Proxy to initialize constants in the Proxy contract.
*/
function _initialize() internal {
// keccak256() values are evaluated only once at the time of this function call.
// Hence, no need to assign hard-coded values to these variables.
KEY_GOVERNANCE = keccak256("Governance");
KEY_STAKING = keccak256("Staking");
KEY_PROXY_ADMIN = keccak256("ProxyAdmin");
KEY_ORACLE_HUB = keccak256("OracleHub");
KEY_MANAGER = keccak256("Manager");
KEY_RECOLLATERALISER = keccak256("Recollateraliser");
KEY_META_TOKEN = keccak256("MetaToken");
KEY_SAVINGS_MANAGER = keccak256("SavingsManager");
}
}
interface INexus {
function governor() external view returns (address);
function getModule(bytes32 key) external view returns (address);
function proposeModule(bytes32 _key, address _addr) external;
function cancelProposedModule(bytes32 _key) external;
function acceptProposedModule(bytes32 _key) external;
function acceptProposedModules(bytes32[] calldata _keys) external;
function requestLockModule(bytes32 _key) external;
function cancelLockModule(bytes32 _key) external;
function lockModule(bytes32 _key) external;
}
contract InitializableModule is InitializableModuleKeys {
INexus public nexus;
/**
* @dev Modifier to allow function calls only from the Governor.
*/
modifier onlyGovernor() {
require(msg.sender == _governor(), "Only governor can execute");
_;
}
/**
* @dev Modifier to allow function calls only from the Governance.
* Governance is either Governor address or Governance address.
*/
modifier onlyGovernance() {
require(
msg.sender == _governor() || msg.sender == _governance(),
"Only governance can execute"
);
_;
}
/**
* @dev Modifier to allow function calls only from the ProxyAdmin.
*/
modifier onlyProxyAdmin() {
require(
msg.sender == _proxyAdmin(), "Only ProxyAdmin can execute"
);
_;
}
/**
* @dev Modifier to allow function calls only from the Manager.
*/
modifier onlyManager() {
require(msg.sender == _manager(), "Only manager can execute");
_;
}
/**
* @dev Initialization function for upgradable proxy contracts
* @param _nexus Nexus contract address
*/
function _initialize(address _nexus) internal {
require(_nexus != address(0), "Nexus address is zero");
nexus = INexus(_nexus);
InitializableModuleKeys._initialize();
}
/**
* @dev Returns Governor address from the Nexus
* @return Address of Governor Contract
*/
function _governor() internal view returns (address) {
return nexus.governor();
}
/**
* @dev Returns Governance Module address from the Nexus
* @return Address of the Governance (Phase 2)
*/
function _governance() internal view returns (address) {
return nexus.getModule(KEY_GOVERNANCE);
}
/**
* @dev Return Staking Module address from the Nexus
* @return Address of the Staking Module contract
*/
function _staking() internal view returns (address) {
return nexus.getModule(KEY_STAKING);
}
/**
* @dev Return ProxyAdmin Module address from the Nexus
* @return Address of the ProxyAdmin Module contract
*/
function _proxyAdmin() internal view returns (address) {
return nexus.getModule(KEY_PROXY_ADMIN);
}
/**
* @dev Return MetaToken Module address from the Nexus
* @return Address of the MetaToken Module contract
*/
function _metaToken() internal view returns (address) {
return nexus.getModule(KEY_META_TOKEN);
}
/**
* @dev Return OracleHub Module address from the Nexus
* @return Address of the OracleHub Module contract
*/
function _oracleHub() internal view returns (address) {
return nexus.getModule(KEY_ORACLE_HUB);
}
/**
* @dev Return Manager Module address from the Nexus
* @return Address of the Manager Module contract
*/
function _manager() internal view returns (address) {
return nexus.getModule(KEY_MANAGER);
}
/**
* @dev Return SavingsManager Module address from the Nexus
* @return Address of the SavingsManager Module contract
*/
function _savingsManager() internal view returns (address) {
return nexus.getModule(KEY_SAVINGS_MANAGER);
}
/**
* @dev Return Recollateraliser Module address from the Nexus
* @return Address of the Recollateraliser Module contract (Phase 2)
*/
function _recollateraliser() internal view returns (address) {
return nexus.getModule(KEY_RECOLLATERALISER);
}
}
contract ILiquidator {
function createLiquidation(
address _integration,
address _sellToken,
address _bAsset,
int128 _curvePosition,
address[] calldata _uniswapPath,
uint256 _trancheAmount
)
external;
function updateBasset(
address _integration,
address _bAsset,
int128 _curvePosition,
address[] calldata _uniswapPath,
uint256 _trancheAmount
)
external;
function deleteLiquidation(address _integration) external;
function triggerLiquidation(address _integration) external;
}
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
library StableMath {
using SafeMath for uint256;
/**
* @dev Scaling unit for use in specific calculations,
* where 1 * 10**18, or 1e18 represents a unit '1'
*/
uint256 private constant FULL_SCALE = 1e18;
/**
* @notice Token Ratios are used when converting between units of bAsset, mAsset and MTA
* Reasoning: Takes into account token decimals, and difference in base unit (i.e. grams to Troy oz for gold)
* @dev bAsset ratio unit for use in exact calculations,
* where (1 bAsset unit * bAsset.ratio) / ratioScale == x mAsset unit
*/
uint256 private constant RATIO_SCALE = 1e8;
/**
* @dev Provides an interface to the scaling unit
* @return Scaling unit (1e18 or 1 * 10**18)
*/
function getFullScale() internal pure returns (uint256) {
return FULL_SCALE;
}
/**
* @dev Provides an interface to the ratio unit
* @return Ratio scale unit (1e8 or 1 * 10**8)
*/
function getRatioScale() internal pure returns (uint256) {
return RATIO_SCALE;
}
/**
* @dev Scales a given integer to the power of the full scale.
* @param x Simple uint256 to scale
* @return Scaled value a to an exact number
*/
function scaleInteger(uint256 x)
internal
pure
returns (uint256)
{
return x.mul(FULL_SCALE);
}
/***************************************
PRECISE ARITHMETIC
****************************************/
/**
* @dev Multiplies two precise units, and then truncates by the full scale
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncate(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
return mulTruncateScale(x, y, FULL_SCALE);
}
/**
* @dev Multiplies two precise units, and then truncates by the given scale. For example,
* when calculating 90% of 10e18, (10e18 * 9e17) / 1e18 = (9e36) / 1e18 = 9e18
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @param scale Scale unit
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncateScale(uint256 x, uint256 y, uint256 scale)
internal
pure
returns (uint256)
{
// e.g. assume scale = fullScale
// z = 10e18 * 9e17 = 9e36
uint256 z = x.mul(y);
// return 9e38 / 1e18 = 9e18
return z.div(scale);
}
/**
* @dev Multiplies two precise units, and then truncates by the full scale, rounding up the result
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit, rounded up to the closest base unit.
*/
function mulTruncateCeil(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
// e.g. 8e17 * 17268172638 = 138145381104e17
uint256 scaled = x.mul(y);
// e.g. 138145381104e17 + 9.99...e17 = 138145381113.99...e17
uint256 ceil = scaled.add(FULL_SCALE.sub(1));
// e.g. 13814538111.399...e18 / 1e18 = 13814538111
return ceil.div(FULL_SCALE);
}
/**
* @dev Precisely divides two units, by first scaling the left hand operand. Useful
* for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17)
* @param x Left hand input to division
* @param y Right hand input to division
* @return Result after multiplying the left operand by the scale, and
* executing the division on the right hand input.
*/
function divPrecisely(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
// e.g. 8e18 * 1e18 = 8e36
uint256 z = x.mul(FULL_SCALE);
// e.g. 8e36 / 10e18 = 8e17
return z.div(y);
}
/***************************************
RATIO FUNCS
****************************************/
/**
* @dev Multiplies and truncates a token ratio, essentially flooring the result
* i.e. How much mAsset is this bAsset worth?
* @param x Left hand operand to multiplication (i.e Exact quantity)
* @param ratio bAsset ratio
* @return Result after multiplying the two inputs and then dividing by the ratio scale
*/
function mulRatioTruncate(uint256 x, uint256 ratio)
internal
pure
returns (uint256 c)
{
return mulTruncateScale(x, ratio, RATIO_SCALE);
}
/**
* @dev Multiplies and truncates a token ratio, rounding up the result
* i.e. How much mAsset is this bAsset worth?
* @param x Left hand input to multiplication (i.e Exact quantity)
* @param ratio bAsset ratio
* @return Result after multiplying the two inputs and then dividing by the shared
* ratio scale, rounded up to the closest base unit.
*/
function mulRatioTruncateCeil(uint256 x, uint256 ratio)
internal
pure
returns (uint256)
{
// e.g. How much mAsset should I burn for this bAsset (x)?
// 1e18 * 1e8 = 1e26
uint256 scaled = x.mul(ratio);
// 1e26 + 9.99e7 = 100..00.999e8
uint256 ceil = scaled.add(RATIO_SCALE.sub(1));
// return 100..00.999e8 / 1e8 = 1e18
return ceil.div(RATIO_SCALE);
}
/**
* @dev Precisely divides two ratioed units, by first scaling the left hand operand
* i.e. How much bAsset is this mAsset worth?
* @param x Left hand operand in division
* @param ratio bAsset ratio
* @return Result after multiplying the left operand by the scale, and
* executing the division on the right hand input.
*/
function divRatioPrecisely(uint256 x, uint256 ratio)
internal
pure
returns (uint256 c)
{
// e.g. 1e14 * 1e8 = 1e22
uint256 y = x.mul(RATIO_SCALE);
// return 1e22 / 1e12 = 1e10
return y.div(ratio);
}
/***************************************
HELPERS
****************************************/
/**
* @dev Calculates minimum of two numbers
* @param x Left hand input
* @param y Right hand input
* @return Minimum of the two inputs
*/
function min(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
return x > y ? y : x;
}
/**
* @dev Calculated maximum of two numbers
* @param x Left hand input
* @param y Right hand input
* @return Maximum of the two inputs
*/
function max(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
return x > y ? x : y;
}
/**
* @dev Clamps a value to an upper bound
* @param x Left hand input
* @param upperBound Maximum possible value to return
* @return Input x clamped to a maximum value, upperBound
*/
function clamp(uint256 x, uint256 upperBound)
internal
pure
returns (uint256)
{
return x > upperBound ? upperBound : x;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev 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.
*/
/**
* @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");
}
}
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");
}
}
}
library MassetHelpers {
using StableMath for uint256;
using SafeMath for uint256;
using SafeERC20 for IERC20;
function transferTokens(
address _sender,
address _recipient,
address _basset,
bool _erc20TransferFeeCharged,
uint256 _qty
)
internal
returns (uint256 receivedQty)
{
receivedQty = _qty;
if(_erc20TransferFeeCharged) {
uint256 balBefore = IERC20(_basset).balanceOf(_recipient);
IERC20(_basset).safeTransferFrom(_sender, _recipient, _qty);
uint256 balAfter = IERC20(_basset).balanceOf(_recipient);
receivedQty = StableMath.min(_qty, balAfter.sub(balBefore));
} else {
IERC20(_basset).safeTransferFrom(_sender, _recipient, _qty);
}
}
function safeInfiniteApprove(address _asset, address _spender)
internal
{
IERC20(_asset).safeApprove(_spender, 0);
IERC20(_asset).safeApprove(_spender, uint256(-1));
}
}
/**
* @title Liquidator
* @author Stability Labs Pty. Ltd.
* @notice The Liquidator allows rewards to be swapped for another token
* and returned to a calling contract
* @dev VERSION: 1.0
* DATE: 2020-10-13
*/
contract Liquidator is
ILiquidator,
Initializable,
InitializableModule
{
using SafeMath for uint256;
using SafeERC20 for IERC20;
event LiquidationModified(address indexed integration);
event LiquidationEnded(address indexed integration);
event Liquidated(address indexed sellToken, address mUSD, uint256 mUSDAmount, address buyToken);
address public mUSD;
ICurveMetaPool public curve;
IUniswapV2Router02 public uniswap;
uint256 private interval = 7 days;
mapping(address => Liquidation) public liquidations;
struct Liquidation {
address sellToken;
address bAsset;
int128 curvePosition;
address[] uniswapPath;
uint256 lastTriggered;
uint256 trancheAmount; // The amount of bAsset units to buy each week, with token decimals
}
function initialize(
address _nexus,
address _uniswap,
address _curve,
address _mUSD
)
external
initializer
{
InitializableModule._initialize(_nexus);
require(_uniswap != address(0), "Invalid uniswap address");
uniswap = IUniswapV2Router02(_uniswap);
require(_curve != address(0), "Invalid curve address");
curve = ICurveMetaPool(_curve);
require(_mUSD != address(0), "Invalid mUSD address");
mUSD = _mUSD;
}
/***************************************
GOVERNANCE
****************************************/
/**
* @dev Create a liquidation
* @param _integration The integration contract address from which to receive sellToken
* @param _sellToken Token harvested from the integration contract
* @param _bAsset The asset to buy on Uniswap
* @param _curvePosition Position of the bAsset in Curves MetaPool
* @param _uniswapPath The Uniswap path as an array of addresses e.g. [COMP, WETH, DAI]
* @param _trancheAmount The amount of bAsset units to buy in each weekly tranche
*/
function createLiquidation(
address _integration,
address _sellToken,
address _bAsset,
int128 _curvePosition,
address[] calldata _uniswapPath,
uint256 _trancheAmount
)
external
onlyGovernance
{
require(liquidations[_integration].sellToken == address(0), "Liquidation exists for this bAsset");
require(
_integration != address(0) &&
_sellToken != address(0) &&
_bAsset != address(0) &&
_uniswapPath.length >= 2,
"Invalid inputs"
);
require(_validUniswapPath(_sellToken, _bAsset, _uniswapPath), "Invalid uniswap path");
liquidations[_integration] = Liquidation({
sellToken: _sellToken,
bAsset: _bAsset,
curvePosition: _curvePosition,
uniswapPath: _uniswapPath,
lastTriggered: 0,
trancheAmount: _trancheAmount
});
emit LiquidationModified(_integration);
}
/**
* @dev Update a liquidation
* @param _integration The integration contract in question
* @param _bAsset New asset to buy on Uniswap
* @param _curvePosition Position of the bAsset in Curves MetaPool
* @param _uniswapPath The Uniswap path as an array of addresses e.g. [COMP, WETH, DAI]
* @param _trancheAmount The amount of bAsset units to buy in each weekly tranche
*/
function updateBasset(
address _integration,
address _bAsset,
int128 _curvePosition,
address[] calldata _uniswapPath,
uint256 _trancheAmount
)
external
onlyGovernance
{
Liquidation memory liquidation = liquidations[_integration];
address oldBasset = liquidation.bAsset;
require(oldBasset != address(0), "Liquidation does not exist");
require(_bAsset != address(0), "Invalid bAsset");
require(_validUniswapPath(liquidation.sellToken, _bAsset, _uniswapPath), "Invalid uniswap path");
liquidations[_integration].bAsset = _bAsset;
liquidations[_integration].curvePosition = _curvePosition;
liquidations[_integration].uniswapPath = _uniswapPath;
liquidations[_integration].trancheAmount = _trancheAmount;
emit LiquidationModified(_integration);
}
/**
* @dev Validates a given uniswap path - valid if sellToken at position 0 and bAsset at end
* @param _sellToken Token harvested from the integration contract
* @param _bAsset New asset to buy on Uniswap
* @param _uniswapPath The Uniswap path as an array of addresses e.g. [COMP, WETH, DAI]
*/
function _validUniswapPath(address _sellToken, address _bAsset, address[] memory _uniswapPath)
internal
pure
returns (bool)
{
uint256 len = _uniswapPath.length;
return _sellToken == _uniswapPath[0] && _bAsset == _uniswapPath[len-1];
}
/**
* @dev Delete a liquidation
*/
function deleteLiquidation(address _integration)
external
onlyGovernance
{
Liquidation memory liquidation = liquidations[_integration];
require(liquidation.bAsset != address(0), "Liquidation does not exist");
delete liquidations[_integration];
emit LiquidationEnded(_integration);
}
/***************************************
LIQUIDATION
****************************************/
/**
* @dev Triggers a liquidation, flow (once per week):
* - Sells $COMP for $USDC (or other) on Uniswap (up to trancheAmount)
* - Sell USDC for mUSD on Curve
* - Send to SavingsManager
* @param _integration Integration for which to trigger liquidation
*/
function triggerLiquidation(address _integration)
external
{
Liquidation memory liquidation = liquidations[_integration];
address bAsset = liquidation.bAsset;
require(bAsset != address(0), "Liquidation does not exist");
require(block.timestamp > liquidation.lastTriggered.add(interval), "Must wait for interval");
liquidations[_integration].lastTriggered = block.timestamp;
// Cache variables
address sellToken = liquidation.sellToken;
address[] memory uniswapPath = liquidation.uniswapPath;
// 1. Transfer sellTokens from integration contract if there are some
// Assumes infinite approval
uint256 integrationBal = IERC20(sellToken).balanceOf(_integration);
if (integrationBal > 0) {
IERC20(sellToken).safeTransferFrom(_integration, address(this), integrationBal);
}
// 2. Get the amount to sell based on the tranche amount we want to buy
// Check contract balance
uint256 sellTokenBal = IERC20(sellToken).balanceOf(address(this));
require(sellTokenBal > 0, "No sell tokens to liquidate");
require(liquidation.trancheAmount > 0, "Liquidation has been paused");
// Calc amounts for max tranche
uint[] memory amountsIn = uniswap.getAmountsIn(liquidation.trancheAmount, uniswapPath);
uint256 sellAmount = amountsIn[0];
if (sellTokenBal < sellAmount) {
sellAmount = sellTokenBal;
}
// 3. Make the swap
// 3.1 Approve Uniswap and make the swap
IERC20(sellToken).safeApprove(address(uniswap), 0);
IERC20(sellToken).safeApprove(address(uniswap), sellAmount);
// 3.2. Make the sale > https://uniswap.org/docs/v2/smart-contracts/router02/#swapexacttokensfortokens
uniswap.swapExactTokensForTokens(
sellAmount,
0,
uniswapPath,
address(this),
block.timestamp.add(1800)
);
uint256 bAssetBal = IERC20(bAsset).balanceOf(address(this));
// 3.3. Trade on Curve
IERC20(bAsset).safeApprove(address(curve), 0);
IERC20(bAsset).safeApprove(address(curve), bAssetBal);
uint256 purchased = curve.exchange_underlying(liquidation.curvePosition, 0, bAssetBal, 0);
// 4.0. Send to SavingsManager
address savings = _savingsManager();
IERC20(mUSD).safeApprove(savings, 0);
IERC20(mUSD).safeApprove(savings, purchased);
ISavingsManager(savings).depositLiquidation(mUSD, purchased);
emit Liquidated(sellToken, mUSD, purchased, bAsset);
}
}
|
* @dev Validates a given uniswap path - valid if sellToken at position 0 and bAsset at end @param _sellToken Token harvested from the integration contract @param _bAsset New asset to buy on Uniswap @param _uniswapPath The Uniswap path as an array of addresses e.g. [COMP, WETH, DAI]/
|
function _validUniswapPath(address _sellToken, address _bAsset, address[] memory _uniswapPath)
internal
pure
returns (bool)
{
uint256 len = _uniswapPath.length;
return _sellToken == _uniswapPath[0] && _bAsset == _uniswapPath[len-1];
}
| 552,329 |
[
1,
9594,
279,
864,
640,
291,
91,
438,
589,
300,
923,
309,
357,
80,
1345,
622,
1754,
374,
471,
324,
6672,
622,
679,
225,
389,
87,
1165,
1345,
3155,
17895,
90,
3149,
628,
326,
12040,
6835,
225,
389,
70,
6672,
1166,
3310,
358,
30143,
603,
1351,
291,
91,
438,
225,
389,
318,
291,
91,
438,
743,
1021,
1351,
291,
91,
438,
589,
487,
392,
526,
434,
6138,
425,
18,
75,
18,
306,
10057,
16,
678,
1584,
44,
16,
463,
18194,
18537,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
877,
984,
291,
91,
438,
743,
12,
2867,
389,
87,
1165,
1345,
16,
1758,
389,
70,
6672,
16,
1758,
8526,
3778,
389,
318,
291,
91,
438,
743,
13,
203,
3639,
2713,
203,
3639,
16618,
203,
3639,
1135,
261,
6430,
13,
203,
565,
288,
203,
3639,
2254,
5034,
562,
273,
389,
318,
291,
91,
438,
743,
18,
2469,
31,
203,
3639,
327,
389,
87,
1165,
1345,
422,
389,
318,
291,
91,
438,
743,
63,
20,
65,
597,
389,
70,
6672,
422,
389,
318,
291,
91,
438,
743,
63,
1897,
17,
21,
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
] |
./full_match/43113/0x392FA11446A6519DD93188E17f24CF3e54aDD1f0/sources/contracts/MasterChefV2.sol
|
Safe ara transfer function, just in case if rounding error causes pool to not have enough ARAs.
|
function safeAraTransfer(address _to, uint256 _amount) internal {
uint256 araBal = ara.balanceOf(address(this));
bool transferSuccess = false;
if (_amount > araBal) {
transferSuccess = ara.transfer(_to, araBal);
transferSuccess = ara.transfer(_to, _amount);
}
require(transferSuccess, "safeAraTransfer: transfer failed");
}
| 7,153,566 |
[
1,
9890,
279,
354,
7412,
445,
16,
2537,
316,
648,
309,
13885,
555,
14119,
2845,
358,
486,
1240,
7304,
6052,
1463,
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
] |
[
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,
4183,
37,
354,
5912,
12,
2867,
389,
869,
16,
2254,
5034,
389,
8949,
13,
2713,
288,
203,
3639,
2254,
5034,
279,
354,
38,
287,
273,
279,
354,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
1426,
7412,
4510,
273,
629,
31,
203,
3639,
309,
261,
67,
8949,
405,
279,
354,
38,
287,
13,
288,
203,
5411,
7412,
4510,
273,
279,
354,
18,
13866,
24899,
869,
16,
279,
354,
38,
287,
1769,
203,
5411,
7412,
4510,
273,
279,
354,
18,
13866,
24899,
869,
16,
389,
8949,
1769,
203,
3639,
289,
203,
3639,
2583,
12,
13866,
4510,
16,
315,
4626,
37,
354,
5912,
30,
7412,
2535,
8863,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xCA8586d15187D31eeF8B006Fc298e0F4fB2519fA/sources/CannathaiNFTShop.sol
|
* @notice set free mint number by address/
|
function setFreeMintNumberByAddress(
address _user,
uint256 _number
) public onlyRole(DEFAULT_ADMIN_ROLE) {
freeMintNumberByAddress[_user] = _number;
emit FreeMintNumberSet(_user, _number);
}
| 2,763,461 |
[
1,
542,
4843,
312,
474,
1300,
635,
1758,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
444,
9194,
49,
474,
1854,
858,
1887,
12,
203,
3639,
1758,
389,
1355,
16,
203,
3639,
2254,
5034,
389,
2696,
203,
565,
262,
1071,
1338,
2996,
12,
5280,
67,
15468,
67,
16256,
13,
288,
203,
3639,
4843,
49,
474,
1854,
858,
1887,
63,
67,
1355,
65,
273,
389,
2696,
31,
203,
3639,
3626,
15217,
49,
474,
1854,
694,
24899,
1355,
16,
389,
2696,
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
] |
./full_match/80001/0xA5Ae44cc150CC95Fb6362Bc83AdEA7F200aF315e/sources/project_/contracts/MiniGames.sol
|
1% for each user lose
|
uint256 public ownerBpc = 100;
| 857,305 |
[
1,
21,
9,
364,
1517,
729,
29612,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
225,
2254,
5034,
1071,
3410,
38,
2436,
273,
2130,
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
] |
./full_match/1/0x8CC23A8CFE803f8E9Ee978bD7F9D343eeA0Cf82F/sources/src/LockRewards.sol
|
* @notice Implements internal deposit logic @dev The deposit is always done in name of caller @param amount: the amount of lock tokens to deposit @param lock: how many epochs to lock/ Increase lockEpochs for user This is done to save gas in case of a relock Also, emits a different event for deposit or relock
|
function _deposit(uint256 amount, uint256 lock) internal {
IERC20 lToken = IERC20(lockToken);
uint256 oldLockEpochs = accounts[msg.sender].lockEpochs;
accounts[msg.sender].lockEpochs += lock;
accounts[msg.sender].lockStart = block.timestamp;
if (amount > 0) {
lToken.safeTransferFrom(msg.sender, address(this), amount);
totalAssets += amount;
accounts[msg.sender].balance += amount;
emit Deposit(msg.sender, amount, lockDuration);
emit Relock(msg.sender, accounts[msg.sender].balance, lockDuration);
}
uint256 next = epochs[_currEpoch].isSet ? _currEpoch + 1 : _currEpoch;
if (!epochs[_currEpoch].isSet || oldLockEpochs == 0) {
lockBoundary = accounts[msg.sender].lockEpochs;
lockBoundary = accounts[msg.sender].lockEpochs - 1;
}
uint256 newBalance = accounts[msg.sender].balance;
for (uint256 i = 0; i < lockBoundary;) {
epochs[i + next].totalLocked += newBalance - epochs[i + next].balanceLocked[msg.sender];
epochs[i + next].balanceLocked[msg.sender] = newBalance;
unchecked {
++i;
}
}
}
| 9,625,234 |
[
1,
17516,
2713,
443,
1724,
4058,
282,
1021,
443,
1724,
353,
3712,
2731,
316,
508,
434,
4894,
282,
3844,
30,
326,
3844,
434,
2176,
2430,
358,
443,
1724,
282,
2176,
30,
3661,
4906,
25480,
358,
2176,
19,
657,
11908,
2176,
14638,
87,
364,
729,
1220,
353,
2731,
358,
1923,
16189,
316,
648,
434,
279,
283,
739,
8080,
16,
24169,
279,
3775,
871,
364,
443,
1724,
578,
283,
739,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
389,
323,
1724,
12,
11890,
5034,
3844,
16,
2254,
5034,
2176,
13,
2713,
288,
203,
3639,
467,
654,
39,
3462,
328,
1345,
273,
467,
654,
39,
3462,
12,
739,
1345,
1769,
203,
203,
3639,
2254,
5034,
1592,
2531,
14638,
87,
273,
9484,
63,
3576,
18,
15330,
8009,
739,
14638,
87,
31,
203,
3639,
9484,
63,
3576,
18,
15330,
8009,
739,
14638,
87,
1011,
2176,
31,
203,
3639,
9484,
63,
3576,
18,
15330,
8009,
739,
1685,
273,
1203,
18,
5508,
31,
203,
203,
3639,
309,
261,
8949,
405,
374,
13,
288,
203,
5411,
328,
1345,
18,
4626,
5912,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
3844,
1769,
203,
5411,
2078,
10726,
1011,
3844,
31,
203,
5411,
9484,
63,
3576,
18,
15330,
8009,
12296,
1011,
3844,
31,
203,
203,
5411,
3626,
4019,
538,
305,
12,
3576,
18,
15330,
16,
3844,
16,
2176,
5326,
1769,
203,
5411,
3626,
4275,
975,
12,
3576,
18,
15330,
16,
9484,
63,
3576,
18,
15330,
8009,
12296,
16,
2176,
5326,
1769,
203,
3639,
289,
203,
203,
3639,
2254,
5034,
1024,
273,
25480,
63,
67,
17016,
14638,
8009,
291,
694,
692,
389,
17016,
14638,
397,
404,
294,
389,
17016,
14638,
31,
203,
203,
3639,
309,
16051,
28530,
63,
67,
17016,
14638,
8009,
291,
694,
747,
1592,
2531,
14638,
87,
422,
374,
13,
288,
203,
5411,
2176,
11941,
273,
9484,
63,
3576,
18,
15330,
8009,
739,
14638,
87,
31,
203,
5411,
2176,
11941,
273,
9484,
63,
3576,
18,
15330,
8009,
739,
14638,
87,
300,
404,
31,
203,
3639,
289,
2
] |
./full_match/137/0x56F00B4009F9dF13864aF8D9C64eC39F4EC8d4C3/sources/contracts/FantasyDoge.sol
|
0.1% swap tokens amount
|
swapTokensAtAmount = totalSupply * 1 / 1000;
| 4,730,685 |
[
1,
20,
18,
21,
9,
7720,
2430,
3844,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
3639,
7720,
5157,
861,
6275,
273,
2078,
3088,
1283,
380,
404,
342,
4336,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x78CF6efA8A1febaDbb86442683232773Ef073da6/sources/browser/KASSIAHOMEReserves.sol
|
** Gov Events ***/* @notice Event emitted when pendingGov is changed/* @notice Event emitted when gov is changed/* @notice Event emitted when rebaser is changed/
|
modifier onlyGov() {
require(msg.sender == gov);
_;
}
constructor(
address reserveToken_,
address kassiahomeAddress_
)
public
| 9,709,024 |
[
1,
43,
1527,
9043,
342,
225,
2587,
17826,
1347,
4634,
43,
1527,
353,
3550,
19,
225,
2587,
17826,
1347,
31841,
353,
3550,
19,
225,
2587,
17826,
1347,
283,
9157,
264,
353,
3550,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
9606,
1338,
43,
1527,
1435,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
31841,
1769,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
3885,
12,
203,
3639,
1758,
20501,
1345,
67,
16,
203,
3639,
1758,
417,
428,
1155,
8712,
1887,
67,
203,
565,
262,
203,
3639,
1071,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
// import files
// import "./Seat.sol"; //deprecated
// import "@bokkypoobah/BokkyPooBahsDateTimeLibrary/contracts/BokkyPooBahsDateTimeLibrary.sol";
import "./Ticket.sol";
//General _variable convention is to leave the regular variable names for storage variables
// prefacing with _ is normally used to differentiate the temporary variable from the permanent.
contract TicketBookingSystem{
address payable private owner; // owner of the event
uint32 private available_seats; // number of available seats in event
Seat[] private seats; // seat list
Ticket private ticket; // ticket for event
bool private cancelled; // bool for preventing double refunding
// seat struct with all the informations needed in a seat
struct Seat {
string title;
string seatURL;
uint64 startTime;
uint128 price;
uint32 seatRow;
uint32 seatNumber;
uint256 ticketID;
}
constructor(string memory title_, uint256 time_, uint32 available_seats_, uint128 price_) {
//Create non-existing seat 0 to store information about the event:
Seat memory _seat = Seat({
title: title_,
seatURL: "hurrdurr.dk",
startTime: time_,
price: price_,
seatRow: 0,
seatNumber: 0,
ticketID: 0});
// push 0 seat to seat list
seats.push(_seat);
available_seats = available_seats_;
owner = payable(msg.sender);
//Ticket has been set up with ownage so owner address is automatically this smart contract
ticket = new Ticket(title_, "TCK", seats[0].startTime);
}
// Define a modifier for a function that only the seller can call
modifier onlyOwner() {
require( msg.sender == owner , "Only owner can call this.");
_;
}
//TODO: What if price isn't always the price of the defaut seat?
// ckecks if enough ethereum is paid for the ticket
modifier paymentValid() {
require (msg.value >= seats[0].price, "Not enough Ethereum paid");
_;
}
function buy(uint32 _seatRow, uint32 _seatNumber) public payable paymentValid{
//"Require()" will return the money to sender upon evaluating to false which is great
// checks if event is already full
require(seats.length < available_seats, "Event full");
// ckecks if seat is already taken. (ticket owned by another person)
require(check_available_seats(_seatRow, _seatNumber), "This seat is taken");
// mint new ticket
uint256 newTicket = ticket.mint(msg.sender);
// creates seat
Seat memory _seat = Seat({
title: seats[0].title,
seatURL: "google.com",
startTime: seats[0].startTime,
price: seats[0].price,
seatRow: _seatRow,
seatNumber: _seatNumber,
ticketID: newTicket});
//transfer the ether and push seat to seat list
owner.transfer(_seat.price);
seats.push(_seat);
}
// refund the tickets. (only owner of event can refund the tickets)
function refund() public onlyOwner{
require(cancelled == false, "Event already cancelled, tickets can't be refunded twice");
//Starts at 1 in order to not refund the "test seat" at [0].
for(uint32 i=1; i < seats.length; i++){
(address payable _to, bool _valid) = ticket.verify(seats[i].ticketID);
//Is this sufficient since only owner has access to the function?
require(_valid);
_to.transfer(seats[i].price);
}
// set available seats to zero so no further tickets can be bought
available_seats = 0;
cancelled = true;
}
function check_available_seats(uint32 _seatRow, uint32 _seatNumber) private view returns (bool){
//Check if seat in seats[] already, if not:
//Mint TICKET for msg.sender
//Create seat with owner linked to TICKET
uint32 _numTakenSeats = uint32(seats.length);
bool _seatFree = true;
for(uint32 i=0; i < _numTakenSeats; i++){
if (seats[i].seatNumber == _seatNumber && seats[i].seatRow == _seatRow){
_seatFree = false;
}
}
return _seatFree;
}
//CALLED BY BUYER WHEN BUYING TICKET THAT IS FOR SALE
//require is used as actively as possible as that returns msg.value if it fails.
function tradeTicket(uint256 _tokenID) public payable{
// check that owner of ticket dont buy his/her own ticket
require( msg.sender != ticket.ownerOf(_tokenID) , "Owner can't buy own token.");
// get information out of mapping in ticket contract with getMarketplaceInfo
(uint256 _price, address _reserved,bool _exists) = ticket.getMarketplaceInfo(_tokenID);
// check if ticket is on sale
require(_exists, "Token requested is not for sale.");
//Not the most readable thing in the world but this checks that the token isn't reserved for someone else
require(_reserved == msg.sender || _reserved == ticket.ownerOf(_tokenID), "You don't have permission to buy this token.");
// if enough ether is paid
require (msg.value >= _price, "Not enough Ether paid");
address payable seller = payable(ticket.ownerOf(_tokenID));
//Safe transfer event, will only work if seller has approved transfer for ticket owner which should be this contract.
ticket.safeTransferFrom(ticket.ownerOf(_tokenID), msg.sender, _tokenID);
seller.transfer(msg.value);
}
}
|
import files import "./Seat.sol"; deprecated import "@bokkypoobah/BokkyPooBahsDateTimeLibrary/contracts/BokkyPooBahsDateTimeLibrary.sol";
|
import "./Ticket.sol";
| 1,054,438 |
[
1,
5666,
1390,
1930,
25165,
1761,
270,
18,
18281,
14432,
6849,
1930,
8787,
70,
601,
79,
879,
83,
947,
9795,
19,
38,
601,
18465,
52,
5161,
38,
69,
4487,
5096,
9313,
19,
16351,
87,
19,
38,
601,
18465,
52,
5161,
38,
69,
4487,
5096,
9313,
18,
18281,
14432,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5666,
25165,
13614,
18,
18281,
14432,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xBB8F3F39B86D4e326A1C6e90e6FceED36EF03329/sources/BUNNYGIRLS.sol
|
* @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. See {_mint}./
|
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return
_startTokenId() <= tokenId &&
}
| 2,812,763 |
[
1,
1356,
2856,
296,
2316,
548,
11,
1704,
18,
13899,
848,
506,
7016,
635,
3675,
3410,
578,
20412,
9484,
3970,
288,
12908,
537,
97,
578,
288,
542,
23461,
1290,
1595,
5496,
13899,
787,
2062,
1347,
2898,
854,
312,
474,
329,
18,
2164,
288,
67,
81,
474,
5496,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
3639,
445,
389,
1808,
12,
11890,
5034,
1147,
548,
13,
2713,
1476,
5024,
1135,
261,
6430,
13,
288,
203,
5411,
327,
203,
7734,
389,
1937,
1345,
548,
1435,
1648,
1147,
548,
597,
203,
3639,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.